Skip to content

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

editor: fix formatting issues when pasting from ChatGPT (#3217)

Muhammad Alib4c15adf5da2
diff --git a/packages/editor/src/extensions/clipboard/clipboard-dom-parser.ts b/packages/editor/src/extensions/clipboard/clipboard-dom-parser.ts
index be03868db..0062b4dfd 100644
--- a/packages/editor/src/extensions/clipboard/clipboard-dom-parser.ts
+++ b/packages/editor/src/extensions/clipboard/clipboard-dom-parser.ts
@@ -21,7 +21,9 @@ import {
DOMParser as ProsemirrorDOMParser,
ParseOptions
} from "@tiptap/pm/model";
+import { encodeNonAsciiHTML } from "entities";
import { Schema, Slice } from "prosemirror-model";
+import { inferLanguage } from "../code-block";
export class ClipboardDOMParser extends ProsemirrorDOMParser {
static fromSchema(schema: Schema): ClipboardDOMParser {
@@ -35,13 +37,30 @@ export class ClipboardDOMParser extends ProsemirrorDOMParser {
}
parseSlice(dom: Node, options?: ParseOptions | undefined): Slice {
- convertBrToSingleSpacedParagraphs(dom);
+ if (dom instanceof HTMLElement) {
+ formatCodeblocks(dom);
+ convertBrToSingleSpacedParagraphs(dom);
+ }
return super.parseSlice(dom, options);
}
}
-export function convertBrToSingleSpacedParagraphs(dom: Node) {
- if (!(dom instanceof HTMLElement)) return;
+export function formatCodeblocks(dom: HTMLElement | Document) {
+ for (const pre of dom.querySelectorAll("pre")) {
+ const codeAsText = pre.textContent;
+ const languageElement = pre.querySelector(
+ '[class*="language-"],[class*="lang-"]'
+ );
+ const language = inferLanguage(languageElement || pre);
+ if (language) pre.classList.add(`language-${language}`);
+
+ const code = document.createElement("code");
+ code.innerHTML = encodeNonAsciiHTML(codeAsText || "");
+ pre.replaceChildren(code);
+ }
+}
+
+export function convertBrToSingleSpacedParagraphs(dom: HTMLElement | Document) {
for (const br of dom.querySelectorAll("br")) {
let paragraph = br.closest("p");
diff --git a/packages/editor/src/extensions/clipboard/tests/__snapshots__/clipboard-dom-parser.test.ts.snap b/packages/editor/src/extensions/clipboard/tests/__snapshots__/clipboard-dom-parser.test.ts.snap
index d7f1ebb76..c910bb08b 100644
--- a/packages/editor/src/extensions/clipboard/tests/__snapshots__/clipboard-dom-parser.test.ts.snap
+++ b/packages/editor/src/extensions/clipboard/tests/__snapshots__/clipboard-dom-parser.test.ts.snap
@@ -1,54 +1,39 @@
// 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`] = `
-"<!--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>"
+exports[`convert br tags to paragraphs 1`] = `"<p>line 1</p><p data-spacing=\\"single\\">line 2</p>"`;
+
+exports[`convert br tags to paragraphs 2`] = `"<p>line <em>1</em></p><p data-spacing=\\"single\\"><em>line</em> 2</p>"`;
+
+exports[`convert br tags to paragraphs 3`] = `"<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 4`] = `"<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 5`] = `"<p><br></p>"`;
+
+exports[`convert br tags to paragraphs 6`] = `
+"<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>"
`;
-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.<br>
+exports[`convert br tags to paragraphs 7`] = `
+"<!--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><br>
- App version: 2.3.0<br>
- Platform: android<br>
- Model: OnePlus-CPH2409-31<br>
- Pro: true<br>
+ <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 &amp; buggy
-
- Switched to Brave for the better Android app, more private out of the box &amp; unsure if uBlock Origin closes gap</span><!--EndFragment-->
- </body>
- </html>) 1`] = `
+exports[`convert br tags to paragraphs 8`] = `
"<!--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)
@@ -58,12 +43,26 @@ exports[`convert br tags to paragraphs (<html><body>
Switched to Brave for the better Android app, more private out of the box &amp; unsure if uBlock Origin closes gap</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<br>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<br data-some=\\"hello\\">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<br>line</em></span> 2</p>"`;
-
-exports[`convert br tags to paragraphs (<p>line 1<br>line 2</p>) 1`] = `"<p>line 1<br>line 2</p>"`;
+exports[`properly format codeblocks 1`] = `
+"<div>
+ <!--StartFragment--><p>Sure! Here's an implementation of a word counter for Thai that considers each syllable consisting of a consonant sound followed by a vowel sound as a word:</p><pre><code>javascript</code></pre><pre class=\\"language-javascript\\"><code>function countThaiWords(text) {
+ // define a regular expression to match Thai syllables
+ const thaiSyllableRegex = /[&#xe01;-&#xe3a;&#xe40;-&#xe5b;]+[&#xe00;-&#xe7f;]?/g;
+
+ // count the number of matches of the Thai syllable regex in the text
+ const matches = text.match(thaiSyllableRegex) || [];
+ const wordCount = matches.length;
+
+ // return the number of words
+ return wordCount;
+ }
+
+ // example usage
+ const text = &quot;&#xe2a;&#xe27;&#xe31;&#xe2a;&#xe14;&#xe35;&#xe04;&#xe48;&#xe30;&#xe22;&#xe34;&#xe19;&#xe14;&#xe35;&#xe15;&#xe49;&#xe2d;&#xe19;&#xe23;&#xe31;&#xe1a;&#xe40;&#xe02;&#xe49;&#xe32;&#xe2a;&#xe39;&#xe48;&#xe42;&#xe25;&#xe01;&#xe02;&#xe2d;&#xe07;&#xe09;&#xe31;&#xe19;&quot;;
+ const wordCount = countThaiWords(text);
+ console.log(\`Word count: &dollar;{wordCount}\`);
+ // output: Word count: 9
+ </code></pre><p>This implementation defines a regular expression to match Thai syllables, which are composed of one or more Thai characters. It then uses the <code>match</code> function of the <code>String</code> object to count the number of matches of the Thai syllable regex in the input text.</p><p>Note that this implementation assumes that each syllable consisting of a consonant sound followed by a vowel sound is considered a word in Thai. This may not always be accurate, as some words in Thai may consist of multiple syllables, and some syllables may be used as prefixes or suffixes to modify other words. However, this approach should work well for many cases where each syllable is considered a separate word.</p><!--EndFragment-->
+
+ </div>"
+`;
diff --git a/packages/editor/src/extensions/clipboard/tests/clipboard-dom-parser.test.ts b/packages/editor/src/extensions/clipboard/tests/clipboard-dom-parser.test.ts
index de7dc774a..64998c5eb 100644
--- a/packages/editor/src/extensions/clipboard/tests/clipboard-dom-parser.test.ts
+++ b/packages/editor/src/extensions/clipboard/tests/clipboard-dom-parser.test.ts
@@ -18,7 +18,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { test } from "vitest";
-import { convertBrToSingleSpacedParagraphs } from "../clipboard-dom-parser";
+import {
+ formatCodeblocks,
+ convertBrToSingleSpacedParagraphs
+} from "../clipboard-dom-parser";
const cases = [
[`<p>line 1<br>line 2</p>`],
@@ -67,9 +70,40 @@ and yet, we somehow manage to get by.<br>
for (const testCase of cases) {
const [html, expected] = testCase;
- test(`convert br tags to paragraphs (${testCase})`, (t) => {
+ test(`convert br tags to paragraphs`, (t) => {
const element = new DOMParser().parseFromString(html, "text/html");
convertBrToSingleSpacedParagraphs(element);
t.expect(element.body.innerHTML.trim()).toMatchSnapshot();
});
}
+
+const codeBlocks = [
+ `<div>
+ <!--StartFragment--><p>Sure! Here's an implementation of a word counter for Thai that considers each syllable consisting of a consonant sound followed by a vowel sound as a word:</p><pre><div class="bg-black rounded-md mb-4"><div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md"><span>javascript</span></div></div></pre><pre><div class="bg-black rounded-md mb-4"><div class="p-4 overflow-y-auto"><code class="!whitespace-pre hljs language-javascript"><span class="hljs-keyword">function</span> <span class="hljs-title function_">countThaiWords</span>(<span class="hljs-params">text</span>) {
+ <span class="hljs-comment">// define a regular expression to match Thai syllables</span>
+ <span class="hljs-keyword">const</span> thaiSyllableRegex = <span class="hljs-regexp">/[\u0E01-\u0E3A\u0E40-\u0E5B]+[\u0E00-\u0E7F]?/g</span>;
+
+ <span class="hljs-comment">// count the number of matches of the Thai syllable regex in the text</span>
+ <span class="hljs-keyword">const</span> matches = text.<span class="hljs-title function_">match</span>(thaiSyllableRegex) || [];
+ <span class="hljs-keyword">const</span> wordCount = matches.<span class="hljs-property">length</span>;
+
+ <span class="hljs-comment">// return the number of words</span>
+ <span class="hljs-keyword">return</span> wordCount;
+ }
+
+ <span class="hljs-comment">// example usage</span>
+ <span class="hljs-keyword">const</span> text = <span class="hljs-string">"สวัสดีค่ะยินดีต้อนรับเข้าสู่โลกของฉัน"</span>;
+ <span class="hljs-keyword">const</span> wordCount = <span class="hljs-title function_">countThaiWords</span>(text);
+ <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">\`Word count: <span class="hljs-subst">\${wordCount}</span>\`</span>);
+ <span class="hljs-comment">// output: Word count: 9</span>
+ </code></div></div></pre><p>This implementation defines a regular expression to match Thai syllables, which are composed of one or more Thai characters. It then uses the <code>match</code> function of the <code>String</code> object to count the number of matches of the Thai syllable regex in the input text.</p><p>Note that this implementation assumes that each syllable consisting of a consonant sound followed by a vowel sound is considered a word in Thai. This may not always be accurate, as some words in Thai may consist of multiple syllables, and some syllables may be used as prefixes or suffixes to modify other words. However, this approach should work well for many cases where each syllable is considered a separate word.</p><!--EndFragment-->
+
+ </div>`
+];
+for (const codeBlock of codeBlocks) {
+ test(`properly format codeblocks`, (t) => {
+ const element = new DOMParser().parseFromString(codeBlock, "text/html");
+ formatCodeblocks(element);
+ t.expect(element.body.innerHTML.trim()).toMatchSnapshot();
+ });
+}