Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

editor: use dom parser to convert br to p tags

alihamuh083f14bf50b3
diff --git a/packages/editor/src/extensions/text-direction/text-direction.ts b/packages/editor/src/extensions/text-direction/text-direction.ts
index 0f758e7a5..53f6c0c12 100644
--- a/packages/editor/src/extensions/text-direction/text-direction.ts
+++ b/packages/editor/src/extensions/text-direction/text-direction.ts
@@ -89,10 +89,13 @@ export const TextDirection = Extension.create<TextDirectionOptions>({
// NOTE: for some reason setting this to undefined breaks enter behaviour
// on Android for some keyboards (GBoard etc.). Empty string works fine.
default: this.options.defaultDirection || "",
- parseHTML: (element) => element.dir,
+ parseHTML: (element) => (element.dir === "rtl" ? "rtl" : undefined),
keepOnSplit: true,
renderHTML: (attributes) => {
- if (!attributes.textDirection) {
+ if (
+ !attributes.textDirection ||
+ attributes.textDirection !== "rtl"
+ ) {
return {};
}
diff --git a/packages/editor/src/index.ts b/packages/editor/src/index.ts
index 880e7c207..5a669d09e 100644
--- a/packages/editor/src/index.ts
+++ b/packages/editor/src/index.ts
@@ -77,6 +77,7 @@ import { useToolbarStore } from "./toolbar/stores/toolbar-store";
import { DownloadOptions } from "./utils/downloader";
import { Heading } from "./extensions/heading";
import Clipboard, { ClipboardOptions } from "./extensions/clipboard";
+import { convertBrToParagraph } from "./utils/html";
declare global {
// eslint-disable-next-line no-var
@@ -125,6 +126,7 @@ const useTiptap = (
dateFormat,
timeFormat,
copyToClipboard,
+ editorProps,
...restOptions
} = options;
const PortalProviderAPI = usePortalProvider();
@@ -146,143 +148,144 @@ const useTiptap = (
}, deps);
const defaultOptions = useMemo<Partial<EditorOptions>>(
- () =>
- ({
- enableCoreExtensions: false,
- extensions: [
- ...CoreExtensions,
- ClipboardTextSerializer,
- NodeViewSelectionNotifier,
- SearchReplace,
- TextStyle.extend({
- parseHTML() {
- return [
- {
- tag: "span",
- getAttrs: (element) => {
- if (!hasStyle(element)) {
- return false;
- }
- return {};
+ () => ({
+ enableCoreExtensions: false,
+ editorProps: {
+ ...editorProps,
+ transformPastedHTML(html) {
+ return convertBrToParagraph(html).documentElement.outerHTML;
+ }
+ },
+ extensions: [
+ ...CoreExtensions,
+ ClipboardTextSerializer,
+ NodeViewSelectionNotifier,
+ SearchReplace,
+ TextStyle.extend({
+ parseHTML() {
+ return [
+ {
+ tag: "span",
+ getAttrs: (element) => {
+ if (!hasStyle(element)) {
+ return false;
}
+ return {};
}
- ];
- }
- }),
- Paragraph.configure({
- doubleSpaced: doubleSpacedLines
- }),
- StarterKit.configure({
- code: false,
- codeBlock: false,
- listItem: false,
- orderedList: false,
- bulletList: false,
- paragraph: false,
- hardBreak: false,
- heading: false,
- history: {
- depth: 200,
- newGroupDelay: 1000
- },
- dropcursor: {
- class: "drop-cursor"
- },
- horizontalRule: false
- }),
- Heading,
- HorizontalRule.extend({
- addInputRules() {
- return [
- {
- find: /^(?:---|—-|___\s|\*\*\*\s)$/,
- handler: ({ state, range, commands }) => {
- commands.splitBlock();
+ }
+ ];
+ }
+ }),
+ Paragraph.configure({
+ doubleSpaced: doubleSpacedLines
+ }),
+ StarterKit.configure({
+ code: false,
+ codeBlock: false,
+ listItem: false,
+ orderedList: false,
+ bulletList: false,
+ paragraph: false,
+ hardBreak: false,
+ heading: false,
+ history: {
+ depth: 200,
+ newGroupDelay: 1000
+ },
+ dropcursor: {
+ class: "drop-cursor"
+ },
+ horizontalRule: false
+ }),
+ Heading,
+ HorizontalRule.extend({
+ addInputRules() {
+ return [
+ {
+ find: /^(?:---|—-|___\s|\*\*\*\s)$/,
+ handler: ({ state, range, commands }) => {
+ commands.splitBlock();
- const attributes = {};
- const { tr } = state;
- const start = range.from;
- const end = range.to;
- tr.replaceWith(
- start - 1,
- end,
- this.type.create(attributes)
- );
- }
+ const attributes = {};
+ const { tr } = state;
+ const start = range.from;
+ const end = range.to;
+ tr.replaceWith(start - 1, end, this.type.create(attributes));
}
- ];
- }
- }),
- CharacterCount,
- Underline,
- Subscript,
- Superscript,
- FontSize,
- TextDirection,
- FontFamily,
- BulletList.configure({ keepMarks: true, keepAttributes: true }),
- OrderedList.configure({ keepMarks: true, keepAttributes: true }),
- TaskItemNode.configure({ nested: true }),
- TaskListNode,
- Link.extend({
- inclusive: true
- }).configure({
- openOnClick: !isMobile,
- autolink: false
- }),
- Table.configure({
- resizable: true,
- allowTableNodeSelection: true,
- cellMinWidth: 50
- }),
- Clipboard.configure({
- copyToClipboard
- }),
- TableRow,
- TableCell,
- TableHeader,
- Highlight,
- CodeBlock,
- Color,
- TextAlign.configure({
- types: ["heading", "paragraph"],
- alignments: ["left", "right", "center", "justify"],
- defaultAlignment: "left"
- }),
- Placeholder.configure({
- placeholder: "Start writing your note..."
- }),
- OpenLink.configure({
- onOpenLink
- }),
- ImageNode.configure({ allowBase64: true }),
- EmbedNode,
- AttachmentNode.configure({
- onDownloadAttachment,
- onOpenAttachmentPicker,
- onPreviewAttachment
- }),
- OutlineListItem,
- OutlineList.configure({ keepAttributes: true, keepMarks: true }),
- ListItem,
- Code.extend({ excludes: "" }),
- Codemark,
- MathInline,
- MathBlock,
- KeepInView.configure({
- scrollIntoViewOnWindowResize: !isMobile
- }),
- DateTime.configure({ dateFormat, timeFormat }),
- KeyMap,
- WebClipNode
- ],
- onBeforeCreate: ({ editor }) => {
- editor.storage.portalProviderAPI = PortalProviderAPI;
- if (onBeforeCreate) onBeforeCreate({ editor });
- },
- injectCSS: false,
- parseOptions: { preserveWhitespace: true }
- } as EditorOptions),
+ }
+ ];
+ }
+ }),
+ CharacterCount,
+ Underline,
+ Subscript,
+ Superscript,
+ FontSize,
+ TextDirection,
+ FontFamily,
+ BulletList.configure({ keepMarks: true, keepAttributes: true }),
+ OrderedList.configure({ keepMarks: true, keepAttributes: true }),
+ TaskItemNode.configure({ nested: true }),
+ TaskListNode,
+ Link.extend({
+ inclusive: true
+ }).configure({
+ openOnClick: !isMobile,
+ autolink: false
+ }),
+ Table.configure({
+ resizable: true,
+ allowTableNodeSelection: true,
+ cellMinWidth: 50
+ }),
+ Clipboard.configure({
+ copyToClipboard
+ }),
+ TableRow,
+ TableCell,
+ TableHeader,
+ Highlight,
+ CodeBlock,
+ Color,
+ TextAlign.configure({
+ types: ["heading", "paragraph"],
+ alignments: ["left", "right", "center", "justify"],
+ defaultAlignment: "left"
+ }),
+ Placeholder.configure({
+ placeholder: "Start writing your note..."
+ }),
+ OpenLink.configure({
+ onOpenLink
+ }),
+ ImageNode.configure({ allowBase64: true }),
+ EmbedNode,
+ AttachmentNode.configure({
+ onDownloadAttachment,
+ onOpenAttachmentPicker,
+ onPreviewAttachment
+ }),
+ OutlineListItem,
+ OutlineList.configure({ keepAttributes: true, keepMarks: true }),
+ ListItem,
+ Code.extend({ excludes: "" }),
+ Codemark,
+ MathInline,
+ MathBlock,
+ KeepInView.configure({
+ scrollIntoViewOnWindowResize: !isMobile
+ }),
+ DateTime.configure({ dateFormat, timeFormat }),
+ KeyMap,
+ WebClipNode
+ ],
+ onBeforeCreate: ({ editor }) => {
+ editor.storage.portalProviderAPI = PortalProviderAPI;
+ if (onBeforeCreate) onBeforeCreate({ editor });
+ },
+ injectCSS: false,
+ parseOptions: { preserveWhitespace: true }
+ }),
[
onPreviewAttachment,
onDownloadAttachment,
@@ -292,6 +295,7 @@ const useTiptap = (
onOpenLink,
dateFormat,
timeFormat,
+ editorProps,
copyToClipboard
]
);
diff --git a/packages/editor/src/utils/html.ts b/packages/editor/src/utils/html.ts
new file mode 100644
index 000000000..96c116731
--- /dev/null
+++ b/packages/editor/src/utils/html.ts
@@ -0,0 +1,54 @@
+/*
+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/>.
+*/
+
+export function convertBrToParagraph(html: string) {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ for (const br of doc.querySelectorAll("br")) {
+ const paragraph = br.closest("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();
+ }
+ }
+ return doc;
+}
+
+function splitOn(bound: Element, cutElement: Element) {
+ let grandparent: ParentNode | null = null;
+ for (
+ let parent = cutElement.parentNode;
+ bound != parent;
+ parent = grandparent
+ ) {
+ if (parent) {
+ const right = parent.cloneNode(false);
+ while (cutElement.nextSibling) right.appendChild(cutElement.nextSibling);
+ grandparent = parent.parentNode;
+ grandparent?.insertBefore(right, parent.nextSibling);
+ grandparent?.insertBefore(cutElement, right);
+ }
+ }
+}
diff --git a/packages/editor/src/utils/tests/html.test.ts b/packages/editor/src/utils/tests/html.test.ts
new file mode 100644
index 000000000..34df53cab
--- /dev/null
+++ b/packages/editor/src/utils/tests/html.test.ts
@@ -0,0 +1,73 @@
+/*
+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 { convertBrToParagraph } from "../html";
+
+const cases = [
+ [
+ `<p>line 1<br>line 2</p>`,
+ `<p data-spacing="single">line 1</p><p data-spacing="single">line 2</p>`
+ ],
+ [
+ `<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>
+ 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>`,
+ `<!--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-->`
+ ]
+];
+
+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()
+ );
+ });
+}