Consider list edge case for line breaks

* Enter makes a new bullet point
* Shift+Enter makes a line break in current bullet point
This commit is contained in:
Henrik Giesel 2021-01-14 18:59:07 +01:00
parent 5c6694950d
commit 4e1139021b

View File

@ -56,7 +56,8 @@ function onKey(evt: KeyboardEvent) {
} }
// prefer <br> instead of <div></div> // prefer <br> instead of <div></div>
if (evt.which === 13) { if (evt.which === 13 && !inListItem()) {
console.log("Enter");
evt.preventDefault(); evt.preventDefault();
document.execCommand("insertLineBreak"); document.execCommand("insertLineBreak");
return; return;
@ -87,6 +88,25 @@ function onKey(evt: KeyboardEvent) {
triggerKeyTimer(); triggerKeyTimer();
} }
function nodeIsElement(node: Node): node is Element {
return node.nodeType == Node.ELEMENT_NODE;
}
function inListItem(): boolean {
const anchor = window.getSelection().anchorNode;
let n = nodeIsElement(anchor) ? anchor : anchor.parentElement;
let inList = false;
while (n) {
inList = inList || window.getComputedStyle(n).display == "list-item";
n = n.parentElement;
}
return inList;
}
function insertNewline() { function insertNewline() {
if (!inPreEnvironment()) { if (!inPreEnvironment()) {
setFormat("insertText", "\n"); setFormat("insertText", "\n");
@ -113,11 +133,10 @@ function insertNewline() {
} }
// is the cursor in an environment that respects whitespace? // is the cursor in an environment that respects whitespace?
function inPreEnvironment() { function inPreEnvironment(): boolean {
let n = window.getSelection().anchorNode as Element; const anchor = window.getSelection().anchorNode;
if (n.nodeType === 3) { const n = nodeIsElement(anchor) ? anchor : anchor.parentElement;
n = n.parentNode as Element;
}
return window.getComputedStyle(n).whiteSpace.startsWith("pre"); return window.getComputedStyle(n).whiteSpace.startsWith("pre");
} }