Created
March 16, 2016 13:02
-
-
Save mindplay-dk/56aa597111f2d6bb926f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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