A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
editor: improve copy pasting
Abdullah Atta5810947a5d25
diff --git a/packages/editor/src/extensions/clipboard-text-serializer/index.ts b/packages/editor/src/extensions/clipboard-text-serializer/index.tsindex b5d2c1802..4bb6fdecf 100644--- a/packages/editor/src/extensions/clipboard-text-serializer/index.ts+++ b/packages/editor/src/extensions/clipboard-text-serializer/index.ts@@ -19,7 +19,46 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Extension, TextSerializer } from "@tiptap/core";import { Plugin, PluginKey } from "prosemirror-state";-import { Schema, Slice } from "prosemirror-model";+import { Fragment, Schema, Slice } from "prosemirror-model";+import { ListItem } from "../list-item";+import { LIST_NODE_TYPES } from "../../utils/node-types";+import { DOMSerializer } from "@tiptap/pm/model";++export class ClipboardDOMSerializer extends DOMSerializer {+ static fromSchema(schema: Schema): ClipboardDOMSerializer {+ return (+ schema.cached.domSerializer2 ||+ (schema.cached.domSerializer2 = new ClipboardDOMSerializer(+ this.nodesFromSchema(schema),+ this.marksFromSchema(schema)+ ))+ );+ }++ serializeFragment(+ fragment: Fragment,+ options?: { document?: Document | undefined } | undefined,+ target?: HTMLElement | DocumentFragment | undefined+ ): HTMLElement | DocumentFragment {+ const dom = super.serializeFragment(fragment, options, target);+ for (const p of dom.querySelectorAll("li > p")) {+ if (p.parentElement && p.parentElement.childElementCount > 1) continue;+ p.parentElement?.append(...p.childNodes);+ p.remove();+ }++ for (const p of dom.querySelectorAll('p[data-spacing="single"]')) {+ if (!p.previousElementSibling || p.previousElementSibling.tagName !== "P")+ continue;+ if (p.previousElementSibling.childNodes.length > 0)+ p.previousElementSibling.appendChild(document.createElement("br"));+ p.previousElementSibling.append(...p.childNodes);+ p.remove();+ }++ return dom;+ }+}export const ClipboardTextSerializer = Extension.create({name: "clipboardTextSerializer",@@ -29,8 +68,12 @@ export const ClipboardTextSerializer = Extension.create({new Plugin({key: new PluginKey("clipboardTextSerializer"),props: {- clipboardTextSerializer: (content) => {- return getTextBetween(content, this.editor.schema);+ transformCopied,+ clipboardSerializer: ClipboardDOMSerializer.fromSchema(+ this.editor.view.state.schema+ ),+ clipboardTextSerializer: (content, view) => {+ return getTextBetween(content, view.state.schema);}}})@@ -38,7 +81,22 @@ export const ClipboardTextSerializer = Extension.create({}});-function getTextBetween(slice: Slice, schema: Schema): string {+export function transformCopied(slice: Slice) {+ // when copying a single list item, we shouldn't retain the+ // list formatting but copy it as a paragraph.+ const maybeList = slice.content.firstChild;+ if (+ maybeList &&+ LIST_NODE_TYPES.includes(maybeList.type.name) &&+ maybeList.childCount === 1 &&+ maybeList.firstChild+ ) {+ return new Slice(maybeList.firstChild.content, 0, 0);+ }+ return slice;+}++export function getTextBetween(slice: Slice, schema: Schema): string {const range = { from: 0, to: slice.size };const separator = "\n";let text = "";@@ -50,7 +108,6 @@ function getTextBetween(slice: Slice, schema: Schema): string {if (textSerializer) {if (node.isBlock && !separated) {- console.log("ADDING separator");text += separator;separated = true;}@@ -68,7 +125,12 @@ function getTextBetween(slice: Slice, schema: Schema): string {text += node?.text;separated = false;} else if (node.isBlock && !!text) {+ // we don't want double spaced list items when pasting+ if (index === 0 && parent?.type.name === ListItem.name) return;+text += separator;+ if (node.attrs.spacing === "double" && node.childCount > 0)+ text += separator;separated = true;}});diff --git a/packages/editor/src/extensions/clipboard-text-serializer/tests/__snapshots__/clipboard-text-serializer.test.ts.snap b/packages/editor/src/extensions/clipboard-text-serializer/tests/__snapshots__/clipboard-text-serializer.test.ts.snapnew file mode 100644index 000000000..add52d2b6--- /dev/null+++ b/packages/editor/src/extensions/clipboard-text-serializer/tests/__snapshots__/clipboard-text-serializer.test.ts.snap@@ -0,0 +1,17 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`copying a single list item shouldn't copy the list metadata 1`] = `+{+ "content": [+ {+ "content": [+ {+ "text": "Hello",+ "type": "text",+ },+ ],+ "type": "paragraph",+ },+ ],+}+`;diff --git a/packages/editor/src/extensions/clipboard-text-serializer/tests/clipboard-text-serializer.test.ts b/packages/editor/src/extensions/clipboard-text-serializer/tests/clipboard-text-serializer.test.tsnew file mode 100644index 000000000..8b9f741ef--- /dev/null+++ b/packages/editor/src/extensions/clipboard-text-serializer/tests/clipboard-text-serializer.test.ts@@ -0,0 +1,172 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { test } from "vitest";+import { createEditor, h } from "../../../../test-utils";+import OrderedList from "../../ordered-list";+import { ListItem } from "../../list-item";+import { getTextBetween, transformCopied, DOMSerializer2 } from "../index";+import { Paragraph } from "../../paragraph";++test("copied list items shouldn't contain extra newlines", (t) => {+ const { editor } = createEditor({+ initialContent: h("div", [+ h("ol", [+ h("li", [+ h("p", ["This is line: ", h("em", ["number 1."])]),+ h("p", ["And this is line number 2."])+ ]),+ h("li", [h("p", ["This is line number 3."])])+ ])+ ]).innerHTML,+ extensions: {+ orderedList: OrderedList,+ listItem: ListItem+ }+ });++ const serializer = DOMSerializer2.fromSchema(editor.view.state.schema);+ t.expect(+ new XMLSerializer().serializeToString(+ serializer.serializeFragment(+ editor.state.doc.slice(0, editor.state.doc.nodeSize - 2).content+ )+ )+ ).toBe(+ "<ol><li><p>This is line: <em>number 1.</em></p><p>And this is line number 2.</p></li><li>This is line number 3.</li></ol>"+ );++ t.expect(+ getTextBetween(+ editor.state.doc.slice(0, editor.state.doc.nodeSize - 2),+ editor.schema+ )+ ).toBe(`This is line: number 1.+And this is line number 2.+This is line number 3.`);+});++test("copying a single list item shouldn't copy the list metadata", (t) => {+ const { editor } = createEditor({+ initialContent: h("div", [h("ol", [h("li", ["Hello"])])]).innerHTML,+ extensions: {+ orderedList: OrderedList,+ listItem: ListItem+ }+ });++ t.expect(+ transformCopied(+ editor.state.doc.slice(0, editor.state.doc.nodeSize - 2)+ ).toJSON()+ ).toMatchSnapshot();+});++const createParagraphs = (spacing: "double" | "single") => [+ h("p", ["I am paragraph 1."], { "data-spacing": spacing }),+ h("p", ["I am paragraph 2."], { "data-spacing": spacing }),+ h("p", ["I am paragraph 3."], { "data-spacing": spacing })+];++const createParagraphsWithSpaces = (spacing: "double" | "single") => [+ h("p", ["I am paragraph 1."], { "data-spacing": spacing }),+ h("p", [h("br")], { "data-spacing": spacing }),+ h("p", [h("br")], { "data-spacing": spacing }),+ h("p", ["I am paragraph 2."], { "data-spacing": spacing }),+ h("p", [h("br")], { "data-spacing": spacing }),+ h("p", [h("br")], { "data-spacing": spacing }),+ h("p", ["I am paragraph 3."], { "data-spacing": spacing })+];++const paragraphTestCases = [+ {+ spacing: "double",+ content: createParagraphs("double"),+ expectedHtml: `<p data-spacing="double">I am paragraph 1.</p><p data-spacing="double">I am paragraph 2.</p><p data-spacing="double">I am paragraph 3.</p>`,+ expectedText: `I am paragraph 1.\n\nI am paragraph 2.\n\nI am paragraph 3.`+ },+ {+ spacing: "single",+ content: createParagraphs("single"),+ expectedHtml: `<p data-spacing="single">I am paragraph 1.<br>I am paragraph 2.<br>I am paragraph 3.</p>`,+ expectedText: `I am paragraph 1.\nI am paragraph 2.\nI am paragraph 3.`+ },+ {+ spacing: "double",+ content: createParagraphsWithSpaces("double"),+ expectedHtml: `<p data-spacing="double">I am paragraph 1.</p><p data-spacing="double"></p><p data-spacing="double"></p><p data-spacing="double">I am paragraph 2.</p><p data-spacing="double"></p><p data-spacing="double"></p><p data-spacing="double">I am paragraph 3.</p>`,+ expectedText: `I am paragraph 1.\n\n\n\nI am paragraph 2.\n\n\n\nI am paragraph 3.`+ },+ {+ spacing: "single",+ content: createParagraphsWithSpaces("single"),+ expectedHtml: `<p data-spacing="single">I am paragraph 1.<br><br><br>I am paragraph 2.<br><br><br>I am paragraph 3.</p>`,+ expectedText: `I am paragraph 1.\n\n\nI am paragraph 2.\n\n\nI am paragraph 3.`+ },+ {+ spacing: "mixed",+ content: [+ ...createParagraphs("double"),+ ...createParagraphs("single"),+ ...createParagraphs("double")+ ],+ expectedHtml: `<p data-spacing="double">I am paragraph 1.</p><p data-spacing="double">I am paragraph 2.</p><p data-spacing="double">I am paragraph 3.<br>I am paragraph 1.<br>I am paragraph 2.<br>I am paragraph 3.</p><p data-spacing="double">I am paragraph 1.</p><p data-spacing="double">I am paragraph 2.</p><p data-spacing="double">I am paragraph 3.</p>`,+ expectedText: `I am paragraph 1.\n\nI am paragraph 2.\n\nI am paragraph 3.\nI am paragraph 1.\nI am paragraph 2.\nI am paragraph 3.\n\nI am paragraph 1.\n\nI am paragraph 2.\n\nI am paragraph 3.`+ },+ {+ spacing: "mixed 2",+ content: [+ h("p", ["I am paragraph 1."], { "data-spacing": "double" }),+ h("p", ["I am paragraph 2."], { "data-spacing": "single" }),+ h("p", ["I am paragraph 3."], { "data-spacing": "double" }),+ h("p", ["I am paragraph 4."], { "data-spacing": "single" }),+ h("p", ["I am paragraph 5."], { "data-spacing": "single" }),+ h("p", ["I am paragraph 6."], { "data-spacing": "double" })+ ],+ expectedHtml: `<p data-spacing="double">I am paragraph 1.<br>I am paragraph 2.</p><p data-spacing="double">I am paragraph 3.<br>I am paragraph 4.<br>I am paragraph 5.</p><p data-spacing="double">I am paragraph 6.</p>`,+ expectedText: `I am paragraph 1.\nI am paragraph 2.\n\nI am paragraph 3.\nI am paragraph 4.\nI am paragraph 5.\n\nI am paragraph 6.`+ }+];+for (const testCase of paragraphTestCases) {+ test(`copying should respect paragraph spacing (${testCase.spacing})`, (t) => {+ const { editor } = createEditor({+ initialContent: h("div", testCase.content).innerHTML,+ extensions: {+ paragraph: Paragraph,+ hardBreak: false+ }+ });++ const serializer = DOMSerializer2.fromSchema(editor.view.state.schema);+ t.expect(+ new XMLSerializer().serializeToString(+ serializer.serializeFragment(+ editor.state.doc.slice(0, editor.state.doc.nodeSize - 2).content+ )+ )+ ).toBe(testCase.expectedHtml);++ t.expect(+ getTextBetween(+ editor.state.doc.slice(0, editor.state.doc.nodeSize - 2),+ editor.schema+ )+ ).toBe(testCase.expectedText);+ });+}diff --git a/packages/editor/src/utils/html.ts b/packages/editor/src/utils/html.tsindex 96c116731..7129d7ce9 100644--- a/packages/editor/src/utils/html.ts+++ b/packages/editor/src/utils/html.ts@@ -18,16 +18,28 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/export function convertBrToParagraph(html: string) {- const doc = new DOMParser().parseFromString(html, "text/html");+ const doc = new DOMParser().parseFromString(+ convertNewlinesToBr(html),+ "text/html"+ );for (const br of doc.querySelectorAll("br")) {- const paragraph = br.closest("p");+ let paragraph = br.closest("p");++ // if no paragraph is found over the br, we add one.+ if (!paragraph && br.parentElement) {+ const parent = br.parentElement;+ const p = document.createElement("p");+ p.append(...parent.childNodes);+ parent.append(p);+ paragraph = p;+ }+if (paragraph && paragraph.childNodes.length === 1) continue;if (paragraph) {splitOn(paragraph, br);const children = Array.from(paragraph.childNodes.values());const newParagraph = doc.createElement("p");newParagraph.dataset.spacing = "single";- paragraph.dataset.spacing = "single";newParagraph.append(...children.slice(children.indexOf(br) + 1));paragraph.insertAdjacentElement("afterend", newParagraph);br.remove();@@ -52,3 +64,12 @@ function splitOn(bound: Element, cutElement: Element) {}}}++function convertNewlinesToBr(html: string) {+ const lines = html.split(/\n/gm);+ for (let i = 0; i < lines.length; ++i) {+ if (lines[i].trim().endsWith(">")) continue;+ lines[i] += "<br>";+ }+ return lines.join("");+}diff --git a/packages/editor/src/utils/tests/__snapshots__/html.test.ts.snap b/packages/editor/src/utils/tests/__snapshots__/html.test.ts.snapnew file mode 100644index 000000000..73d3cbdbd--- /dev/null+++ b/packages/editor/src/utils/tests/__snapshots__/html.test.ts.snap@@ -0,0 +1,45 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`convert br tags to paragraphs (+ <html><body>+<!--StartFragment-->A troll, they call me, but I have no wish<br>+to be associated with those dolls<br>+<br>+We lack religion, purpose, politics,<br>+and yet, we somehow manage to get by.<br>+</body>+</html>) 1`] = `"<p><!--StartFragment-->A troll, they call me, but I have no wish</p><p data-spacing=\\"single\\">to be associated with those dolls</p><p data-spacing=\\"single\\"></p><p data-spacing=\\"single\\">We lack religion, purpose, politics,</p><p data-spacing=\\"single\\">and yet, we somehow manage to get by.</p><p data-spacing=\\"single\\"></p><p data-spacing=\\"single\\"> </p>"`;++exports[`convert br tags to paragraphs (<html><body>+ <!--StartFragment--><p dir="auto">When I try to paste something (e.g. email content) to a note, the styling is kept, which is good, but the newlines are removed.<br>+ Also when I share the selection to Notesnook via the share functionality from Android, I have the same issue.</p>+ <hr>+ <p dir="auto"><strong>Device information:</strong><br>+ App version: 2.3.0<br>+ Platform: android<br>+ Model: OnePlus-CPH2409-31<br>+ Pro: true<br>+ Logged in: yes</p><!--EndFragment-->+ </body>+ </html>) 1`] = `"<!--StartFragment--><p dir=\\"auto\\">When I try to paste something (e.g. email content) to a note, the styling is kept, which is good, but the newlines are removed.</p><p data-spacing=\\"single\\"> Also when I share the selection to Notesnook via the share functionality from Android, I have the same issue.</p> <hr> <p dir=\\"auto\\"><strong>Device information:</strong></p><p data-spacing=\\"single\\"> App version: 2.3.0</p><p data-spacing=\\"single\\"> Platform: android</p><p data-spacing=\\"single\\"> Model: OnePlus-CPH2409-31</p><p data-spacing=\\"single\\"> Pro: true</p><p data-spacing=\\"single\\"> Logged in: yes</p><!--EndFragment-->"`;++exports[`convert br tags to paragraphs (<html><body>+ <!--StartFragment--><span class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0">Why switch from Gmail?++ Not sacrificing features for more privacy, prefer using one app, in many public groups and channels (Telegram)++ LibreOffice Slow & buggy++ Switched to Brave for the better Android app, more private out of the box & unsure if uBlock Origin closes gap</span><!--EndFragment-->+ </body>+ </html>) 1`] = `"<!--StartFragment--><span class=\\"css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0\\"><p>Why switch from Gmail? </p><p data-spacing=\\"single\\"></p><p data-spacing=\\"single\\"> Not sacrificing features for more privacy, prefer using one app, in many public groups and channels (Telegram)</p><p data-spacing=\\"single\\"> </p><p data-spacing=\\"single\\"> LibreOffice Slow & buggy</p><p data-spacing=\\"single\\"> </p><p data-spacing=\\"single\\"> Switched to Brave for the better Android app, more private out of the box & unsure if uBlock Origin closes gap</p></span><!--EndFragment-->"`;++exports[`convert br tags to paragraphs (<p><br/></p>) 1`] = `"<p><br></p>"`;++exports[`convert br tags to paragraphs (<p>line <em>1<br>line</em> 2</p>) 1`] = `"<p>line <em>1</em></p><p data-spacing=\\"single\\"><em>line</em> 2</p>"`;++exports[`convert br tags to paragraphs (<p>line <span><em>1<br data-some="hello">line</em></span> 2</p>) 1`] = `"<p>line <span><em>1</em></span></p><p data-spacing=\\"single\\"><span><em>line</em></span> 2</p>"`;++exports[`convert br tags to paragraphs (<p>line <span><em>1<br>line</em></span> 2</p>) 1`] = `"<p>line <span><em>1</em></span></p><p data-spacing=\\"single\\"><span><em>line</em></span> 2</p>"`;++exports[`convert br tags to paragraphs (<p>line 1<br>line 2</p>) 1`] = `"<p>line 1</p><p data-spacing=\\"single\\">line 2</p>"`;diff --git a/packages/editor/src/utils/tests/html.test.ts b/packages/editor/src/utils/tests/html.test.tsindex 34df53cab..2fb22f45c 100644--- a/packages/editor/src/utils/tests/html.test.ts+++ b/packages/editor/src/utils/tests/html.test.ts@@ -21,23 +21,22 @@ import { test } from "vitest";import { convertBrToParagraph } from "../html";const cases = [+ [`<p>line 1<br>line 2</p>`],+ [`<p>line <em>1<br>line</em> 2</p>`],+ [`<p>line <span><em>1<br>line</em></span> 2</p>`],+ [`<p>line <span><em>1<br data-some="hello">line</em></span> 2</p>`],+ [`<p><br/></p>`],[- `<p>line 1<br>line 2</p>`,- `<p data-spacing="single">line 1</p><p data-spacing="single">line 2</p>`+ `+ <html><body>+<!--StartFragment-->A troll, they call me, but I have no wish<br>+to be associated with those dolls<br>+<br>+We lack religion, purpose, politics,<br>+and yet, we somehow manage to get by.<br>+</body>+</html>`],- [- `<p>line <em>1<br>line</em> 2</p>`,- `<p data-spacing="single">line <em>1</em></p><p data-spacing="single"><em>line</em> 2</p>`- ],- [- `<p>line <span><em>1<br>line</em></span> 2</p>`,- `<p data-spacing="single">line <span><em>1</em></span></p><p data-spacing="single"><span><em>line</em></span> 2</p>`- ],- [- `<p>line <span><em>1<br data-some="hello">line</em></span> 2</p>`,- `<p data-spacing="single">line <span><em>1</em></span></p><p data-spacing="single"><span><em>line</em></span> 2</p>`- ],- [`<p><br/></p>`, `<p><br></p>`],[`<html><body><!--StartFragment--><p dir="auto">When I try to paste something (e.g. email content) to a note, the styling is kept, which is good, but the newlines are removed.<br>@@ -50,24 +49,27 @@ const cases = [Pro: true<br>Logged in: yes</p><!--EndFragment--></body>- </html>`,- `<!--StartFragment--><p dir="auto" data-spacing="single">When I try to paste something (e.g. email content) to a note, the styling is kept, which is good, but the newlines are removed.</p><p data-spacing="single">- Also when I share the selection to Notesnook via the share functionality from Android, I have the same issue.</p>- <hr>- <p dir="auto" data-spacing="single"><strong>Device information:</strong></p><p data-spacing="single">- App version: 2.3.0</p><p data-spacing="single">- Platform: android</p><p data-spacing="single">- Model: OnePlus-CPH2409-31</p><p data-spacing="single">- Pro: true</p><p data-spacing="single">- Logged in: yes</p><!--EndFragment-->`+ </html>`+ ],+ [+ `<html><body>+ <!--StartFragment--><span class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0">Why switch from Gmail?++ Not sacrificing features for more privacy, prefer using one app, in many public groups and channels (Telegram)++ LibreOffice Slow & buggy++ Switched to Brave for the better Android app, more private out of the box & unsure if uBlock Origin closes gap</span><!--EndFragment-->+ </body>+ </html>`]];for (const testCase of cases) {const [html, expected] = testCase;test(`convert br tags to paragraphs (${testCase})`, (t) => {- t.expect(convertBrToParagraph(html).body.innerHTML.trim()).toBe(- expected.trim()- );+ t.expect(+ convertBrToParagraph(html).body.innerHTML.trim()+ ).toMatchSnapshot();});}diff --git a/packages/editor/test-utils/index.ts b/packages/editor/test-utils/index.tsindex b26392b71..bd9f0aeee 100644--- a/packages/editor/test-utils/index.ts+++ b/packages/editor/test-utils/index.ts@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { Editor, AnyExtension, Extensions } from "@tiptap/core";-import StarterKit from "@tiptap/starter-kit";+import StarterKit, { StarterKitOptions } from "@tiptap/starter-kit";import { builders, NodeBuilder } from "prosemirror-test-builder";import { Schema } from "@tiptap/pm/model";@@ -28,7 +28,7 @@ type Builder<TNodes extends string> = {type EditorOptions<TNodes extends string> = {element?: HTMLElement;- extensions: Record<TNodes, AnyExtension>;+ extensions: Record<TNodes, AnyExtension | false>;initialContent?: string;};@@ -41,11 +41,13 @@ export function createEditor<TNodes extends string>(content: initialContent,extensions: [StarterKit.configure({- bulletList: false,- listItem: false,- orderedList: false,- codeBlock: false,- code: false+ ...Object.entries(extensions).reduce(+ (prev, [name]) => ({+ ...prev,+ [name]: false+ }),+ {}+ )}),...(Object.values(extensions) as Extensions)]