Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created March 16, 2016 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/56aa597111f2d6bb926f to your computer and use it in GitHub Desktop.
Save mindplay-dk/56aa597111f2d6bb926f to your computer and use it in GitHub Desktop.
/**
* Automatically create ordered/unordered lists when detecting content like "* " or "1. "
*/
define(function () {
"use strict";
return function () {
return function (scribe) {
/**
* @param {Node} textNode - TextNode being replaced
* @param {string} type - one of "UL" or "OL"
*/
function create_list(textNode, type) {
scribe.transactionManager.run(function () {
var list = document.createElement(type);
var item = document.createElement("LI");
list.appendChild(item);
var parent = textNode.parentNode;
if (parent.nodeName === "LI") {
var sibling = parent.previousElementSibling;
if (sibling.nodeName === "LI") {
sibling.appendChild(list); // append created <ul> or <ol> to previous <li> tag
parent.remove(); // discard extraneous <li>
textNode.remove(); // discard replaced text-node
}
} else {
parent.parentNode.replaceChild(list, parent); // replace parent <p> with created <ul> or <ol>
}
});
}
scribe.el.addEventListener("keyup", function (event) {
var selection = new scribe.api.Selection();
if (!selection.range.collapsed) {
return;
}
var node = selection.range.startContainer;
var parent = node.parentNode;
if (node.nodeType === Node.TEXT_NODE && parent.childNodes.length === 1 && /^P|LI$/.test(parent.nodeName)) {
if (/^\*\s$/.test(node.nodeValue)) {
create_list(node, "UL");
} else if (/^1\.\s$/.test(node.nodeValue)) {
create_list(node, "OL");
}
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment