From 73c71ae690ec10cde1b919781844a0afdb404d34 Mon Sep 17 00:00:00 2001 From: Taly Date: Fri, 21 Jan 2022 18:34:40 +0300 Subject: [PATCH] split list feature resolves #30 --- src/index.js | 107 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 101 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index 2aa6ff69..adb967c0 100644 --- a/src/index.js +++ b/src/index.js @@ -412,15 +412,48 @@ export default class NestedList { const isEmpty = this.getItemContent(currentItem).trim().length === 0; const isFirstLevelItem = currentItem.parentNode === this.nodes.wrapper; const isLastItem = currentItem.nextElementSibling === null; + const haveNoChilds = !currentItem.querySelector(`.${this.CSS.itemChildren}`); - if (isFirstLevelItem && isLastItem && isEmpty) { - this.getOutOfList(); + if (isEmpty && haveNoChilds) { + /** + * Get out of list + * + * 1. first item 1. first item + * 2. second item => 2. second item + * 3. | | + */ + if (isFirstLevelItem && isLastItem) { + this.getOutOfList(); - return; - } else if (isLastItem && isEmpty) { - this.unshiftItem(); + return; + } - return; + + /** + * Split list into two lists + * + * 1. first item 1. first item + * 2. | => | + * 3. third item 1. third item + */ + if (isFirstLevelItem) { + this.splitList(); + + return; + } + + /** + * Unshift item + * + * 1. first item 1. first item + * 2. second item => 2. second item + * 2.1. |child item 3. child item + */ + if (isLastItem) { + this.unshiftItem(); + + return; + } } /** @@ -530,6 +563,68 @@ export default class NestedList { this.api.caret.setToBlock(this.api.blocks.getCurrentBlockIndex()); } + /** + * Split list by Enter on the empty first-level non-last item + * + * @returns {void} + */ + splitList() { + /** + * Get current item + * @type {Element} + */ + const currentItem = this.currentItem; + + /** + * Get first-level list parent item wrapper + */ + const parentItem = currentItem.parentNode.closest(`.${this.CSS.wrapper}`); + + /** + * Get first-leveled items + */ + const parentChildrenList = Array.from(parentItem.querySelectorAll(`:scope > .${this.CSS.item}`)); + + /** + * Detect currentItem position + */ + const currentItemPosition = parentChildrenList.indexOf(currentItem); + + /** + * Get list of items to be moved to the new block + */ + const childsToBeMoved = parentChildrenList.slice(currentItemPosition + 1); + + /** + * Get raw data for this list + * @type {ListData} + */ + const rawData = this.save(); + + /** + * Remove first items and current item from data + * @type {ListItem[]} + */ + rawData.items = rawData.items.slice(currentItemPosition + 1); + + /** + * Remove childs from current list + */ + childsToBeMoved.forEach(item => { + item.remove(); + }) + + /** + * Remove current item, create an empty paragraph and focus it + */ + this.getOutOfList(); + + /** + * Create a new list with saved data + */ + this.api.blocks.insert('nestedList', rawData); // @todo: get tool name from variable + } + /** * Handle backspace *