Skip to content

Commit

Permalink
fix: remove newlines in copied text when pasting to table (fix #1102) (
Browse files Browse the repository at this point in the history
…#1100)

* fix: paste text including newlines to table

* feat: move function to util module

* feat: apply code review
  • Loading branch information
seonim-ryu authored Jul 16, 2020
1 parent 48d94da commit f98ffc4
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
28 changes: 26 additions & 2 deletions apps/editor/src/js/utils/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -1301,7 +1301,7 @@ const toggleClass = (element, className, state) => {
* @param {HTMLElement} html root element
* @param {boolean} needHtmlText pass true if need html text
* @returns {string|DocumentFragment} result
* @private
* @ignore
*/
function finalizeHtml(html, needHtmlText) {
let result;
Expand All @@ -1322,6 +1322,29 @@ function finalizeHtml(html, needHtmlText) {
return result;
}

/**
* Get fragment replaced by newline to br tag
* @param {string} text original text
* @returns {DocumentFragment} fragment
* @ignore
*/
function getFragmentReplacedByNewlineToBr(text) {
const fragment = document.createDocumentFragment();
const texts = text.split('\n');

texts.forEach((plainText, index) => {
const textNode = document.createTextNode(plainText);

fragment.appendChild(textNode);

if (index < texts.length - 1) {
fragment.appendChild(document.createElement('br'));
}
});

return fragment;
}

export default {
getNodeName,
isTextNode,
Expand Down Expand Up @@ -1388,5 +1411,6 @@ export default {
getOuterWidth,
getOuterHeight,
toggleClass,
finalizeHtml
finalizeHtml,
getFragmentReplacedByNewlineToBr
};
4 changes: 3 additions & 1 deletion apps/editor/src/js/wwTablePasteHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ class WwTablePasteHelper {
});
} else if (textItem) {
textItem.getAsString(text => {
this._pasteClipboardContainer(document.createTextNode(text));
const fragment = domUtils.getFragmentReplacedByNewlineToBr(text);

this._pasteClipboardContainer(fragment);
});
}
}
Expand Down
9 changes: 9 additions & 0 deletions apps/editor/test/unit/utils/dom.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -951,4 +951,13 @@ describe('domUtils', () => {
expect(target.className).toBe('test');
});
});

it('getFragmentReplacedByNewlineToBr() returns fragment replaced by newline to br', () => {
const result = domUtils.getFragmentReplacedByNewlineToBr('foo\nbar\nbaz');
const div = document.createElement('div');

div.appendChild(result.cloneNode(true));

expect(div.innerHTML).toBe('foo<br>bar<br>baz');
});
});

0 comments on commit f98ffc4

Please sign in to comment.