Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format nested list on paste #69

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 71 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,9 @@ export default class NestedList {
onPaste(event) {
const list = event.detail.data;

this.data = this.pasteHandler(list);
const formattedList = this.formatNestedListOnPaste(list);

this.data = this.pasteHandler(formattedList);

// render new list
const oldView = this.nodes.wrapper;
Expand Down Expand Up @@ -253,6 +255,74 @@ export default class NestedList {
return data;
}

/**
* Method to fix some pasted nested list
* If the nested list is not well formatted, it will fix it. This can happens when copy paste form word
* Input :
* <ul>
* <li>Coffee</li>
* <li>Tea</li>
* <ul>
* <li>Black tea</li>
* </ul>
* </ul>
* Output :
* <ul>
* <li>Coffee</li>
* <li>Tea
* <ul>
* <li>Black tea</li>
* </ul>
* </li>
* </ul>
* @param {HTMLUListElement|HTMLOListElement|HTMLLIElement} ulElement
* @returns {HTMLUListElement|HTMLOListElement|HTMLLIElement}
*/
formatNestedListOnPaste(ulElement) {
// set list style and tag to search.
let tagToSearch;
let tagName;

switch (ulElement?.tagName) {
case 'OL':
tagToSearch = 'ol';
tagName = 'OL';
break;
case 'UL':
case 'LI':
tagToSearch = 'ul';
tagName = 'UL';
}


for (let i = 0; i < ulElement.children.length; i++) {
const child = ulElement.children[i];

if (child.tagName === tagName) {
// call recursively the function to fix the nested list
this.formatNestedListOnPaste(child);
// move the ul inside the previous li
const li = ulElement.children[i - 1];

li.appendChild(child);
continue;
}

if (child.tagName === 'LI') {
const ul = child.querySelector(tagToSearch);

if (ul) {
// call recursively the function to fix the nested list
const fixedUl = this.formatNestedListOnPaste(ul);

child.appendChild(fixedUl);
}
}
}

return ulElement;
}

/**
* Renders children list
*
Expand Down