Skip to content

Commit

Permalink
simplify whitespace handling and remove redundancy
Browse files Browse the repository at this point in the history
  • Loading branch information
jhchen committed Nov 26, 2024
1 parent e7a3bfd commit 2e48505
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions packages/quill/src/modules/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,9 +624,6 @@ function matchTable(
return delta;
}

const NBSP = '\u00a0';
const SPACE_EXCLUDE_NBSP = `[^\\S${NBSP}]`;

function matchText(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {
// @ts-expect-error
let text = node.data as string;
Expand All @@ -642,26 +639,31 @@ function matchText(node: HTMLElement, delta: Delta, scroll: ScrollBlot) {
) {
return delta;
}
text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
text = text.replace(new RegExp(`${SPACE_EXCLUDE_NBSP}{2,}`, 'g'), ' '); // collapse whitespace
// convert all non-nbsp whitespace into regular space
text = text.replace(/[^\S\u00a0]/g, ' ');
// collapse consecutive spaces into one
text = text.replace(/ {2,}/g, ' ');
if (
(node.previousSibling == null &&
node.parentElement != null &&
isLine(node.parentElement, scroll)) ||
(node.previousSibling instanceof Element &&
isLine(node.previousSibling, scroll))
) {
text = text.replace(new RegExp(`^${SPACE_EXCLUDE_NBSP}+`), '');
// block structure means we don't need leading space
text = text.replace(/^ /, '');
}
if (
(node.nextSibling == null &&
node.parentElement != null &&
isLine(node.parentElement, scroll)) ||
(node.nextSibling instanceof Element && isLine(node.nextSibling, scroll))
) {
text = text.replace(new RegExp(`${SPACE_EXCLUDE_NBSP}+$`), '');
// block structure means we don't even need trailing space
text = text.replace(/ $/, '');
}
text = text.replaceAll(NBSP, ' ');
// done removing whitespace and can normalize all to regular space
text = text.replaceAll('\u00a0', ' ');
}
return delta.insert(text);
}
Expand Down

0 comments on commit 2e48505

Please sign in to comment.