AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(editor): continue after an inserted or edited formula (#720)
Dariusz Korytoc596046b4f5d
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 54b0c6b8..17b3c612 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -3970,7 +3970,9 @@ const RichEditorPane = ({to: stored?.to ?? draft.to,pos: stored?.pos ?? draft.pos,});- editor.chain().focus(stored?.from ?? draft.from ?? null, { scrollIntoView: true }).run();+ // Keep the selection the insert left after the formula; focusing+ // `from` put the caret back in front of it, so typing went there.+ editor.chain().focus(null, { scrollIntoView: true }).run();}}onRemove={mathFormulaDraft && typeof mathFormulaDraft.pos === "number"diff --git a/apps/web/src/components/editor/math-formula.test.mjs b/apps/web/src/components/editor/math-formula.test.mjsindex ecb4b6f7..5086f404 100644--- a/apps/web/src/components/editor/math-formula.test.mjs+++ b/apps/web/src/components/editor/math-formula.test.mjs@@ -118,4 +118,53 @@ describe("math formula commands", () => {expect(applyMathFormula(editor, { kind: "inline", latex: " " })).toBe(false);editor.destroy();});++ test("continues after a newly inserted formula instead of in front of it (#719)", () => {+ const inline = createEditor({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Energy is " }] }] });+ inline.commands.setTextSelection(11);+ expect(applyMathFormula(inline, { kind: "inline", latex: "E = mc^2" })).toBe(true);+ inline.commands.insertContent({ type: "text", text: "AFTER" });+ expect(inline.getJSON().content[0].content).toEqual([+ { type: "text", text: "Energy is " },+ { type: "inlineMath", attrs: { latex: "E = mc^2" } },+ { type: "text", text: "AFTER" },+ ]);+ inline.destroy();++ for (const content of [+ [{ type: "paragraph", content: [{ type: "text", text: "Energy is " }] }],+ [{ type: "paragraph", content: [{ type: "text", text: "Energy is " }] }, { type: "paragraph", content: [{ type: "text", text: "next" }] }],+ ]) {+ const block = createEditor({ type: "doc", content });+ block.commands.setTextSelection(11);+ expect(applyMathFormula(block, { kind: "block", latex: "E = mc^2" })).toBe(true);+ // Typing must not replace the selected formula.+ block.commands.insertContent({ type: "text", text: "AFTER" });+ const types = block.getJSON().content.map((node) => node.type === "blockMath" ? "blockMath" : (node.content ?? []).map((child) => child.text).join(""));+ expect(types).toEqual(content.length === 1 ? ["Energy is ", "blockMath", "AFTER"] : ["Energy is ", "blockMath", "AFTER", "next"]);+ expect(block.getJSON().content.find((node) => node.type === "blockMath")?.attrs).toEqual({ latex: "E = mc^2" });+ block.destroy();+ }+ });++ test("continues after an edited formula instead of in front of it or replacing it (#719)", () => {+ const editor = createEditor({ type: "doc", content: [+ { type: "paragraph", content: [{ type: "text", text: "A " }, { type: "inlineMath", attrs: { latex: "x" } }, { type: "text", text: " B" }] },+ { type: "blockMath", attrs: { latex: "y" } },+ { type: "paragraph", content: [{ type: "text", text: "C" }] },+ ] });+ const outline = () => editor.getJSON().content.map((node) => node.type === "blockMath"+ ? `[block:${node.attrs.latex}]`+ : (node.content ?? []).map((child) => child.text ?? `[inline:${child.attrs.latex}]`).join(""));++ expect(applyMathFormula(editor, { kind: "inline", latex: "z^2", pos: 3 })).toBe(true);+ editor.commands.insertContent({ type: "text", text: "Q" });+ expect(outline()).toEqual(["A [inline:z^2]Q B", "[block:y]", "C"]);++ const blockPos = editor.state.doc.child(0).nodeSize;+ expect(applyMathFormula(editor, { kind: "block", latex: "w", pos: blockPos })).toBe(true);+ editor.commands.insertContent({ type: "text", text: "R" });+ expect(outline()).toEqual(["A [inline:z^2]Q B", "[block:w]", "R", "C"]);+ editor.destroy();+ });});diff --git a/apps/web/src/components/editor/math-formula.ts b/apps/web/src/components/editor/math-formula.tsindex 18e93d3e..bc8dba16 100644--- a/apps/web/src/components/editor/math-formula.ts+++ b/apps/web/src/components/editor/math-formula.ts@@ -1,4 +1,5 @@import type { Editor } from "@tiptap/core";+import { NodeSelection, TextSelection, type Transaction } from "@tiptap/pm/state";import {BLOCK_MATH_NODE_TYPE,INLINE_MATH_NODE_TYPE,@@ -36,14 +37,40 @@ export const resolveMathFormulaTarget = (editor: Editor, pos?: number): MathFormreturn null;};+/**+ * Puts the caret right after the formula at `formulaPos`, so the next key+ * continues the text instead of landing in front of it or replacing it. A+ * display formula continues in an empty paragraph after it, so typing does not+ * join the following text either.+ */+const placeCaretAfterFormula = (tr: Transaction, formulaPos: number) => {+ const node = tr.doc.nodeAt(formulaPos);+ if (!node) return;+ const after = formulaPos + node.nodeSize;+ if (node.type.name !== BLOCK_MATH_NODE_TYPE) {+ tr.setSelection(TextSelection.create(tr.doc, after));+ return;+ }+ const next = tr.doc.resolve(after).nodeAfter;+ if (next?.type.name !== "paragraph" || next.content.size > 0) {+ tr.insert(after, tr.doc.type.schema.nodes.paragraph!.create());+ }+ tr.setSelection(TextSelection.create(tr.doc, after + 1));+};+export const applyMathFormula = (editor: Editor, draft: MathFormulaDraft) => {const latex = draft.latex.trim();if (!latex) return false;if (typeof draft.pos === "number") {- return draft.kind === "inline"- ? editor.commands.updateInlineMath({ latex, pos: draft.pos })- : editor.commands.updateBlockMath({ latex, pos: draft.pos });+ const pos = draft.pos;+ const chain = editor.chain();+ return (draft.kind === "inline" ? chain.updateInlineMath({ latex, pos }) : chain.updateBlockMath({ latex, pos }))+ .command(({ tr }) => {+ placeCaretAfterFormula(tr, tr.mapping.map(pos));+ return true;+ })+ .run();}const from = draft.from ?? editor.state.selection.from;@@ -52,7 +79,18 @@ export const applyMathFormula = (editor: Editor, draft: MathFormulaDraft) => {? { type: INLINE_MATH_NODE_TYPE, attrs: { latex } }: { type: BLOCK_MATH_NODE_TYPE, attrs: { latex } };- return editor.chain().insertContentAt(from === to ? from : { from, to }, content).run();+ return editor.chain()+ .insertContentAt(from === to ? from : { from, to }, content)+ .command(({ tr }) => {+ // An inline formula already leaves the caret after it; a display formula+ // is left selected as a node.+ const { selection } = tr;+ if (selection instanceof NodeSelection && selection.node.type.name === BLOCK_MATH_NODE_TYPE) {+ placeCaretAfterFormula(tr, selection.from);+ }+ return true;+ })+ .run();};export const deleteMathFormula = (editor: Editor, target: Pick<MathFormulaTarget, "kind" | "pos">) => {diff --git a/tests/e2e/math-formula-caret.spec.ts b/tests/e2e/math-formula-caret.spec.tsnew file mode 100644index 00000000..89670c5f--- /dev/null+++ b/tests/e2e/math-formula-caret.spec.ts@@ -0,0 +1,107 @@+import { expect, test, type Page } from "@playwright/test";++test.use({ locale: "en-US" });++const createMemo = async (page: Page, title: string, contentMarkdown: string) => {+ const notebooks = await (await page.request.get("/api/v1/notebooks")).json() as { notebooks: Array<{ id: string }> };+ const response = await page.request.post("/api/v1/memos", {+ data: { notebookId: notebooks.notebooks[0]!.id, title, contentMarkdown },+ });+ expect(response.status()).toBe(201);+ return (await response.json() as { memo: { id: string } }).memo;+};++const paragraphs = (page: Page) => page.evaluate(() => {+ const editor = (document.querySelector(".ProseMirror") as HTMLElement & {+ editor: { getJSON: () => { content: Array<{ type: string; content?: Array<{ type: string; text?: string }> }> } };+ }).editor;+ return editor.getJSON().content.map((node) => node.type === "blockMath" ? "[blockMath]" : (node.content ?? []).map((child) => child.text ?? `[${child.type}]`).join(""));+});++// Issue #719: the caret was moved back in front of a newly inserted formula.+for (const kind of ["Inline", "Display"] as const) {+ test(`typing right after inserting a ${kind.toLowerCase()} formula continues after it`, async ({ page }) => {+ const title = `Formula caret ${kind} ${Date.now()}`;+ const memo = await createMemo(page, title, "Energy is");+ try {+ await page.goto("/");+ await page.getByRole("button", { name: "All notes", exact: true }).click();+ await page.getByPlaceholder("Search notes").fill(title);+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ const editor = page.locator(".ProseMirror[contenteditable='true']");+ await expect(editor).toBeEditable();+ await editor.getByText("Energy is").click();+ await page.keyboard.press("End");+ await page.keyboard.type(" ");++ await page.getByRole("button", { name: "Insert formula" }).click();+ const dialog = page.getByRole("dialog");+ await dialog.getByRole("button", { name: kind, exact: true }).click();+ await dialog.getByRole("button", { name: "LaTeX source" }).click();+ await dialog.locator("textarea").fill("E = mc^2");+ await dialog.getByRole("button", { name: "Apply" }).click();+ await expect(dialog).toBeHidden();+ await page.keyboard.type("AFTER");++ await expect.poll(() => paragraphs(page)).toEqual(kind === "Inline"+ ? ["Energy is [inlineMath]AFTER"]+ : ["Energy is ", "[blockMath]", "AFTER"]);++ // Undo removes the formula together with the paragraph added after it.+ // History may group the typing with the insertion, so undo up to twice.+ await page.keyboard.press("ControlOrMeta+z");+ if ((await paragraphs(page)).join("|") !== "Energy is ") await page.keyboard.press("ControlOrMeta+z");+ await expect.poll(() => paragraphs(page)).toEqual(["Energy is "]);+ } finally {+ await page.request.delete(`/api/v1/memos/${memo.id}`);+ await page.request.delete(`/api/v1/memos/${memo.id}?permanent=1`);+ }+ });+}++const clickFormula = async (page: Page, selector: string) => {+ // A real click on the rendered formula; Playwright's actionability check+ // reports the surrounding paragraph as covering the inline node.+ const box = (await page.locator(`.ProseMirror ${selector}`).boundingBox())!;+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+};++const outline = (page: Page) => page.evaluate(() => {+ const editor = (document.querySelector(".ProseMirror") as HTMLElement & {+ editor: { getJSON: () => { content: Array<{ type: string; attrs?: { latex?: string }; content?: Array<{ type: string; text?: string; attrs?: { latex?: string } }> }> } };+ }).editor;+ return editor.getJSON().content.map((node) => node.type === "blockMath"+ ? `[block:${node.attrs?.latex}]`+ : (node.content ?? []).map((child) => child.text ?? `[inline:${child.attrs?.latex}]`).join(""));+});++for (const [kind, selector, expected] of [+ ["inline", "[data-type='inline-math']", ["A [inline:z^2]Q B", "[block:y]", "C"]],+ ["display", "[data-type='block-math']", ["A [inline:x] B", "[block:z^2]", "Q", "C"]],+] as const) {+ test(`typing right after editing a ${kind} formula continues after it and keeps it`, async ({ page }) => {+ const title = `Formula edit caret ${kind} ${Date.now()}`;+ const memo = await createMemo(page, title, "A $x$ B\n\n$$\ny\n$$\n\nC");+ try {+ await page.goto("/");+ await page.getByRole("button", { name: "All notes", exact: true }).click();+ await page.getByPlaceholder("Search notes").fill(title);+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ await expect(page.locator(`.ProseMirror ${selector}`)).toBeVisible();++ await clickFormula(page, selector);+ const dialog = page.getByRole("dialog");+ await expect(dialog.getByRole("heading", { name: "Edit formula" })).toBeVisible();+ await dialog.getByRole("button", { name: "LaTeX source" }).click();+ await dialog.locator("textarea").fill("z^2");+ await dialog.getByRole("button", { name: "Apply" }).click();+ await expect(dialog).toBeHidden();+ await page.keyboard.type("Q");++ await expect.poll(() => outline(page)).toEqual([...expected]);+ } finally {+ await page.request.delete(`/api/v1/memos/${memo.id}`);+ await page.request.delete(`/api/v1/memos/${memo.id}?permanent=1`);+ }+ });+}