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): chemical formulas and equations in Insert formula (#718)

Dariusz Koryto526366075ca8
diff --git a/apps/web/src/components/dialogs/MathFormulaDialog.tsx b/apps/web/src/components/dialogs/MathFormulaDialog.tsx
index 5abd468a..2983ac35 100644
--- a/apps/web/src/components/dialogs/MathFormulaDialog.tsx
+++ b/apps/web/src/components/dialogs/MathFormulaDialog.tsx
@@ -1,7 +1,7 @@
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import katex from "katex";
-import { Sigma } from "lucide-react";
+import { FlaskConical, Sigma } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -13,6 +13,17 @@ import {
import type { MathFormulaDraft, MathFormulaKind } from "@/components/editor/math-formula";
import { MathVisualInput } from "@/components/editor/MathVisualInput";
import { hasMathPlaceholders, renderMathPreview } from "@/components/editor/math-formula-preview";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ CHEMISTRY_EXAMPLES,
+ insertChemistryExample,
+ isChemistryLatex,
+ mathFormulaSubjectOf,
+ type MathFormulaSubject,
+} from "@/components/editor/chemistry-formula";
+
+const SEGMENT_ACTIVE = "flex flex-1 items-center justify-center gap-1.5 rounded-sm bg-slate-100 px-3 py-1.5 text-xs font-semibold text-slate-950";
+const SEGMENT_IDLE = "flex flex-1 items-center justify-center gap-1.5 rounded-sm px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-50";
export const MathFormulaDialog = ({
open,
@@ -34,17 +45,40 @@ export const MathFormulaDialog = ({
const [kind, setKind] = useState<MathFormulaKind>(draft?.kind ?? "inline");
const [latex, setLatex] = useState(draft?.latex ?? "");
const [error, setError] = useState<string | null>(null);
+ const [subject, setSubject] = useState<MathFormulaSubject>(mathFormulaSubjectOf(draft?.latex ?? ""));
const [inputMode, setInputMode] = useState<"visual" | "source">("visual");
const editing = typeof draft?.pos === "number";
useEffect(() => {
if (!open) return;
+ const initialLatex = draft?.latex ?? "";
setKind(draft?.kind ?? "inline");
- setLatex(draft?.latex ?? "");
+ setLatex(initialLatex);
setError(null);
- setInputMode("visual");
+ setSubject(mathFormulaSubjectOf(initialLatex));
+ // The visual math editor does not understand \ce or \pu and would rewrite them.
+ setInputMode(isChemistryLatex(initialLatex) ? "source" : "visual");
}, [draft, open]);
+ const changeSubject = (next: MathFormulaSubject) => {
+ setSubject(next);
+ setError(null);
+ setInputMode(next === "chemistry" || isChemistryLatex(latex) ? "source" : "visual");
+ };
+
+ const insertExample = (example: string) => {
+ const input = latexInputRef.current;
+ const start = input?.selectionStart ?? latex.length;
+ const end = input?.selectionEnd ?? latex.length;
+ const next = insertChemistryExample(latex, start, end, example);
+ setLatex(next.value);
+ setError(null);
+ window.requestAnimationFrame(() => {
+ latexInputRef.current?.focus();
+ latexInputRef.current?.setSelectionRange(next.caret, next.caret);
+ });
+ };
+
useEffect(() => {
if (open && inputMode === "source") latexInputRef.current?.focus();
}, [inputMode, open]);
@@ -84,13 +118,29 @@ export const MathFormulaDialog = ({
</DialogTitle>
</DialogHeader>
+ {/* min-w-0: a long formula scrolls inside the preview instead of widening the dialog. */}
<form
- className="space-y-4 px-5 py-4"
+ className="min-w-0 space-y-4 px-5 py-4"
onSubmit={(event) => {
event.preventDefault();
submit();
}}
>
+ <div className="flex rounded-md border border-slate-200 p-0.5" role="group" aria-label={t("mathFormulaDialog.subjectLabel")}>
+ {(["math", "chemistry"] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ className={subject === value ? SEGMENT_ACTIVE : SEGMENT_IDLE}
+ aria-pressed={subject === value}
+ onClick={() => changeSubject(value)}
+ >
+ {value === "math" ? <Sigma className="h-3.5 w-3.5" aria-hidden="true" /> : <FlaskConical className="h-3.5 w-3.5" aria-hidden="true" />}
+ {value === "math" ? t("mathFormulaDialog.subjectMath") : t("mathFormulaDialog.subjectChemistry")}
+ </button>
+ ))}
+ </div>
+
{!editing && (
<div className="flex rounded-md border border-slate-200 p-0.5">
{(["inline", "block"] as const).map((value) => (
@@ -116,12 +166,14 @@ export const MathFormulaDialog = ({
<label htmlFor={latexId} className="text-xs font-medium text-slate-600">
{t(inputMode === "visual" ? "mathFormulaDialog.visualLabel" : "mathFormulaDialog.latexLabel")}
</label>
- <Button type="button" variant="ghost" size="sm" onClick={() => {
- setInputMode(inputMode === "visual" ? "source" : "visual");
- setError(null);
- }}>
- {t(inputMode === "visual" ? "mathFormulaDialog.sourceMode" : "mathFormulaDialog.visualMode")}
- </Button>
+ {subject === "math" && !isChemistryLatex(latex) ? (
+ <Button type="button" variant="ghost" size="sm" onClick={() => {
+ setInputMode(inputMode === "visual" ? "source" : "visual");
+ setError(null);
+ }}>
+ {t(inputMode === "visual" ? "mathFormulaDialog.sourceMode" : "mathFormulaDialog.visualMode")}
+ </Button>
+ ) : null}
</div>
{inputMode === "visual" ? (open ? (
<MathVisualInput
@@ -142,7 +194,7 @@ export const MathFormulaDialog = ({
rows={3}
spellCheck={false}
className="w-full resize-y rounded-md border border-slate-200 bg-card px-3 py-2 font-mono text-sm text-slate-900 outline-none ring-slate-900/15 placeholder:text-slate-400 focus:border-slate-900 focus:ring-2"
- placeholder={t("mathFormulaDialog.latexPlaceholder")}
+ placeholder={subject === "chemistry" ? "\\ce{2H2 + O2 -> 2H2O}" : t("mathFormulaDialog.latexPlaceholder")}
aria-invalid={Boolean(error) || undefined}
onChange={(event) => {
setLatex(event.target.value);
@@ -151,8 +203,37 @@ export const MathFormulaDialog = ({
/>
)}
{inputMode === "source" && incomplete && <p className="text-xs leading-5 text-slate-500" role="status">{t("mathFormulaDialog.incomplete")}</p>}
+ {subject === "chemistry" ? (
+ <p className="text-xs leading-5 text-slate-500">{t("mathFormulaDialog.chemistryHint")}</p>
+ ) : null}
</div>
+ {subject === "chemistry" ? (
+ <div className="space-y-1.5">
+ <p className="text-xs font-medium text-slate-600">{t("mathFormulaDialog.chemistryExamplesLabel")}</p>
+ <div className="flex flex-wrap gap-1.5">
+ {CHEMISTRY_EXAMPLES.map((example) => (
+ <Tooltip key={example.key}>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-8 px-2.5 text-xs font-normal"
+ onClick={() => insertExample(example.latex)}
+ >
+ {t(`mathFormulaDialog.chemistryExamples.${example.key}`)}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span className="font-mono">{example.latex}</span>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </div>
+ </div>
+ ) : null}
+
<div className="space-y-1.5">
<p id={previewId} className="text-xs font-medium text-slate-600">
{t("mathFormulaDialog.preview")}
diff --git a/apps/web/src/components/editor/chemistry-formula.test.mjs b/apps/web/src/components/editor/chemistry-formula.test.mjs
new file mode 100644
index 00000000..b906776b
--- /dev/null
+++ b/apps/web/src/components/editor/chemistry-formula.test.mjs
@@ -0,0 +1,95 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { CHEMISTRY_EXAMPLES, insertChemistryExample, isChemistryLatex, mathFormulaSubjectOf } from "./chemistry-formula.ts";
+import { renderMathPreview } from "./math-formula-preview.ts";
+
+const locales = ["en-US", "pl", "zh-CN", "ja", "ru"].map((name) =>
+ readFileSync(new URL(`../../../../../packages/shared/src/i18n/${name}.ts`, import.meta.url), "utf8"));
+
+describe("chemistry formulas in the formula dialog", () => {
+ test("recognizes mhchem formulas so they open in the chemistry mode", () => {
+ for (const latex of ["\\ce{H2O}", "x + \\ce{CO2}", "\\pu{5 mol}", "\\ce {NaCl}"]) {
+ expect(isChemistryLatex(latex)).toBe(true);
+ expect(mathFormulaSubjectOf(latex)).toBe("chemistry");
+ }
+ for (const latex of ["", "E = mc^2", "\\cent", "\\cos x", "\\put"]) {
+ expect(isChemistryLatex(latex)).toBe(false);
+ expect(mathFormulaSubjectOf(latex)).toBe("math");
+ }
+ });
+
+ test("every example renders inline and as a display formula, with a label in every locale", () => {
+ expect(CHEMISTRY_EXAMPLES.length).toBeGreaterThanOrEqual(8);
+ for (const example of CHEMISTRY_EXAMPLES) {
+ expect(isChemistryLatex(example.latex)).toBe(true);
+ expect(renderMathPreview(example.latex, "inline")).toContain('class="katex"');
+ expect(renderMathPreview(example.latex, "block")).toContain("katex-display");
+ for (const catalog of locales) expect(catalog).toMatch(new RegExp(`\\n\\s+${example.key}: "`));
+ }
+ });
+
+ test("the preview renders reactions with arrows and charges instead of an error", () => {
+ const html = renderMathPreview("\\ce{2H2 + O2 -> 2H2O}", "inline");
+ expect(html).toContain("katex");
+ expect(html).not.toContain("#cc0000");
+ expect(renderMathPreview("\\ce{H2O", "inline")).toBe("");
+ });
+
+ // `|` marks the caret (or `[…]` a selection) in the field before the example is inserted.
+ const insertAt = (template, example) => {
+ const start = template.includes("[") ? template.indexOf("[") : template.indexOf("|");
+ const value = template.replace(/[|[\]]/g, "");
+ const end = template.includes("]") ? template.indexOf("]") - 1 : start;
+ const result = insertChemistryExample(value, start, end, example);
+ return `${result.value.slice(0, result.caret)}|${result.value.slice(result.caret)}`;
+ };
+
+ test("inserts an example into an empty field, at the caret, or inside an open command of the same kind", () => {
+ expect(insertAt("|", "\\ce{H2O}")).toBe("\\ce{H2O}|");
+ expect(insertAt("Water:|", "\\ce{H2O}")).toBe("Water: \\ce{H2O}|");
+ expect(insertAt("a |b", "\\ce{H2O}")).toBe("a \\ce{H2O} |b");
+ expect(insertAt("\\ce{A -> |2H2O}", "\\pu{1 mol}")).toBe("\\ce{A -> \\pu{1 mol} |2H2O}");
+ expect(insertAt("\\ce{A + |B}", "\\ce{H2O}")).toBe("\\ce{A + H2O |B}");
+ expect(insertAt("\\ce{A -> |}", "\\ce{H2O}")).toBe("\\ce{A -> H2O|}");
+ expect(insertAt("\\pu{5 |}", "\\pu{123 kJ/mol}")).toBe("\\pu{5 123 kJ/mol|}");
+ expect(insertAt("[\\ce{X}]", "\\pu{1 mol}")).toBe("\\pu{1 mol}|");
+ });
+
+ test("keeps the whole command when the caret is inside a different command", () => {
+ // Review case: Ion inside \pu used to become \pu{5 SO4^2-} ("Double superscript").
+ expect(insertAt("\\pu{5 |}", "\\ce{SO4^2-}")).toBe("\\pu{5 \\ce{SO4^2-}|}");
+ expect(insertAt("\\ce{A -> |}", "\\pu{123 kJ/mol}")).toBe("\\ce{A -> \\pu{123 kJ/mol}|}");
+ expect(renderMathPreview("\\pu{5 \\ce{SO4^2-}}", "inline")).toContain('class="katex"');
+ expect(renderMathPreview("\\ce{A -> \\pu{123 kJ/mol}}", "inline")).toContain('class="katex"');
+ });
+
+ test("finds the enclosing command past nested groups and escaped braces", () => {
+ expect(insertAt("\\ce{^{14}_{6}C + |}", "\\ce{H2O}")).toBe("\\ce{^{14}_{6}C + H2O|}");
+ expect(insertAt("\\ce{^{14}_{6}C + |}", "\\pu{1 mol}")).toBe("\\ce{^{14}_{6}C + \\pu{1 mol}|}");
+ // The innermost open command decides: \ce nested inside \pu.
+ expect(insertAt("\\pu{5 \\ce{A + |}}", "\\ce{H2O}")).toBe("\\pu{5 \\ce{A + H2O|}}");
+ expect(insertAt("\\pu{5 \\ce{A} |}", "\\ce{H2O}")).toBe("\\pu{5 \\ce{A} \\ce{H2O}|}");
+ // A closed command before the caret does not count.
+ expect(insertAt("\\pu{5 mol} and |", "\\ce{H2O}")).toBe("\\pu{5 mol} and \\ce{H2O}|");
+ expect(insertAt("\\ce{\\{ |}", "\\ce{H2O}")).toBe("\\ce{\\{ H2O|}");
+ });
+
+ test("every example inserted into every kind of context still renders", () => {
+ const contexts = ["|", "x = |", "\\ce{A -> |}", "\\ce{^{14}_{6}C + |}", "\\pu{5 |}", "\\ce{H2O} and |", "\\pu{5 \\ce{A + |}}"];
+ for (const context of contexts) {
+ for (const example of CHEMISTRY_EXAMPLES) {
+ const result = insertAt(context, example.latex).replace("|", "");
+ expect({ context, example: example.key, rendered: renderMathPreview(result, "inline") !== "" })
+ .toEqual({ context, example: example.key, rendered: true });
+ }
+ }
+ });
+
+ test("the dialog keeps chemistry out of the visual math editor and uses shadcn tooltips", () => {
+ const dialog = readFileSync(new URL("../dialogs/MathFormulaDialog.tsx", import.meta.url), "utf8");
+ expect(dialog).toContain('setInputMode(isChemistryLatex(initialLatex) ? "source" : "visual")');
+ expect(dialog).toContain('subject === "math" && !isChemistryLatex(latex)');
+ expect(dialog).toContain("<TooltipContent>");
+ expect(dialog).not.toMatch(/\btitle=/);
+ });
+});
diff --git a/apps/web/src/components/editor/chemistry-formula.ts b/apps/web/src/components/editor/chemistry-formula.ts
new file mode 100644
index 00000000..1d80484a
--- /dev/null
+++ b/apps/web/src/components/editor/chemistry-formula.ts
@@ -0,0 +1,84 @@
+export type MathFormulaSubject = "math" | "chemistry";
+
+/** Formulas written with the KaTeX mhchem commands `\ce{…}` or `\pu{…}`. */
+export const isChemistryLatex = (latex: string) => /\\(?:ce|pu)\s*\{/.test(latex);
+
+export const mathFormulaSubjectOf = (latex: string): MathFormulaSubject =>
+ isChemistryLatex(latex) ? "chemistry" : "math";
+
+export type ChemistryExample = {
+ /** Key under `mathFormulaDialog.chemistryExamples`. */
+ key: string;
+ latex: string;
+};
+
+/** One-click starting points that cover the mhchem syntax people need most. */
+export const CHEMISTRY_EXAMPLES: readonly ChemistryExample[] = [
+ { key: "formula", latex: "\\ce{H2O}" },
+ { key: "ion", latex: "\\ce{SO4^2-}" },
+ { key: "reaction", latex: "\\ce{2H2 + O2 -> 2H2O}" },
+ { key: "equilibrium", latex: "\\ce{N2 + 3H2 <=> 2NH3}" },
+ { key: "conditions", latex: "\\ce{CaCO3 ->[\\Delta] CaO + CO2}" },
+ { key: "gasPrecipitate", latex: "\\ce{Ag+ + Cl- -> AgCl v}" },
+ { key: "states", latex: "\\ce{NaCl(s) -> Na+(aq) + Cl-(aq)}" },
+ { key: "isotope", latex: "\\ce{^{14}_{6}C}" },
+ { key: "hydrate", latex: "\\ce{CuSO4*5H2O}" },
+ { key: "units", latex: "\\pu{123 kJ/mol}" },
+];
+
+type ChemistryCommand = "ce" | "pu";
+
+const exampleCommand = (example: string) => /^\\(ce|pu)\{([\s\S]*)\}$/.exec(example) as
+ | (RegExpExecArray & [string, ChemistryCommand, string])
+ | null;
+
+/**
+ * The `\ce{…}` or `\pu{…}` whose braces are still open at the end of `before`,
+ * found by brace depth so nested groups such as `^{14}_{6}` are skipped.
+ */
+const enclosingCommand = (before: string): ChemistryCommand | null => {
+ const open: Array<ChemistryCommand | null> = [];
+ for (let index = 0; index < before.length; index += 1) {
+ const char = before[index];
+ if (char === "\\") {
+ index += 1;
+ continue;
+ }
+ if (char === "{") {
+ const command = /\\(ce|pu)\s*$/.exec(before.slice(0, index))?.[1] as ChemistryCommand | undefined;
+ open.push(command ?? null);
+ } else if (char === "}") {
+ open.pop();
+ }
+ }
+ for (let level = open.length - 1; level >= 0; level -= 1) {
+ if (open[level]) return open[level]!;
+ }
+ return null;
+};
+
+/**
+ * Inserts an example at the caret. An empty field takes the example as is. A
+ * caret inside an open command of the same kind (`\ce` in `\ce`, `\pu` in
+ * `\pu`) gets only the example's content, so the result stays one command.
+ * Any other position keeps the whole command: `\ce` syntax inside `\pu` (or
+ * the reverse) is not valid and cannot be rendered.
+ */
+export const insertChemistryExample = (
+ value: string,
+ selectionStart: number,
+ selectionEnd: number,
+ example: string,
+) => {
+ if (!value.trim()) return { value: example, caret: example.length };
+ const before = value.slice(0, selectionStart);
+ const after = value.slice(selectionEnd);
+ const parsed = exampleCommand(example);
+ const sameCommand = parsed !== null && enclosingCommand(before) === parsed[1];
+ const text = sameCommand ? parsed[2] : example;
+ // Keep the example apart from the text around it, but not from a closing brace.
+ const leading = before && !/\s$/.test(before) ? " " : "";
+ const trailing = after && !/^[\s}]/.test(after) ? " " : "";
+ const inserted = `${leading}${text}${trailing}`;
+ return { value: `${before}${inserted}${after}`, caret: before.length + inserted.length };
+};
diff --git a/apps/web/src/components/editor/math-formula-preview.ts b/apps/web/src/components/editor/math-formula-preview.ts
index 1d95567e..77407b06 100644
--- a/apps/web/src/components/editor/math-formula-preview.ts
+++ b/apps/web/src/components/editor/math-formula-preview.ts
@@ -1,4 +1,5 @@
import katex from "katex";
+import "katex/contrib/mhchem";
import type { MathFormulaKind } from "./math-formula";
export const hasMathPlaceholders = (latex: string) => /\\placeholder\b/.test(latex);
diff --git a/apps/web/src/lib/wechat-copy.ts b/apps/web/src/lib/wechat-copy.ts
index 5dc99679..e5c01837 100644
--- a/apps/web/src/lib/wechat-copy.ts
+++ b/apps/web/src/lib/wechat-copy.ts
@@ -10,6 +10,7 @@ import {
type NoteProsePaletteColors,
} from "@edgeever/shared";
import katex from "katex";
+import "katex/contrib/mhchem";
import { common, createLowlight } from "lowlight";
import { toCanvas } from "html-to-image";
import { marked } from "marked";
diff --git a/docs/changes/2026-10-28-chemistry-formulas.md b/docs/changes/2026-10-28-chemistry-formulas.md
new file mode 100644
index 00000000..7dc0b540
--- /dev/null
+++ b/docs/changes/2026-10-28-chemistry-formulas.md
@@ -0,0 +1,20 @@
+# Chemical formulas and equations in "Insert formula"
+
+[简体中文](2026-10-28-chemistry-formulas.zh-CN.md)
+
+## Problem and outcome
+
+Implements [Issue #717](https://github.com/tianma-if/edgeever/issues/717). Chemistry had to be written by hand with subscripts, superscripts, arrow commands and `\mathrm{}`. Note math now understands the KaTeX `mhchem` extension: `\ce{…}` for formulas and equations and `\pu{…}` for quantities with units. The "Insert formula" dialog has a Math / Chemistry switch with one-click examples.
+
+## Behavior
+
+| ID | Behavior | Acceptance |
+| --- | --- | --- |
+| C01 | `katex/contrib/mhchem` is registered by the shared math extensions, so `\ce` and `\pu` render in the web and desktop editor, the Android and iOS editors, public share pages and notebook sites. The dialog preview and the WeChat copy register it as well. `trust: false` still applies; commands such as `\href` inside `\ce` stay inert text. | Shared tests render every example inline and as a display formula through the shared module only, and fail without the registration. |
+| C02 | Formulas are stored unchanged as inline or display math (`$\ce{H2O}$`, `$$…$$`). There is no data, API or migration change. | Markdown round-trip test. |
+| C03 | The dialog's Math / Chemistry switch is shown for new and existing formulas. Chemistry uses the LaTeX source field, because the visual math editor would rewrite `\ce`; a formula containing `\ce` or `\pu` opens in this mode, and the visual editor toggle is hidden while the source contains them. | Browser test: insert, edit and reopen inline and display chemistry. |
+| C04 | Ten examples (formula, ion, reaction, equilibrium, conditions on the arrow, gas/precipitate, states of matter, isotope, hydrate, units) insert at the caret; inside an open `\ce{…}` only the example's content is inserted. Each example has a Tooltip with its source. Copy is in all shipped locales. | Unit tests for insertion and labels; browser test in `pl-PL` at 1280 px and 390 px. |
+
+## Risk and rollback
+
+The editor bundle grows by the mhchem module (about 34 KB minified). Older app versions show existing `\ce` formulas as render errors until they update; the stored text is unchanged. The committed iOS editor bundle (`apps/ios/EditorBundle`) has to be rebuilt in the usual iOS release step to include the extension. Rollback is a revert; stored chemistry formulas then show as render errors again.
diff --git a/docs/changes/2026-10-28-chemistry-formulas.zh-CN.md b/docs/changes/2026-10-28-chemistry-formulas.zh-CN.md
new file mode 100644
index 00000000..7fec6839
--- /dev/null
+++ b/docs/changes/2026-10-28-chemistry-formulas.zh-CN.md
@@ -0,0 +1,20 @@
+# “插入公式”支持化学式与化学方程式
+
+[English](2026-10-28-chemistry-formulas.md)
+
+## 问题与结果
+
+实现 [Issue #717](https://github.com/tianma-if/edgeever/issues/717)。此前化学式只能手动用上下标、箭头命令和 `\mathrm{}` 拼写。笔记中的公式现在支持 KaTeX 的 `mhchem` 扩展:`\ce{…}` 用于化学式和化学方程式,`\pu{…}` 用于带单位的物理量。“插入公式”对话框新增“数学 / 化学”切换,并提供一键示例。
+
+## 行为
+
+| ID | 行为 | 验收 |
+| --- | --- | --- |
+| C01 | 共享公式扩展注册 `katex/contrib/mhchem`,因此 `\ce` 和 `\pu` 可在 Web 与桌面编辑器、Android 与 iOS 编辑器、公开分享页和笔记本站点中渲染。对话框预览和公众号复制同样注册该扩展。`trust: false` 仍然生效,`\ce` 中的 `\href` 等命令只作为无效文本显示。 | 共享测试仅通过共享模块渲染所有示例(行内与独立公式),移除注册后测试失败。 |
+| C02 | 公式按原样保存为行内或独立公式(`$\ce{H2O}$`、`$$…$$`),没有数据、API 或迁移变化。 | Markdown 往返测试。 |
+| C03 | 新建和编辑公式时都显示“数学 / 化学”切换。化学模式使用 LaTeX 源码输入,因为可视化数学编辑器会改写 `\ce`;包含 `\ce` 或 `\pu` 的公式会以该模式打开,源码中包含它们时隐藏可视化编辑器切换。 | 浏览器测试:插入、编辑并重新打开行内和独立化学公式。 |
+| C04 | 十个示例(化学式、离子、反应、平衡、反应条件、气体/沉淀、物态、同位素、结晶水合物、单位)插入到光标处;光标位于未闭合的 `\ce{…}` 中时只插入示例内容。每个示例都有显示源码的 Tooltip。所有已发布语言均有文案。 | 插入逻辑与文案的单元测试;`pl-PL` 下 1280 px 和 390 px 的浏览器测试。 |
+
+## 风险与回滚
+
+编辑器包增加 mhchem 模块(压缩后约 34 KB)。旧版本应用在更新前会把已有的 `\ce` 公式显示为渲染错误,保存的文本不变。仓库中提交的 iOS 编辑器包(`apps/ios/EditorBundle`)需要在常规 iOS 发布步骤中重新构建才会包含该扩展。回滚即 revert;回滚后已保存的化学公式会重新显示为渲染错误。
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 6a5acb42..3c5c256e 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -3099,6 +3099,23 @@ export const enUS = {
loading: "Loading formula editor…",
loadError: "The visual editor could not load. You can continue with LaTeX.",
incomplete: "Type in an empty slot; press Tab for the next one",
+ subjectLabel: "Formula type",
+ subjectMath: "Math",
+ subjectChemistry: "Chemistry",
+ chemistryHint: "Write chemistry with \\ce{…} and quantities with \\pu{…}: -> reaction, <=> equilibrium, ^ gas, v precipitate.",
+ chemistryExamplesLabel: "Insert an example",
+ chemistryExamples: {
+ formula: "Formula",
+ ion: "Ion",
+ reaction: "Reaction",
+ equilibrium: "Equilibrium",
+ conditions: "Conditions on the arrow",
+ gasPrecipitate: "Gas / precipitate",
+ states: "States of matter",
+ isotope: "Isotope",
+ hydrate: "Hydrate",
+ units: "Units",
+ },
},
noteLinkPicker: {
title: "Link a note",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index d8fc535a..249f1ae7 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -3088,6 +3088,23 @@ export const ja = {
loading: "数式エディターを読み込み中…",
loadError: "ビジュアルエディターを読み込めませんでした。LaTeX で編集できます。",
incomplete: "空欄に入力し、Tab キーで次の空欄へ移動",
+ subjectLabel: "数式の種類",
+ subjectMath: "数学",
+ subjectChemistry: "化学",
+ chemistryHint: "化学式は \\ce{…}、単位付きの量は \\pu{…} で書きます:-> 反応、<=> 平衡、^ 気体、v 沈殿。",
+ chemistryExamplesLabel: "例を挿入",
+ chemistryExamples: {
+ formula: "化学式",
+ ion: "イオン",
+ reaction: "反応",
+ equilibrium: "平衡",
+ conditions: "矢印上の条件",
+ gasPrecipitate: "気体 / 沈殿",
+ states: "状態",
+ isotope: "同位体",
+ hydrate: "水和物",
+ units: "単位",
+ },
},
noteLinkPicker: {
title: "ノートをリンク",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 7b5a27b9..00e6a7eb 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -3088,6 +3088,23 @@ export const pl = {
loading: "Ładowanie edytora wzorów…",
loadError: "Nie udało się załadować edytora wizualnego. Możesz użyć LaTeX.",
incomplete: "Wpisz w pustym polu; Tab przechodzi do następnego",
+ subjectLabel: "Rodzaj wzoru",
+ subjectMath: "Matematyka",
+ subjectChemistry: "Chemia",
+ chemistryHint: "Wzory chemiczne zapisuj w \\ce{…}, a wielkości z jednostkami w \\pu{…}: -> reakcja, <=> równowaga, ^ gaz, v osad.",
+ chemistryExamplesLabel: "Wstaw przykład",
+ chemistryExamples: {
+ formula: "Wzór",
+ ion: "Jon",
+ reaction: "Reakcja",
+ equilibrium: "Równowaga",
+ conditions: "Warunki nad strzałką",
+ gasPrecipitate: "Gaz / osad",
+ states: "Stany skupienia",
+ isotope: "Izotop",
+ hydrate: "Hydrat",
+ units: "Jednostki",
+ },
},
noteLinkPicker: {
title: "Połącz z notatką",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index f7f1b909..8b80f6b1 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -3099,6 +3099,23 @@ export const ru = {
loading: "Загрузка редактора формул…",
loadError: "Визуальный редактор не загрузился. Можно продолжить в LaTeX.",
incomplete: "Введите текст в пустой слот; Tab — следующий",
+ subjectLabel: "Тип формулы",
+ subjectMath: "Математика",
+ subjectChemistry: "Химия",
+ chemistryHint: "Химические формулы пишите в \\ce{…}, величины с единицами — в \\pu{…}: -> реакция, <=> равновесие, ^ газ, v осадок.",
+ chemistryExamplesLabel: "Вставить пример",
+ chemistryExamples: {
+ formula: "Формула",
+ ion: "Ион",
+ reaction: "Реакция",
+ equilibrium: "Равновесие",
+ conditions: "Условия над стрелкой",
+ gasPrecipitate: "Газ / осадок",
+ states: "Агрегатные состояния",
+ isotope: "Изотоп",
+ hydrate: "Кристаллогидрат",
+ units: "Единицы",
+ },
},
noteLinkPicker: {
title: "Ссылка на заметку",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 6f544cea..728e6caa 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -3097,6 +3097,23 @@ export const zhCN = {
loading: "正在加载公式编辑器…",
loadError: "可视化编辑器暂时无法加载,可继续使用 LaTeX。",
incomplete: "在空框中输入,按 Tab 切换到下一处",
+ subjectLabel: "公式类型",
+ subjectMath: "数学",
+ subjectChemistry: "化学",
+ chemistryHint: "化学式写在 \\ce{…} 中,带单位的量写在 \\pu{…} 中:-> 反应,<=> 平衡,^ 气体,v 沉淀。",
+ chemistryExamplesLabel: "插入示例",
+ chemistryExamples: {
+ formula: "化学式",
+ ion: "离子",
+ reaction: "反应",
+ equilibrium: "平衡",
+ conditions: "反应条件",
+ gasPrecipitate: "气体 / 沉淀",
+ states: "物态",
+ isotope: "同位素",
+ hydrate: "结晶水合物",
+ units: "单位",
+ },
},
noteLinkPicker: {
title: "引用笔记",
diff --git a/packages/shared/src/mathematics-chemistry.test.mjs b/packages/shared/src/mathematics-chemistry.test.mjs
new file mode 100644
index 00000000..52cc1ccd
--- /dev/null
+++ b/packages/shared/src/mathematics-chemistry.test.mjs
@@ -0,0 +1,46 @@
+import { describe, expect, test } from "bun:test";
+import katex from "katex";
+// Only the shared math module is imported: it must register mhchem for every client.
+import { createEdgeEverMathematics } from "./mathematics.ts";
+import { docToMarkdown, markdownToDoc } from "./content.ts";
+
+const options = { throwOnError: true, strict: "warn", trust: false };
+
+describe("chemistry formulas", () => {
+ test("the shared math extensions register \\ce and \\pu on KaTeX", () => {
+ expect(createEdgeEverMathematics()).toHaveLength(2);
+ for (const latex of [
+ "\\ce{H2O}",
+ "\\ce{SO4^2-}",
+ "\\ce{2H2 + O2 -> 2H2O}",
+ "\\ce{N2 + 3H2 <=> 2NH3}",
+ "\\ce{CaCO3 ->[\\Delta] CaO + CO2}",
+ "\\ce{Ag+ + Cl- -> AgCl v}",
+ "\\ce{NaCl(s) -> Na+(aq) + Cl-(aq)}",
+ "\\ce{^{14}_{6}C}",
+ "\\ce{CuSO4*5H2O}",
+ "\\pu{123 kJ/mol}",
+ ]) {
+ expect(katex.renderToString(latex, options)).toContain('class="katex"');
+ expect(katex.renderToString(latex, { ...options, displayMode: true })).toContain("katex-display");
+ }
+ });
+
+ test("keeps links and other untrusted commands inert inside \\ce", () => {
+ const html = katex.renderToString("\\ce{\\href{javascript:alert(1)}{x}}", options);
+ expect(html).not.toMatch(/<a[\s>]/);
+ expect(html).not.toContain('href="javascript');
+ });
+
+ test("stores chemistry as ordinary inline and display math in Markdown", () => {
+ const markdown = "Water $\\ce{H2O}$ forms:\n\n$$\\ce{2H2 + O2 -> 2H2O}$$\n";
+ const doc = markdownToDoc(markdown);
+ const nodes = JSON.stringify(doc);
+ expect(nodes).toContain('"latex":"\\\\ce{H2O}"');
+ expect(nodes).toContain('"latex":"\\\\ce{2H2 + O2 -> 2H2O}"');
+ const roundTrip = docToMarkdown(doc);
+ expect(roundTrip).toContain("$\\ce{H2O}$");
+ expect(roundTrip).toContain("$$\n\\ce{2H2 + O2 -> 2H2O}\n$$");
+ expect(markdownToDoc(roundTrip)).toEqual(doc);
+ });
+});
diff --git a/packages/shared/src/mathematics.ts b/packages/shared/src/mathematics.ts
index 63431021..4977ea51 100644
--- a/packages/shared/src/mathematics.ts
+++ b/packages/shared/src/mathematics.ts
@@ -2,6 +2,9 @@ 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";
+// Registers \ce{...} and \pu{...} (chemical formulas, equations and units) on
+// the KaTeX instance the math nodes render with, on every client.
+import "katex/contrib/mhchem";
import {
edgeEverBlockMathMarkdownTokenizer,
edgeEverInlineMathMarkdownTokenizer,
diff --git a/tests/e2e/chemistry-formula.spec.ts b/tests/e2e/chemistry-formula.spec.ts
new file mode 100644
index 00000000..b802bead
--- /dev/null
+++ b/tests/e2e/chemistry-formula.spec.ts
@@ -0,0 +1,190 @@
+import { expect, test, type Locator, type Page } from "@playwright/test";
+
+test.use({ locale: "en-US" });
+test.setTimeout(90_000);
+
+const createMemo = async (page: Page, title: string, contentMarkdown = "") => {
+ 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 deleteMemo = async (page: Page, memoId: string) => {
+ await page.request.delete(`/api/v1/memos/${memoId}`);
+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);
+};
+
+const openMemo = async (page: Page, memoId: string, title: string) => {
+ 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="${memoId}"]`).locator("button").first().click();
+ const editor = page.locator(".ProseMirror[contenteditable='true']");
+ await expect(editor).toBeEditable();
+ return editor;
+};
+
+const savedMarkdown = (page: Page, memoId: string) => async () => {
+ const body = await (await page.request.get(`/api/v1/memos/${memoId}`)).json() as { memo: { contentMarkdown: string } };
+ return body.memo.contentMarkdown;
+};
+
+// KaTeX marks commands it cannot render in red, and the math nodes flag parse errors.
+const RENDER_ERROR = "[style*='#cc0000'], [mathcolor='#cc0000'], .block-math-error, .inline-math-error";
+const BLOCK_MATH = "[data-type='block-math']";
+
+// A real click on the rendered formula, as a user makes it. Playwright's own
+// actionability check reports the surrounding paragraph as covering the inline node.
+const clickFormula = async (page: Page, formula: Locator) => {
+ const box = (await formula.boundingBox())!;
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+};
+
+test("inserts chemistry examples inline and as a display formula, then reopens them for editing", async ({ page }) => {
+ const title = `Chemistry formula ${Date.now()}`;
+ const memo = await createMemo(page, title, "Water is\n\nReaction below");
+ try {
+ const editor = await openMemo(page, memo.id, title);
+ await editor.getByText("Water is").click();
+ await page.keyboard.press("End");
+ await page.keyboard.type(" ");
+
+ // Inline: a single example from the chemistry mode.
+ await page.getByRole("button", { name: "Insert formula" }).click();
+ const dialog = page.getByRole("dialog");
+ await dialog.getByRole("button", { name: "Chemistry" }).click();
+ await expect(dialog.getByRole("button", { name: "Chemistry" })).toHaveAttribute("aria-pressed", "true");
+ // Chemistry has no visual editor toggle; the LaTeX source is the input.
+ await expect(dialog.getByRole("button", { name: "Visual editor" })).toHaveCount(0);
+ await expect(dialog.getByRole("button", { name: "LaTeX source" })).toHaveCount(0);
+ await dialog.getByRole("button", { name: "Formula", exact: true }).click();
+ await expect(dialog.locator("textarea")).toHaveValue("\\ce{H2O}");
+ await expect(dialog.locator(".katex")).toBeVisible();
+ await dialog.getByRole("button", { name: "Apply" }).click();
+ await expect(dialog).toBeHidden();
+ await expect(editor.locator(".katex").first()).toBeVisible();
+
+ // Display: start from an example and add the gas arrow by hand.
+ // An automated click right after the dialog closes can lose to ProseMirror
+ // restoring its selection on focus (see #719), so the caret is placed twice.
+ await editor.getByText("Reaction below").click();
+ await editor.getByText("Reaction below").click();
+ await page.keyboard.press("End");
+ await page.keyboard.press("Enter");
+ await page.getByRole("button", { name: "Insert formula" }).click();
+ await expect(dialog.getByRole("heading", { name: "Insert formula" })).toBeVisible();
+ await dialog.getByRole("button", { name: "Chemistry" }).click();
+ await dialog.getByRole("button", { name: "Display" }).click();
+ await dialog.getByRole("button", { name: "Conditions on the arrow" }).click();
+ await expect(dialog.locator("textarea")).toHaveValue("\\ce{CaCO3 ->[\\Delta] CaO + CO2}");
+ await dialog.locator("textarea").press("End");
+ await dialog.locator("textarea").press("ArrowLeft");
+ await dialog.locator("textarea").pressSequentially(" ^");
+ await expect(dialog.locator("textarea")).toHaveValue("\\ce{CaCO3 ->[\\Delta] CaO + CO2 ^}");
+ await expect(dialog.locator(".katex-display")).toBeVisible();
+ await expect(dialog.locator(RENDER_ERROR)).toHaveCount(0);
+ await dialog.getByRole("button", { name: "Apply" }).click();
+ await expect(dialog).toBeHidden();
+ await expect(editor.locator(BLOCK_MATH)).toHaveCount(1);
+ await expect(editor.locator(BLOCK_MATH).locator(".katex")).toBeVisible();
+ await expect(editor.locator(RENDER_ERROR)).toHaveCount(0);
+
+ await expect.poll(savedMarkdown(page, memo.id), { timeout: 20_000 }).toContain("$\\ce{H2O}$");
+ await expect.poll(savedMarkdown(page, memo.id), { timeout: 20_000 }).toContain("\\ce{CaCO3 ->[\\Delta] CaO + CO2 ^}");
+
+ // Editing an existing chemistry formula opens the chemistry mode with its source.
+ await clickFormula(page, editor.locator(BLOCK_MATH));
+ await expect(dialog.getByRole("heading", { name: "Edit formula" })).toBeVisible();
+ await expect(dialog.getByRole("button", { name: "Chemistry" })).toHaveAttribute("aria-pressed", "true");
+ await expect(dialog.locator("textarea")).toHaveValue("\\ce{CaCO3 ->[\\Delta] CaO + CO2 ^}");
+ await dialog.getByRole("button", { name: "Cancel" }).click();
+ } finally {
+ await deleteMemo(page, memo.id);
+ }
+});
+
+test("renders stored chemistry in the editor and on the public share page", async ({ page }) => {
+ const title = `Chemistry share ${Date.now()}`;
+ const memo = await createMemo(page, title, [
+ "Ions $\\ce{SO4^2-}$ and $\\ce{Na+(aq)}$, isotope $\\ce{^{14}_{6}C}$, hydrate $\\ce{CuSO4*5H2O}$, energy $\\pu{-286 kJ/mol}$.",
+ "",
+ "$$",
+ "\\ce{N2 + 3H2 <=> 2NH3}",
+ "$$",
+ "",
+ "Math still works: $E = mc^2$.",
+ ].join("\n"));
+ try {
+ const editor = await openMemo(page, memo.id, title);
+ await expect(editor.locator(".katex")).toHaveCount(7);
+ await expect(editor.locator(BLOCK_MATH)).toHaveCount(1);
+ await expect(editor.locator(RENDER_ERROR)).toHaveCount(0);
+
+ // An ordinary math formula still opens in the math mode.
+ const dialog = page.getByRole("dialog");
+ await clickFormula(page, editor.locator("[data-type='inline-math']").last());
+ await expect(dialog.getByRole("button", { name: "Math" })).toHaveAttribute("aria-pressed", "true");
+ await page.keyboard.press("Escape");
+ await expect(dialog).toBeHidden();
+ // A stored chemistry formula opens in the chemistry mode, without the visual editor.
+ await clickFormula(page, editor.locator("[data-type='inline-math']").first());
+ await expect(dialog.getByRole("button", { name: "Chemistry" })).toHaveAttribute("aria-pressed", "true");
+ await expect(dialog.locator("textarea")).toHaveValue("\\ce{SO4^2-}");
+ await expect(dialog.locator("math-field")).toHaveCount(0);
+ await dialog.getByRole("button", { name: "Cancel" }).click();
+
+ const share = (await (await page.request.post(`/api/v1/memos/${memo.id}/share`, { data: {} })).json()).share as { token: string };
+ await page.goto(`/share/${share.token}`);
+ const article = page.locator("article").last();
+ await expect(article.locator(".katex")).toHaveCount(7);
+ await expect(article.locator(BLOCK_MATH)).toHaveCount(1);
+ await expect(article.locator(RENDER_ERROR)).toHaveCount(0);
+ } finally {
+ await deleteMemo(page, memo.id);
+ }
+});
+
+test("examples keep their command inside a different command and unwrap inside the same one", async ({ page }) => {
+ const title = `Chemistry nesting ${Date.now()}`;
+ const memo = await createMemo(page, title, "Energy");
+ try {
+ const editor = await openMemo(page, memo.id, title);
+ await editor.getByText("Energy").click();
+ await page.keyboard.press("End");
+ await page.getByRole("button", { name: "Insert formula" }).click();
+ const dialog = page.getByRole("dialog");
+ const source = dialog.locator("textarea");
+ await dialog.getByRole("button", { name: "Chemistry" }).click();
+
+ // Review case: an ion inside \pu stays a \ce command instead of "Double superscript".
+ await source.fill("\\pu{5 }");
+ await source.evaluate((element: HTMLTextAreaElement) => element.setSelectionRange(6, 6));
+ await dialog.getByRole("button", { name: "Ion", exact: true }).click();
+ await expect(source).toHaveValue("\\pu{5 \\ce{SO4^2-}}");
+ await expect(dialog.locator(".katex")).toBeVisible();
+ await expect(dialog.locator(RENDER_ERROR)).toHaveCount(0);
+
+ // Units inside a reaction keep \pu; a formula inside the same \ce is unwrapped.
+ await source.fill("\\ce{A -> }");
+ await source.evaluate((element: HTMLTextAreaElement) => element.setSelectionRange(9, 9));
+ await dialog.getByRole("button", { name: "Units", exact: true }).click();
+ await expect(source).toHaveValue("\\ce{A -> \\pu{123 kJ/mol}}");
+ // The dialog moves the caret after the inserted example on the next frame.
+ await expect.poll(() => source.evaluate((element: HTMLTextAreaElement) => element.selectionStart)).toBe(24);
+ await source.evaluate((element: HTMLTextAreaElement) => element.setSelectionRange(5, 5));
+ await dialog.getByRole("button", { name: "Formula", exact: true }).click();
+ await expect(source).toHaveValue("\\ce{A H2O -> \\pu{123 kJ/mol}}");
+ await expect(dialog.locator(RENDER_ERROR)).toHaveCount(0);
+
+ await dialog.getByRole("button", { name: "Apply" }).click();
+ await expect(dialog).toBeHidden();
+ await expect(editor.locator("[data-type='inline-math']")).toHaveCount(1);
+ await expect(editor.locator(RENDER_ERROR)).toHaveCount(0);
+ await expect.poll(savedMarkdown(page, memo.id), { timeout: 20_000 }).toContain("$\\ce{A H2O -> \\pu{123 kJ/mol}}$");
+ } finally {
+ await deleteMemo(page, memo.id);
+ }
+});