Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(editor): convert typed checklists and dollar formulas in rich text

tianma-if540d494a258f
diff --git a/apps/web/src/components/editor/markdown-shortcuts.test.mjs b/apps/web/src/components/editor/markdown-shortcuts.test.mjs
new file mode 100644
index 00000000..e8e5dee7
--- /dev/null
+++ b/apps/web/src/components/editor/markdown-shortcuts.test.mjs
@@ -0,0 +1,327 @@
+import { describe, expect, test } from "bun:test";
+import { Editor } from "@tiptap/core";
+import { createEdgeEverDocumentExtensions, docToMarkdown } from "@edgeever/shared";
+import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
+import { ensureTestWindowDom } from "../../lib/restore-test-global.mjs";
+
+const createEditor = (content = { type: "doc", content: [{ type: "paragraph" }] }) => {
+ ensureTestWindowDom();
+ const editor = new Editor({
+ extensions: createEdgeEverDocumentExtensions({
+ mathematics: createEdgeEverMathematics(),
+ }),
+ content,
+ });
+ editor.view.updateState(editor.state.reconfigure({
+ plugins: editor.extensionManager.plugins,
+ }));
+ return editor;
+};
+
+const typeText = (editor, text) => {
+ // Headless Bun never mounts an EditorView, so call the input-rule plugins
+ // with the same state and dispatch the real view proxy already exposes.
+ const plugins = editor.extensionManager.plugins;
+ for (const char of text) {
+ const { from, to } = editor.state.selection;
+ const view = {
+ composing: false,
+ state: editor.state,
+ dispatch: (transaction) => editor.view.dispatch(transaction),
+ };
+ let handled = false;
+ for (const plugin of plugins) {
+ const handleTextInput = plugin.props?.handleTextInput;
+ if (handleTextInput?.call(plugin, view, from, to, char)) {
+ handled = true;
+ break;
+ }
+ }
+ if (!handled) editor.view.dispatch(editor.state.tr.insertText(char, from, to));
+ }
+};
+
+const pastePlainText = (editor, text) => {
+ const { schema } = editor;
+ const nodes = text.split("\n").map((line) => (
+ line ? schema.nodes.paragraph.create(null, schema.text(line)) : schema.nodes.paragraph.create()
+ ));
+ editor.view.dispatch(
+ editor.state.tr
+ .replaceWith(0, editor.state.doc.content.size, nodes)
+ .setMeta("uiEvent", "paste"),
+ );
+};
+
+const paragraphText = (node) => node.content?.filter((child) => child.type === "text").map((child) => child.text).join("") ?? "";
+
+describe("checklist typing", () => {
+ test("turns - [ ] into an empty task and keeps the following words in that task", () => {
+ const editor = createEditor();
+ typeText(editor, "- [ ] buy milk");
+
+ expect(editor.getJSON().content[0]).toEqual({
+ type: "taskList",
+ content: [{
+ type: "taskItem",
+ attrs: { checked: false },
+ content: [{ type: "paragraph", content: [{ type: "text", text: "buy milk" }] }],
+ }],
+ });
+ expect(docToMarkdown(editor.getJSON())).toContain("- [ ] buy milk");
+ editor.destroy();
+ });
+
+ test("turns * [x] and + [X] into checked tasks", () => {
+ const star = createEditor();
+ typeText(star, "* [x] ");
+ expect(star.getJSON().content[0].content[0].attrs.checked).toBe(true);
+
+ const plus = createEditor();
+ typeText(plus, "+ [X] ");
+ expect(plus.getJSON().content[0].content[0].attrs.checked).toBe(true);
+ star.destroy();
+ plus.destroy();
+ });
+
+ test("splits only the marked bullet out of a list and keeps the surrounding items", () => {
+ const editor = createEditor({
+ type: "doc",
+ content: [{
+ type: "bulletList",
+ content: [
+ { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "a" }] }] },
+ { type: "listItem", content: [{ type: "paragraph" }] },
+ { type: "listItem", content: [{ type: "paragraph", content: [{ type: "text", text: "c" }] }] },
+ ],
+ }],
+ });
+ let cursor = null;
+ editor.state.doc.descendants((node, pos) => {
+ if (cursor !== null) return false;
+ if (node.type.name === "paragraph" && node.content.size === 0) {
+ cursor = pos + 1;
+ return false;
+ }
+ });
+ editor.commands.setTextSelection(cursor);
+ typeText(editor, "[ ] ");
+
+ expect(editor.getJSON().content.map((node) => node.type)).toEqual(["bulletList", "taskList", "bulletList", "paragraph"]);
+ expect(paragraphText(editor.getJSON().content[0].content[0].content[0])).toBe("a");
+ expect(editor.getJSON().content[1].content[0].attrs.checked).toBe(false);
+ expect(paragraphText(editor.getJSON().content[2].content[0].content[0])).toBe("c");
+ editor.destroy();
+ });
+
+ test("converts a bullet that already has text when the marker is typed at its start", () => {
+ const editor = createEditor({
+ type: "doc",
+ content: [{
+ type: "bulletList",
+ content: [{
+ type: "listItem",
+ content: [{ type: "paragraph", content: [{ type: "text", text: "beta" }] }],
+ }],
+ }],
+ });
+ let cursor = null;
+ editor.state.doc.descendants((node, pos) => {
+ if (cursor !== null) return false;
+ if (node.type.name === "paragraph") {
+ cursor = pos + 1;
+ return false;
+ }
+ });
+ editor.commands.setTextSelection(cursor);
+ typeText(editor, "[ ] ");
+
+ expect(editor.getJSON().content[0].type).toBe("taskList");
+ expect(paragraphText(editor.getJSON().content[0].content[0].content[0])).toBe("beta");
+ editor.destroy();
+ });
+
+ test("still turns a plain [ ] into a task and leaves ordered lists unchanged", () => {
+ const plain = createEditor();
+ typeText(plain, "[ ] ");
+ expect(plain.getJSON().content[0].type).toBe("taskList");
+
+ const ordered = createEditor();
+ typeText(ordered, "1. [ ] ");
+ expect(ordered.getJSON().content[0].type).toBe("orderedList");
+ expect(paragraphText(ordered.getJSON().content[0].content[0].content[0])).toBe("[ ] ");
+ plain.destroy();
+ ordered.destroy();
+ });
+
+ test("joins the converted item with a task list on either side", () => {
+ const editor = createEditor({
+ type: "doc",
+ content: [
+ {
+ type: "taskList",
+ content: [{
+ type: "taskItem",
+ attrs: { checked: false },
+ content: [{ type: "paragraph", content: [{ type: "text", text: "a" }] }],
+ }],
+ },
+ {
+ type: "bulletList",
+ content: [{ type: "listItem", content: [{ type: "paragraph" }] }],
+ },
+ {
+ type: "taskList",
+ content: [{
+ type: "taskItem",
+ attrs: { checked: true },
+ content: [{ type: "paragraph", content: [{ type: "text", text: "c" }] }],
+ }],
+ },
+ ],
+ });
+ let cursor = null;
+ editor.state.doc.descendants((node, pos) => {
+ if (cursor !== null) return false;
+ if (node.type.name === "paragraph" && node.content.size === 0) {
+ cursor = pos + 1;
+ return false;
+ }
+ });
+ editor.commands.setTextSelection(cursor);
+ typeText(editor, "[x] ");
+
+ const taskList = editor.getJSON().content[0];
+ expect(taskList.type).toBe("taskList");
+ expect(taskList.content.map((item) => item.attrs.checked)).toEqual([false, true, true]);
+ expect(taskList.content.map((item) => paragraphText(item.content[0]))).toEqual(["a", "", "c"]);
+ editor.destroy();
+ });
+
+ test("undoes the checklist conversion", () => {
+ const editor = createEditor();
+ typeText(editor, "- [ ] ");
+ expect(editor.getJSON().content[0].type).toBe("taskList");
+ expect(editor.commands.undo()).toBe(true);
+ expect(docToMarkdown(editor.getJSON())).not.toContain("- [ ]");
+ editor.destroy();
+ });
+});
+
+describe("formula typing and pasting", () => {
+ test("turns $latex$ into inline math and leaves currency as text", () => {
+ const editor = createEditor();
+ typeText(editor, "Euler $e=mc^2$ and $100$.");
+
+ const content = editor.getJSON().content[0].content;
+ expect(content).toEqual([
+ { type: "text", text: "Euler " },
+ { type: "inlineMath", attrs: { latex: "e=mc^2" } },
+ { type: "text", text: " and $100$." },
+ ]);
+ expect(docToMarkdown(editor.getJSON())).toBe("Euler $e=mc^2$ and \\$100\\$.");
+ editor.destroy();
+ });
+
+ test("turns a paragraph of $$latex$$ into display math and ignores $$ inside a sentence", () => {
+ const block = createEditor();
+ typeText(block, "$$c+d$$next");
+ expect(block.getJSON().content[0]).toMatchObject({
+ type: "blockMath",
+ attrs: { latex: "c+d" },
+ });
+ expect(block.getJSON().content[1]).toEqual({
+ type: "paragraph",
+ content: [{ type: "text", text: "next" }],
+ });
+
+ const inline = createEditor();
+ typeText(inline, "hello $$x$$");
+ expect(inline.getJSON().content[0].content).toEqual([{ type: "text", text: "hello $$x$$" }]);
+ block.destroy();
+ inline.destroy();
+ });
+
+ test("does not convert dollars typed in a code block", () => {
+ const editor = createEditor({
+ type: "doc",
+ content: [{ type: "codeBlock", content: [{ type: "text", text: "before " }] }],
+ });
+ let cursor = null;
+ editor.state.doc.descendants((node, pos) => {
+ if (cursor !== null) return false;
+ if (node.isText) {
+ cursor = pos + node.text.length;
+ return false;
+ }
+ });
+ editor.commands.setTextSelection(cursor);
+ typeText(editor, "$x$");
+ expect(editor.getJSON().content[0].type).toBe("codeBlock");
+ expect(editor.getJSON().content[0].content[0].text).toBe("before $x$");
+ editor.destroy();
+ });
+
+ test("converts only math delimiters when plain text is pasted", () => {
+ const editor = createEditor();
+ pastePlainText(editor, [
+ "See $a+b$ and $100$.",
+ "$$c+d$$",
+ "- not a list",
+ "# not a heading",
+ ].join("\n"));
+
+ const content = editor.getJSON().content;
+ expect(content[0].content).toEqual([
+ { type: "text", text: "See " },
+ { type: "inlineMath", attrs: { latex: "a+b" } },
+ { type: "text", text: " and $100$." },
+ ]);
+ expect(content[1]).toMatchObject({ type: "blockMath", attrs: { latex: "c+d" } });
+ expect(content[2]).toEqual({
+ type: "paragraph",
+ content: [{ type: "text", text: "- not a list" }],
+ });
+ expect(content[3]).toEqual({
+ type: "paragraph",
+ content: [{ type: "text", text: "# not a heading" }],
+ });
+ editor.destroy();
+ });
+
+ test("leaves the caret after a pasted display formula", () => {
+ const editor = createEditor();
+ pastePlainText(editor, "$$c+d$$");
+ expect(editor.getJSON().content[0]).toMatchObject({
+ type: "blockMath",
+ attrs: { latex: "c+d" },
+ });
+ expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
+ typeText(editor, "next");
+ expect(editor.getJSON().content[0].type).toBe("blockMath");
+ expect(editor.getJSON().content[1].content).toEqual([{ type: "text", text: "next" }]);
+ editor.destroy();
+ });
+
+ test("leaves dollars inside a pasted code block as text", () => {
+ const editor = createEditor();
+ const { schema } = editor;
+ const nodes = [
+ schema.nodes.paragraph.create(null, schema.text("See $a$")),
+ schema.nodes.codeBlock.create(null, schema.text("const value = $a$;")),
+ ];
+ editor.view.dispatch(
+ editor.state.tr
+ .replaceWith(0, editor.state.doc.content.size, nodes)
+ .setMeta("uiEvent", "paste"),
+ );
+
+ const content = editor.getJSON().content;
+ expect(content[0].content[1]).toMatchObject({ type: "inlineMath", attrs: { latex: "a" } });
+ expect(content[1]).toMatchObject({
+ type: "codeBlock",
+ content: [{ type: "text", text: "const value = $a$;" }],
+ });
+ editor.destroy();
+ });
+});
diff --git a/packages/shared/src/document-extensions.ts b/packages/shared/src/document-extensions.ts
index 829e910a..e1f60a17 100644
--- a/packages/shared/src/document-extensions.ts
+++ b/packages/shared/src/document-extensions.ts
@@ -1,6 +1,6 @@
import type { AnyExtension } from "@tiptap/core";
import Image from "@tiptap/extension-image";
-import { TaskItem, TaskList } from "@tiptap/extension-list";
+import { TaskList } from "@tiptap/extension-list";
import { TableKit } from "@tiptap/extension-table";
import { Markdown } from "@tiptap/markdown";
import StarterKit from "@tiptap/starter-kit";
@@ -12,6 +12,7 @@ import { PdfAttachment } from "./pdf-attachment";
import { PluginEmbed } from "./plugin-embed";
import { EmptyExternalLink } from "./empty-external-link";
import { EdgeEverLink } from "./editor-link";
+import { createEdgeEverTaskItem } from "./task-item-input";
export type CreateEdgeEverDocumentExtensionsOptions = {
mathematics: AnyExtension[];
@@ -44,7 +45,7 @@ export const createEdgeEverDocumentExtensions = (
...(options.markdown ? [EdgeEverLink] : []),
EmptyExternalLink,
TaskList,
- TaskItem.configure({ nested: true }),
+ createEdgeEverTaskItem(),
options.table === undefined ? TableKit : TableKit.configure(options.table),
...withOptional(options.image, Image),
...withOptional(options.gallery, ImageGallery),
diff --git a/packages/shared/src/mathematics-markdown.test.mjs b/packages/shared/src/mathematics-markdown.test.mjs
new file mode 100644
index 00000000..07c2f915
--- /dev/null
+++ b/packages/shared/src/mathematics-markdown.test.mjs
@@ -0,0 +1,40 @@
+import { describe, expect, test } from "bun:test";
+import {
+ findInlineMathSpans,
+ matchBlockMathText,
+ matchInlineMathSuffix,
+} from "./mathematics-markdown.ts";
+
+describe("math delimiter recognition", () => {
+ test("reads an inline formula that ends at the caret", () => {
+ expect(matchInlineMathSuffix("Euler $e^{i\\pi}+1=0$")).toEqual({
+ index: 6,
+ raw: "$e^{i\\pi}+1=0$",
+ latex: "e^{i\\pi}+1=0",
+ });
+ });
+
+ test("leaves currency pairs as text and still finds a later formula", () => {
+ const text = "Price $100$ and $12.50$, then $x$";
+ expect(findInlineMathSpans(text)).toEqual([
+ { index: text.lastIndexOf("$x$"), raw: "$x$", latex: "x" },
+ ]);
+ expect(matchInlineMathSuffix("$100$")).toBeNull();
+ expect(matchInlineMathSuffix("$12,50$")).toBeNull();
+ });
+
+ test("does not treat double dollars as inline math", () => {
+ expect(findInlineMathSpans("hello $$x$$")).toEqual([]);
+ expect(matchInlineMathSuffix("hello $$x$$")).toBeNull();
+ expect(matchInlineMathSuffix("$$c+d$")).toBeNull();
+ expect(matchInlineMathSuffix("$$c+d$$")).toBeNull();
+ expect(matchBlockMathText("hello $$x$$")).toBeNull();
+ });
+
+ test("reads a display formula only when it occupies the paragraph", () => {
+ expect(matchBlockMathText("$$c+d$$")).toEqual({ latex: "c+d" });
+ expect(matchBlockMathText(" $$ c + d $$ ")).toEqual({ latex: "c + d" });
+ expect(matchBlockMathText("$$$c$$$")).toBeNull();
+ expect(matchBlockMathText("$$ $$")).toBeNull();
+ });
+});
diff --git a/packages/shared/src/mathematics-markdown.ts b/packages/shared/src/mathematics-markdown.ts
index 6979c9e8..05a65242 100644
--- a/packages/shared/src/mathematics-markdown.ts
+++ b/packages/shared/src/mathematics-markdown.ts
@@ -20,6 +20,90 @@ const findClosingDelimiter = (source: string, delimiter: "$" | "$$", from: numbe
return -1;
};
+/** A dollar-wrapped number is currency, so it must not become a formula. */
+export const isCurrencyLatex = (latex: string) => /^\d+(?:[.,]\d+)?$/u.test(latex);
+
+export type InlineMathSpan = {
+ index: number;
+ raw: string;
+ latex: string;
+};
+
+const readInlineMathAt = (text: string, start: number): InlineMathSpan | null => {
+ if (text[start] !== "$" || isEscaped(text, start) || text.startsWith("$$", start)) {
+ return null;
+ }
+ // The second `$` of `$$` belongs to a display delimiter, not an inline formula.
+ if (start > 0 && text[start - 1] === "$" && !isEscaped(text, start - 1)) {
+ return null;
+ }
+
+ const closing = findClosingDelimiter(text, "$", start + 1);
+ if (closing < 0 || text[closing + 1] === "$") return null;
+
+ const latex = text.slice(start + 1, closing).trim();
+ if (!latex || latex.includes("\n") || isCurrencyLatex(latex)) return null;
+
+ return {
+ index: start,
+ raw: text.slice(start, closing + 1),
+ latex,
+ };
+};
+
+const skipConsumedDollars = (text: string, start: number) => {
+ if (isEscaped(text, start) || text.startsWith("$$", start)) return start + 1;
+
+ const closing = findClosingDelimiter(text, "$", start + 1);
+ if (closing < 0 || text[closing + 1] === "$") return start + 1;
+
+ const latex = text.slice(start + 1, closing).trim();
+ if (latex && !latex.includes("\n") && isCurrencyLatex(latex)) return closing + 1;
+ return start + 1;
+};
+
+/** Inline `$...$` spans in document order. Currency pairs are consumed and skipped. */
+export const findInlineMathSpans = (text: string): InlineMathSpan[] => {
+ const spans: InlineMathSpan[] = [];
+ let index = 0;
+
+ while (index < text.length) {
+ const start = text.indexOf("$", index);
+ if (start < 0) break;
+
+ const span = readInlineMathAt(text, start);
+ if (!span) {
+ index = skipConsumedDollars(text, start);
+ continue;
+ }
+
+ spans.push(span);
+ index = span.index + span.raw.length;
+ }
+
+ return spans;
+};
+
+/** The inline formula that ends at the caret, if the closing `$` was just typed. */
+export const matchInlineMathSuffix = (text: string): InlineMathSpan | null => {
+ const span = findInlineMathSpans(text).at(-1);
+ if (!span || span.index + span.raw.length !== text.length) return null;
+ return span;
+};
+
+/** A paragraph whose entire text is one `$$...$$` display formula. */
+export const matchBlockMathText = (text: string): { latex: string } | null => {
+ const trimmed = text.trim();
+ if (!trimmed.startsWith("$$") || trimmed.startsWith("$$$")) return null;
+
+ const closing = findClosingDelimiter(trimmed, "$$", 2);
+ if (closing < 0 || trimmed.slice(closing + 2).trim() !== "") return null;
+
+ const latex = trimmed.slice(2, closing).trim();
+ if (!latex) return null;
+ return { latex };
+};
+
export const edgeEverInlineMathMarkdownTokenizer = {
name: INLINE_MATH_NODE_TYPE,
level: "inline" as const,
@@ -42,7 +126,7 @@ export const edgeEverInlineMathMarkdownTokenizer = {
// A dollar-wrapped number is overwhelmingly likely to be currency. Consume
// it as text so its closing delimiter cannot start a later math token.
- if (/^\d+(?:[.,]\d+)?$/u.test(latex)) {
+ if (isCurrencyLatex(latex)) {
return { type: "text", raw, text: raw };
}
diff --git a/packages/shared/src/mathematics.ts b/packages/shared/src/mathematics.ts
index 694301ed..f156b152 100644
--- a/packages/shared/src/mathematics.ts
+++ b/packages/shared/src/mathematics.ts
@@ -1,10 +1,15 @@
+import { InputRule, PasteRule } from "@tiptap/core";
import { BlockMath, InlineMath } from "@tiptap/extension-mathematics";
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { TextSelection, type Transaction } from "@tiptap/pm/state";
import {
BLOCK_MATH_NODE_TYPE,
edgeEverBlockMathMarkdownTokenizer,
edgeEverInlineMathMarkdownTokenizer,
+ findInlineMathSpans,
INLINE_MATH_NODE_TYPE,
+ matchBlockMathText,
+ matchInlineMathSuffix,
} from "./mathematics-markdown";
export {
@@ -19,12 +24,127 @@ export type CreateEdgeEverMathematicsOptions = {
onBlockClick?: EdgeEverMathematicsClickHandler;
};
+const textAt = (doc: ProseMirrorNode, from: number, to: number) => {
+ if (from < 0 || to > doc.content.size || from >= to) return "";
+ return doc.textBetween(from, to);
+};
+
+const placeCaretAfterBlock = (tr: Transaction, posAfterBlock: number) => {
+ const $after = tr.doc.resolve(posAfterBlock);
+ const paragraph = $after.nodeAfter?.type.name === "paragraph"
+ ? null
+ : tr.doc.type.schema.nodes.paragraph?.create();
+ if (paragraph) tr.insert(posAfterBlock, paragraph);
+ tr.setSelection(TextSelection.create(tr.doc, posAfterBlock + 1));
+};
+
const EdgeEverInlineMath = InlineMath.extend({
markdownTokenizer: edgeEverInlineMathMarkdownTokenizer,
+
+ // Stored notes use `$latex$`. TipTap's own rule treats `$$latex$$` as inline math.
+ addInputRules() {
+ return [
+ new InputRule({
+ find: (text) => {
+ const span = matchInlineMathSuffix(text);
+ if (!span) return null;
+ return { index: span.index, text: span.raw, data: { latex: span.latex } };
+ },
+ handler: ({ state, range, match }) => {
+ const latex = match.data?.latex;
+ if (typeof latex !== "string" || !latex) return null;
+ state.tr.replaceWith(range.from, range.to, this.type.create({ latex }));
+ },
+ }),
+ ];
+ },
+
+ addPasteRules() {
+ return [
+ new PasteRule({
+ find: (text) => findInlineMathSpans(text).map((span) => ({
+ index: span.index,
+ text: span.raw,
+ data: { latex: span.latex },
+ })),
+ handler: ({ state, range, match }) => {
+ const latex = match.data?.latex;
+ if (typeof latex !== "string" || !latex || range.from >= range.to) return;
+ if (textAt(state.doc, range.from, range.to) !== match[0]) return;
+
+ const $from = state.doc.resolve(range.from);
+ if ($from.parent.type.spec.code || $from.marks().some((mark) => mark.type.spec.code)) return;
+ state.tr.replaceWith(range.from, range.to, this.type.create({ latex }));
+ },
+ }),
+ ];
+ },
});
const EdgeEverBlockMath = BlockMath.extend({
markdownTokenizer: edgeEverBlockMathMarkdownTokenizer,
+
+ // A display formula is a paragraph of `$$latex$$`. TipTap's own rule expects `$$$latex$$$`.
+ addInputRules() {
+ return [
+ new InputRule({
+ find: (text) => {
+ const block = matchBlockMathText(text);
+ if (!block) return null;
+ return { index: 0, text, data: { latex: block.latex } };
+ },
+ handler: ({ state, range, match }) => {
+ const latex = match.data?.latex;
+ if (typeof latex !== "string" || !latex) return null;
+
+ const $from = state.doc.resolve(range.from);
+ const replacesParagraph = $from.parent.isTextblock
+ && range.from === $from.start()
+ && range.to === $from.end();
+ if (!replacesParagraph || $from.depth < 1) return null;
+ if (!$from.node(-1).canReplaceWith($from.index(-1), $from.indexAfter(-1), this.type)) return null;
+
+ const { tr } = state;
+ tr.replaceWith($from.before(), $from.after(), this.type.create({ latex }));
+ placeCaretAfterBlock(tr, tr.mapping.map($from.after()));
+ },
+ }),
+ ];
+ },
+
+ addPasteRules() {
+ return [
+ new PasteRule({
+ find: (text) => {
+ const block = matchBlockMathText(text);
+ if (!block) return null;
+ const trimmed = text.trim();
+ const index = text.indexOf(trimmed);
+ return [{ index, text: trimmed, data: { latex: block.latex } }];
+ },
+ handler: ({ state, range, match }) => {
+ const latex = match.data?.latex;
+ if (typeof latex !== "string" || !latex || range.from >= range.to) return;
+
+ const $from = state.doc.resolve(range.from);
+ if (!$from.parent.isTextblock || $from.parent.type.spec.code) return;
+ if ($from.parent.textContent.trim() !== match[0]) return;
+ if ($from.depth < 1) return;
+ if (!$from.node(-1).canReplaceWith($from.index(-1), $from.indexAfter(-1), this.type)) return;
+
+ const { tr } = state;
+ const blockStart = $from.before();
+ const blockEnd = $from.after();
+ tr.replaceWith(blockStart, blockEnd, this.type.create({ latex }));
+ const posAfter = tr.mapping.map(blockEnd);
+ const { from, to } = tr.selection;
+ if (from >= tr.mapping.map(blockStart) && to <= posAfter) {
+ placeCaretAfterBlock(tr, posAfter);
+ }
+ },
+ }),
+ ];
+ },
});
const katexOptions = {
diff --git a/packages/shared/src/task-item-input.ts b/packages/shared/src/task-item-input.ts
new file mode 100644
index 00000000..105b03ac
--- /dev/null
+++ b/packages/shared/src/task-item-input.ts
@@ -0,0 +1,79 @@
+import { InputRule } from "@tiptap/core";
+import { TaskItem } from "@tiptap/extension-list";
+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { TextSelection } from "@tiptap/pm/state";
+import { canJoin } from "@tiptap/pm/transform";
+
+// `- `, `* `, and `+ ` already become a bullet list. This recognizes the
+// checklist marker typed next, which is the Obsidian `- [ ] ` sequence.
+const bulletTaskMarker = /^\s*\[([ xX])\] $/;
+
+const convertBulletItemMarkedAsTask: InputRule["handler"] = ({ state, range, match }) => {
+ const checked = match[1]?.toLowerCase() === "x";
+ const $before = state.doc.resolve(range.from);
+ if ($before.parent.type.name !== "paragraph" || $before.depth < 2) return null;
+ if ($before.node(-1).type.name !== "listItem" || $before.node(-2).type.name !== "bulletList") {
+ return null;
+ }
+
+ const taskItemType = state.schema.nodes.taskItem;
+ const taskListType = state.schema.nodes.taskList;
+ if (!taskItemType || !taskListType) return null;
+
+ const tr = state.tr.delete(range.from, range.to);
+ const $pos = tr.doc.resolve(range.from);
+ if ($pos.parent.type.name !== "paragraph" || $pos.depth < 2) return null;
+
+ const listItem = $pos.node(-1);
+ const bulletList = $pos.node(-2);
+ if (listItem.type.name !== "listItem" || bulletList.type.name !== "bulletList") return null;
+
+ const bulletDepth = $pos.depth - 2;
+ const itemIndex = $pos.index(bulletDepth);
+ const taskItem = taskItemType.create({ checked }, listItem.content);
+ const taskList = taskListType.create(null, taskItem);
+ const before: ProseMirrorNode[] = [];
+ const after: ProseMirrorNode[] = [];
+
+ bulletList.forEach((child, _offset, index) => {
+ if (index < itemIndex) before.push(child);
+ else if (index > itemIndex) after.push(child);
+ });
+
+ const replacement = [
+ ...(before.length ? [bulletList.type.create(bulletList.attrs, before)] : []),
+ taskList,
+ ...(after.length ? [bulletList.type.create(bulletList.attrs, after)] : []),
+ ];
+ const bulletStart = $pos.before(bulletDepth);
+ tr.replaceWith(bulletStart, $pos.after(bulletDepth), replacement);
+
+ // bulletStart is the left edge of the replacement, so it still addresses the
+ // new nodes. Mapping it would treat that intermediate position as original.
+ let taskListPos = bulletStart;
+ if (before.length) taskListPos += replacement[0]?.nodeSize ?? 0;
+ const caret = taskListPos + 3;
+ const mapFrom = tr.steps.length;
+ const joinTaskListsAt = (pos: number) => {
+ if (pos <= 0 || pos >= tr.doc.content.size) return;
+ const $join = tr.doc.resolve(pos);
+ if ($join.nodeBefore?.type !== taskListType || $join.nodeAfter?.type !== taskListType) return;
+ if (canJoin(tr.doc, pos)) tr.join(pos);
+ };
+ joinTaskListsAt(taskListPos + taskList.nodeSize);
+ joinTaskListsAt(taskListPos);
+
+ tr.setSelection(TextSelection.create(tr.doc, tr.mapping.slice(mapFrom).map(caret)));
+};
+
+export const createEdgeEverTaskItem = () => TaskItem.extend({
+ addInputRules() {
+ return [
+ new InputRule({
+ find: bulletTaskMarker,
+ handler: convertBulletItemMarkedAsTask,
+ }),
+ ...(this.parent?.() ?? []),
+ ];
+ },
+}).configure({ nested: true });