@viveeditor/ext-math 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 viveEditor contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @viveeditor/ext-math
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ LaTeX formulas for viveEditor, rendered with a KaTeX copy the site loads on demand.
4
+
5
+ Part of [viveEditor](https://github.com/mtvrkan/viveeditor#readme), a free, open-source rich text editor.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @viveeditor/ext-math @viveeditor/core katex
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { Editor } from '@viveeditor/core'
17
+ import '@viveeditor/core/style.css'
18
+ import { MathExtension } from '@viveeditor/ext-math'
19
+ import '@viveeditor/ext-math/style.css'
20
+ import 'katex/dist/katex.min.css'
21
+
22
+ const editor = await Editor.create(document.querySelector('#editor'), {
23
+ extensions: [MathExtension.configure({ load: () => import('katex') })],
24
+ })
25
+ ```
26
+
27
+ The editor stores the LaTeX source. KaTeX **0.18.2 or newer** is required; older versions are refused. On published pages call `renderMath(root, { load: () => import('katex') })` from `@viveeditor/ext-math/render`.
28
+
29
+ ## License
30
+
31
+ MIT
@@ -0,0 +1,26 @@
1
+ import { a as MIN_KATEX_VERSION, c as isSupportedKatex, i as MAX_LATEX_LENGTH, n as KatexLoader, o as MathError, r as KatexModule, s as MathErrorCode, t as KatexLike } from "./katex-517YH_fa.js";
2
+ import { Extension } from "@viveeditor/core";
3
+ import { Command } from "prosemirror-state";
4
+ import "prosemirror-model";
5
+ import "prosemirror-view";
6
+ interface MathLabels {
7
+ empty: string;
8
+ edit: string;
9
+ }
10
+ export interface MathOptions {
11
+ load: KatexLoader | null;
12
+ labels: MathLabels;
13
+ onError: ((error: MathError) => void) | null;
14
+ }
15
+ export interface InsertMathOptions {
16
+ display?: boolean;
17
+ latex?: string;
18
+ }
19
+ declare module "@viveeditor/core" {
20
+ interface CommandRegistry {
21
+ insertMath: (options?: InsertMathOptions) => Command;
22
+ }
23
+ }
24
+ export declare const MathExtension: Extension<MathOptions>;
25
+ export { type KatexLike, type KatexLoader, type KatexModule, MAX_LATEX_LENGTH, MIN_KATEX_VERSION, type MathError, type MathErrorCode, type MathLabels, isSupportedKatex };
26
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,271 @@
1
+ import { a as katexLoader, i as isSupportedKatex, n as MIN_KATEX_VERSION, o as renderLatex, r as cleanLatex, t as MAX_LATEX_LENGTH } from "./katex-ckeBhi54.js";
2
+ import { defineExtension } from "@viveeditor/core";
3
+ import { InputRule } from "prosemirror-inputrules";
4
+ import { NodeSelection, Plugin, TextSelection } from "prosemirror-state";
5
+ // src/view.ts
6
+ const PREVIEW_DELAY = 100;
7
+ const views = /* @__PURE__ */ new WeakMap();
8
+ const mathViewOf = (dom) => dom instanceof Element ? views.get(dom) : void 0;
9
+ var MathView = class {
10
+ node;
11
+ view;
12
+ getPos;
13
+ settings;
14
+ dom;
15
+ katex = null;
16
+ field = null;
17
+ timer = 0;
18
+ destroyed = false;
19
+ constructor(node, view, getPos, settings) {
20
+ this.node = node;
21
+ this.view = view;
22
+ this.getPos = getPos;
23
+ this.settings = settings;
24
+ this.dom = document.createElement(this.display ? "div" : "span");
25
+ this.dom.className = "vive-math";
26
+ this.dom.dataset.math = this.display ? "block" : "inline";
27
+ this.dom.contentEditable = "false";
28
+ this.dom.addEventListener("click", () => this.open());
29
+ views.set(this.dom, this);
30
+ this.render();
31
+ settings.katex().then((katex) => {
32
+ this.katex = katex;
33
+ if (katex && !this.destroyed && !this.field) this.render();
34
+ });
35
+ }
36
+ get display() {
37
+ return this.node.type.name === "mathBlock";
38
+ }
39
+ get latex() {
40
+ return cleanLatex(this.node.attrs.latex) ?? "";
41
+ }
42
+ update(node) {
43
+ if (node.type !== this.node.type) return false;
44
+ this.node = node;
45
+ if (!this.field) this.render();
46
+ return true;
47
+ }
48
+ selectNode() {
49
+ this.dom.classList.add("ProseMirror-selectednode");
50
+ if (this.latex === "") this.open();
51
+ }
52
+ deselectNode() {
53
+ this.dom.classList.remove("ProseMirror-selectednode");
54
+ }
55
+ stopEvent(event) {
56
+ return this.field !== null && event.target instanceof Node && this.dom.contains(event.target);
57
+ }
58
+ ignoreMutation(mutation) {
59
+ return mutation.type !== "selection" || this.field !== null;
60
+ }
61
+ destroy() {
62
+ this.destroyed = true;
63
+ window.clearTimeout(this.timer);
64
+ }
65
+ open() {
66
+ if (this.field || !this.view.editable || this.getPos() === void 0) return;
67
+ const field = document.createElement(this.display ? "textarea" : "input");
68
+ field.className = "vive-math-field";
69
+ field.value = this.latex;
70
+ field.spellcheck = false;
71
+ field.setAttribute("aria-label", this.settings.labels.edit);
72
+ field.setAttribute("maxlength", "2000");
73
+ const preview = document.createElement(this.display ? "div" : "span");
74
+ preview.className = "vive-math-preview";
75
+ preview.setAttribute("aria-hidden", "true");
76
+ this.field = field;
77
+ this.dom.classList.add("is-editing");
78
+ this.dom.replaceChildren(field, preview);
79
+ this.preview(preview);
80
+ field.addEventListener("input", () => {
81
+ window.clearTimeout(this.timer);
82
+ this.timer = window.setTimeout(() => this.preview(preview), PREVIEW_DELAY);
83
+ });
84
+ field.addEventListener("keydown", (event) => {
85
+ if (!(event instanceof KeyboardEvent)) return;
86
+ if (this.display ? event.key === "Enter" && (event.metaKey || event.ctrlKey) : event.key === "Enter") {
87
+ event.preventDefault();
88
+ this.close(true);
89
+ } else if (event.key === "Escape") {
90
+ event.preventDefault();
91
+ this.close(false);
92
+ }
93
+ });
94
+ field.addEventListener("blur", () => this.close(true, false));
95
+ field.focus();
96
+ }
97
+ preview(target) {
98
+ const latex = cleanLatex(this.field?.value ?? "");
99
+ if (this.katex && latex) renderLatex(this.katex, target, latex, this.display);
100
+ else target.replaceChildren();
101
+ }
102
+ close(save, refocus = true) {
103
+ const field = this.field;
104
+ if (!field) return;
105
+ this.field = null;
106
+ window.clearTimeout(this.timer);
107
+ this.dom.classList.remove("is-editing");
108
+ const pos = this.getPos();
109
+ const latex = save ? cleanLatex(field.value.trim()) ?? this.latex : this.latex;
110
+ this.render();
111
+ if (pos === void 0 || !this.view.editable || this.destroyed) return;
112
+ const { state } = this.view;
113
+ const transaction = state.tr;
114
+ if (latex === "") transaction.delete(pos, pos + this.node.nodeSize);
115
+ else if (save) {
116
+ if (latex !== this.latex) transaction.setNodeMarkup(pos, void 0, { latex });
117
+ const after = pos + this.node.nodeSize;
118
+ transaction.setSelection(TextSelection.near(transaction.doc.resolve(after)));
119
+ } else transaction.setSelection(NodeSelection.create(state.doc, pos));
120
+ this.view.dispatch(transaction.scrollIntoView());
121
+ if (refocus) this.view.focus();
122
+ }
123
+ render() {
124
+ const latex = this.latex;
125
+ this.dom.classList.toggle("is-empty", latex === "");
126
+ if (latex === "") {
127
+ this.dom.textContent = this.settings.labels.empty;
128
+ return;
129
+ }
130
+ if (this.katex && renderLatex(this.katex, this.dom, latex, this.display)) return;
131
+ const source = document.createElement("code");
132
+ source.className = "vive-math-source";
133
+ source.textContent = this.display ? latex : `$${latex}$`;
134
+ this.dom.replaceChildren(source);
135
+ }
136
+ };
137
+ // src/index.ts
138
+ const latexAttrs = { latex: {
139
+ default: "",
140
+ validate: (value) => {
141
+ if (cleanLatex(value) === null) throw new RangeError("Invalid formula");
142
+ }
143
+ } };
144
+ const latexOf = (dom) => {
145
+ const latex = cleanLatex(dom.textContent?.trim() ?? "");
146
+ return latex ? { latex } : false;
147
+ };
148
+ const mathSpecs = () => ({
149
+ mathInline: {
150
+ group: "inline",
151
+ inline: true,
152
+ atom: true,
153
+ selectable: true,
154
+ attrs: latexAttrs,
155
+ parseDOM: [{
156
+ tag: "span[data-math=\"inline\"]",
157
+ priority: 60,
158
+ getAttrs: latexOf
159
+ }],
160
+ toDOM: (node) => [
161
+ "span",
162
+ { "data-math": "inline" },
163
+ cleanLatex(node.attrs.latex) ?? ""
164
+ ],
165
+ leafText: (node) => `$${cleanLatex(node.attrs.latex) ?? ""}$`
166
+ },
167
+ mathBlock: {
168
+ group: "block",
169
+ atom: true,
170
+ selectable: true,
171
+ attrs: latexAttrs,
172
+ parseDOM: [{
173
+ tag: "div[data-math=\"block\"]",
174
+ priority: 60,
175
+ getAttrs: latexOf
176
+ }],
177
+ toDOM: (node) => [
178
+ "div",
179
+ { "data-math": "block" },
180
+ cleanLatex(node.attrs.latex) ?? ""
181
+ ]
182
+ }
183
+ });
184
+ function blockInsertion(state) {
185
+ const { $from } = state.selection;
186
+ if ($from.depth === 0 || !$from.parent.isTextblock) return null;
187
+ return $from.parent.content.size === 0 ? $from.before() : $from.after();
188
+ }
189
+ function insertMath(inline, block) {
190
+ return (options = {}) => (state, dispatch, view) => {
191
+ if (view && !view.editable) return false;
192
+ const latex = cleanLatex(options.latex ?? "");
193
+ const { $from } = state.selection;
194
+ if (latex === null || $from.parent.type.spec.code) return false;
195
+ if (!options.display) {
196
+ if (!$from.parent.inlineContent) return false;
197
+ if (dispatch) {
198
+ const transaction = state.tr.replaceSelectionWith(inline.create({ latex }), false);
199
+ const pos = transaction.selection.from - 1;
200
+ dispatch(transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView());
201
+ }
202
+ return true;
203
+ }
204
+ const pos = blockInsertion(state);
205
+ if (pos === null) return false;
206
+ const $pos = state.doc.resolve(pos);
207
+ if (!$pos.parent.canReplaceWith($pos.index(), $pos.index(), block)) return false;
208
+ if (dispatch) {
209
+ const node = block.create({ latex });
210
+ const transaction = $from.parent.content.size === 0 ? state.tr.replaceWith(pos, pos + $from.parent.nodeSize, node) : state.tr.insert(pos, node);
211
+ dispatch(transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView());
212
+ }
213
+ return true;
214
+ };
215
+ }
216
+ const MathExtension = defineExtension({
217
+ name: "math",
218
+ defaultOptions: {
219
+ load: null,
220
+ labels: {
221
+ empty: "Formula",
222
+ edit: "LaTeX formula"
223
+ },
224
+ onError: null
225
+ },
226
+ nodes: () => mathSpecs(),
227
+ commands: ({ schema }) => ({ insertMath: insertMath(schema.nodes.mathInline, schema.nodes.mathBlock) }),
228
+ keymap: ({ schema }) => {
229
+ const block = schema.nodes.mathBlock;
230
+ const inline = schema.nodes.mathInline;
231
+ const enter = (state, dispatch, view) => {
232
+ const { selection } = state;
233
+ if (selection instanceof NodeSelection && [inline, block].includes(selection.node.type)) {
234
+ if (dispatch && view) mathViewOf(view.nodeDOM(selection.from))?.open();
235
+ return true;
236
+ }
237
+ const { $from } = selection;
238
+ if (!selection.empty || $from.parent.type !== schema.nodes.paragraph) return false;
239
+ if ($from.parent.textContent !== "$$" || $from.parentOffset !== 2) return false;
240
+ const pos = $from.before();
241
+ if (!$from.node(-1).canReplaceWith($from.index(-1), $from.indexAfter(-1), block)) return false;
242
+ if (view && !view.editable) return false;
243
+ if (dispatch) {
244
+ const transaction = state.tr.replaceWith(pos, $from.after(), block.create());
245
+ dispatch(transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView());
246
+ }
247
+ return true;
248
+ };
249
+ return { Enter: enter };
250
+ },
251
+ inputRules: ({ schema }) => [new InputRule(/(^|[^$\\\w])\$([^$\s](?:[^$]*[^$\s\\])?)\$$/, (state, match, start, end) => {
252
+ const latex = cleanLatex(match[2]);
253
+ if (!latex || !state.selection.$from.parent.inlineContent) return null;
254
+ const from = start + (match[1]?.length ?? 0);
255
+ return state.tr.replaceWith(from, end, schema.nodes.mathInline.create({ latex }));
256
+ })],
257
+ plugins: ({ options }) => {
258
+ const report = (error) => options.onError?.(error);
259
+ const settings = {
260
+ katex: katexLoader(options.load, report),
261
+ labels: options.labels
262
+ };
263
+ return [new Plugin({ props: { nodeViews: {
264
+ mathInline: (node, view, getPos) => new MathView(node, view, getPos, settings),
265
+ mathBlock: (node, view, getPos) => new MathView(node, view, getPos, settings)
266
+ } } })];
267
+ }
268
+ });
269
+ export { MAX_LATEX_LENGTH, MIN_KATEX_VERSION, MathExtension, isSupportedKatex };
270
+
271
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/view.ts","../src/index.ts"],"sourcesContent":["import type { Node as ProseMirrorNode } from 'prosemirror-model'\nimport { NodeSelection, TextSelection } from 'prosemirror-state'\nimport type { EditorView, NodeView, ViewMutationRecord } from 'prosemirror-view'\nimport { cleanLatex, type KatexLike, renderLatex } from './katex.js'\n\nexport interface MathLabels {\n empty: string\n edit: string\n}\n\nexport interface MathViewSettings {\n katex: () => Promise<KatexLike | null>\n labels: MathLabels\n}\n\nconst PREVIEW_DELAY = 100\nconst views = new WeakMap<Element, MathView>()\n\nexport const mathViewOf = (dom: Node | null): MathView | undefined =>\n dom instanceof Element ? views.get(dom) : undefined\n\nexport class MathView implements NodeView {\n readonly dom: HTMLElement\n private katex: KatexLike | null = null\n private field: HTMLInputElement | HTMLTextAreaElement | null = null\n private timer = 0\n private destroyed = false\n\n constructor(\n private node: ProseMirrorNode,\n private readonly view: EditorView,\n private readonly getPos: () => number | undefined,\n private readonly settings: MathViewSettings,\n ) {\n this.dom = document.createElement(this.display ? 'div' : 'span')\n this.dom.className = 'vive-math'\n this.dom.dataset.math = this.display ? 'block' : 'inline'\n this.dom.contentEditable = 'false'\n this.dom.addEventListener('click', () => this.open())\n views.set(this.dom, this)\n this.render()\n settings.katex().then((katex) => {\n this.katex = katex\n if (katex && !this.destroyed && !this.field) this.render()\n })\n }\n\n private get display(): boolean {\n return this.node.type.name === 'mathBlock'\n }\n\n private get latex(): string {\n return cleanLatex(this.node.attrs.latex) ?? ''\n }\n\n update(node: ProseMirrorNode): boolean {\n if (node.type !== this.node.type) return false\n this.node = node\n if (!this.field) this.render()\n return true\n }\n\n selectNode(): void {\n this.dom.classList.add('ProseMirror-selectednode')\n if (this.latex === '') this.open()\n }\n\n deselectNode(): void {\n this.dom.classList.remove('ProseMirror-selectednode')\n }\n\n stopEvent(event: Event): boolean {\n return this.field !== null && event.target instanceof Node && this.dom.contains(event.target)\n }\n\n ignoreMutation(mutation: ViewMutationRecord): boolean {\n return mutation.type !== 'selection' || this.field !== null\n }\n\n destroy(): void {\n this.destroyed = true\n window.clearTimeout(this.timer)\n }\n\n open(): void {\n if (this.field || !this.view.editable || this.getPos() === undefined) return\n const field = document.createElement(this.display ? 'textarea' : 'input')\n field.className = 'vive-math-field'\n field.value = this.latex\n field.spellcheck = false\n field.setAttribute('aria-label', this.settings.labels.edit)\n field.setAttribute('maxlength', '2000')\n const preview = document.createElement(this.display ? 'div' : 'span')\n preview.className = 'vive-math-preview'\n preview.setAttribute('aria-hidden', 'true')\n this.field = field\n this.dom.classList.add('is-editing')\n this.dom.replaceChildren(field, preview)\n this.preview(preview)\n field.addEventListener('input', () => {\n window.clearTimeout(this.timer)\n this.timer = window.setTimeout(() => this.preview(preview), PREVIEW_DELAY)\n })\n field.addEventListener('keydown', (event: Event) => {\n if (!(event instanceof KeyboardEvent)) return\n const commit = this.display\n ? event.key === 'Enter' && (event.metaKey || event.ctrlKey)\n : event.key === 'Enter'\n if (commit) {\n event.preventDefault()\n this.close(true)\n } else if (event.key === 'Escape') {\n event.preventDefault()\n this.close(false)\n }\n })\n field.addEventListener('blur', () => this.close(true, false))\n field.focus()\n }\n\n private preview(target: HTMLElement): void {\n const latex = cleanLatex(this.field?.value ?? '')\n if (this.katex && latex) renderLatex(this.katex, target, latex, this.display)\n else target.replaceChildren()\n }\n\n private close(save: boolean, refocus = true): void {\n const field = this.field\n if (!field) return\n this.field = null\n window.clearTimeout(this.timer)\n this.dom.classList.remove('is-editing')\n const pos = this.getPos()\n const latex = save ? (cleanLatex(field.value.trim()) ?? this.latex) : this.latex\n this.render()\n if (pos === undefined || !this.view.editable || this.destroyed) return\n const { state } = this.view\n const transaction = state.tr\n if (latex === '') {\n transaction.delete(pos, pos + this.node.nodeSize)\n } else if (save) {\n if (latex !== this.latex) transaction.setNodeMarkup(pos, undefined, { latex })\n const after = pos + this.node.nodeSize\n transaction.setSelection(TextSelection.near(transaction.doc.resolve(after)))\n } else {\n transaction.setSelection(NodeSelection.create(state.doc, pos))\n }\n this.view.dispatch(transaction.scrollIntoView())\n if (refocus) this.view.focus()\n }\n\n private render(): void {\n const latex = this.latex\n this.dom.classList.toggle('is-empty', latex === '')\n if (latex === '') {\n this.dom.textContent = this.settings.labels.empty\n return\n }\n if (this.katex && renderLatex(this.katex, this.dom, latex, this.display)) return\n const source = document.createElement('code')\n source.className = 'vive-math-source'\n source.textContent = this.display ? latex : `$${latex}$`\n this.dom.replaceChildren(source)\n }\n}\n","import { defineExtension, type Extension } from '@viveeditor/core'\nimport { InputRule } from 'prosemirror-inputrules'\nimport type { NodeSpec, NodeType } from 'prosemirror-model'\nimport { type Command, type EditorState, NodeSelection, Plugin } from 'prosemirror-state'\nimport { cleanLatex, type KatexLoader, katexLoader, type MathError } from './katex.js'\nimport { type MathLabels, MathView, mathViewOf } from './view.js'\n\nexport {\n isSupportedKatex,\n type KatexLike,\n type KatexLoader,\n type KatexModule,\n MAX_LATEX_LENGTH,\n type MathError,\n type MathErrorCode,\n MIN_KATEX_VERSION,\n} from './katex.js'\nexport type { MathLabels } from './view.js'\n\nexport interface MathOptions {\n load: KatexLoader | null\n labels: MathLabels\n onError: ((error: MathError) => void) | null\n}\n\nexport interface InsertMathOptions {\n display?: boolean\n latex?: string\n}\n\ndeclare module '@viveeditor/core' {\n interface CommandRegistry {\n insertMath: (options?: InsertMathOptions) => Command\n }\n}\n\nconst latexAttrs = {\n latex: {\n default: '',\n validate: (value: unknown) => {\n if (cleanLatex(value) === null) throw new RangeError('Invalid formula')\n },\n },\n}\n\nconst latexOf = (dom: HTMLElement): { latex: string } | false => {\n const latex = cleanLatex(dom.textContent?.trim() ?? '')\n return latex ? { latex } : false\n}\n\nconst mathSpecs = (): Record<string, NodeSpec> => ({\n mathInline: {\n group: 'inline',\n inline: true,\n atom: true,\n selectable: true,\n attrs: latexAttrs,\n parseDOM: [{ tag: 'span[data-math=\"inline\"]', priority: 60, getAttrs: latexOf }],\n toDOM: (node) => ['span', { 'data-math': 'inline' }, cleanLatex(node.attrs.latex) ?? ''],\n leafText: (node) => `$${cleanLatex(node.attrs.latex) ?? ''}$`,\n },\n mathBlock: {\n group: 'block',\n atom: true,\n selectable: true,\n attrs: latexAttrs,\n parseDOM: [{ tag: 'div[data-math=\"block\"]', priority: 60, getAttrs: latexOf }],\n toDOM: (node) => ['div', { 'data-math': 'block' }, cleanLatex(node.attrs.latex) ?? ''],\n },\n})\n\nfunction blockInsertion(state: EditorState): number | null {\n const { $from } = state.selection\n if ($from.depth === 0 || !$from.parent.isTextblock) return null\n return $from.parent.content.size === 0 ? $from.before() : $from.after()\n}\n\nfunction insertMath(inline: NodeType, block: NodeType) {\n return (options: InsertMathOptions = {}): Command =>\n (state, dispatch, view) => {\n if (view && !view.editable) return false\n const latex = cleanLatex(options.latex ?? '')\n const { $from } = state.selection\n if (latex === null || $from.parent.type.spec.code) return false\n if (!options.display) {\n if (!$from.parent.inlineContent) return false\n if (dispatch) {\n const transaction = state.tr.replaceSelectionWith(inline.create({ latex }), false)\n const pos = transaction.selection.from - 1\n dispatch(\n transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView(),\n )\n }\n return true\n }\n const pos = blockInsertion(state)\n if (pos === null) return false\n const $pos = state.doc.resolve(pos)\n if (!$pos.parent.canReplaceWith($pos.index(), $pos.index(), block)) return false\n if (dispatch) {\n const node = block.create({ latex })\n const empty = $from.parent.content.size === 0\n const transaction = empty\n ? state.tr.replaceWith(pos, pos + $from.parent.nodeSize, node)\n : state.tr.insert(pos, node)\n dispatch(\n transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView(),\n )\n }\n return true\n }\n}\n\nexport const MathExtension: Extension<MathOptions> = defineExtension<MathOptions>({\n name: 'math',\n defaultOptions: {\n load: null,\n labels: { empty: 'Formula', edit: 'LaTeX formula' },\n onError: null,\n },\n nodes: () => mathSpecs(),\n commands: ({ schema }) => ({\n insertMath: insertMath(schema.nodes.mathInline as NodeType, schema.nodes.mathBlock as NodeType),\n }),\n keymap: ({ schema }) => {\n const block = schema.nodes.mathBlock as NodeType\n const inline = schema.nodes.mathInline as NodeType\n const enter: Command = (state, dispatch, view) => {\n const { selection } = state\n if (selection instanceof NodeSelection && [inline, block].includes(selection.node.type)) {\n if (dispatch && view) mathViewOf(view.nodeDOM(selection.from))?.open()\n return true\n }\n const { $from } = selection\n if (!selection.empty || $from.parent.type !== schema.nodes.paragraph) return false\n if ($from.parent.textContent !== '$$' || $from.parentOffset !== 2) return false\n const pos = $from.before()\n if (!$from.node(-1).canReplaceWith($from.index(-1), $from.indexAfter(-1), block)) return false\n if (view && !view.editable) return false\n if (dispatch) {\n const transaction = state.tr.replaceWith(pos, $from.after(), block.create())\n dispatch(\n transaction.setSelection(NodeSelection.create(transaction.doc, pos)).scrollIntoView(),\n )\n }\n return true\n }\n return { Enter: enter }\n },\n inputRules: ({ schema }) => [\n new InputRule(/(^|[^$\\\\\\w])\\$([^$\\s](?:[^$]*[^$\\s\\\\])?)\\$$/, (state, match, start, end) => {\n const latex = cleanLatex(match[2])\n if (!latex || !state.selection.$from.parent.inlineContent) return null\n const from = start + (match[1]?.length ?? 0)\n return state.tr.replaceWith(\n from,\n end,\n (schema.nodes.mathInline as NodeType).create({ latex }),\n )\n }),\n ],\n plugins: ({ options }) => {\n const report = (error: MathError): void => options.onError?.(error)\n const settings = { katex: katexLoader(options.load, report), labels: options.labels }\n return [\n new Plugin({\n props: {\n nodeViews: {\n mathInline: (node, view, getPos) => new MathView(node, view, getPos, settings),\n mathBlock: (node, view, getPos) => new MathView(node, view, getPos, settings),\n },\n },\n }),\n ]\n },\n})\n"],"mappings":";;;;;AAeA,MAAM,gBAAgB;AACtB,MAAM,wBAAQ,IAAI,QAA2B;AAE7C,MAAa,cAAc,QACzB,eAAe,UAAU,MAAM,IAAI,GAAG,IAAI,KAAA;AAE5C,IAAa,WAAb,MAA0C;CAQ9B;CACS;CACA;CACA;CAVnB;CACA,QAAkC;CAClC,QAA+D;CAC/D,QAAgB;CAChB,YAAoB;CAEpB,YACE,MACA,MACA,QACA,UACA;EAJQ,KAAA,OAAA;EACS,KAAA,OAAA;EACA,KAAA,SAAA;EACA,KAAA,WAAA;EAEjB,KAAK,MAAM,SAAS,cAAc,KAAK,UAAU,QAAQ,MAAM;EAC/D,KAAK,IAAI,YAAY;EACrB,KAAK,IAAI,QAAQ,OAAO,KAAK,UAAU,UAAU;EACjD,KAAK,IAAI,kBAAkB;EAC3B,KAAK,IAAI,iBAAiB,eAAe,KAAK,KAAK,CAAC;EACpD,MAAM,IAAI,KAAK,KAAK,IAAI;EACxB,KAAK,OAAO;EACZ,SAAS,MAAM,CAAC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,WAAW,EAAE,GAAG,KAAK,GAAG,OAAO;GACzF,IAAI,QAAQ,CAAC,KAAK,UAAU,OAAO;GACnC,IAAI,UAAU;IACZ,MAAM,cAAc,MAAM,GAAG,YAAY,KAAK,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC;IAC3E,SACE,YAAY,aAAa,cAAc,OAAO,YAAY,KAAK,GAAG,CAAC,CAAC,CAAC,eAAe,CACtF;GACF;GACA,OAAO;EACT;EACA,OAAO,EAAE,OAAO,MAAM;CACxB;CACA,aAAa,EAAE,aAAa,CAC1B,IAAI,UAAU,gDAAgD,OAAO,OAAO,OAAO,QAAQ;EACzF,MAAM,QAAQ,WAAW,MAAM,EAAE;EACjC,IAAI,CAAC,SAAS,CAAC,MAAM,UAAU,MAAM,OAAO,eAAe,OAAO;EAClE,MAAM,OAAO,SAAS,MAAM,EAAE,EAAE,UAAU;EAC1C,OAAO,MAAM,GAAG,YACd,MACA,KACC,OAAO,MAAM,WAAwB,OAAO,EAAE,MAAM,CAAC,CACxD;CACF,CAAC,CACH;CACA,UAAU,EAAE,cAAc;EACxB,MAAM,UAAU,UAA2B,QAAQ,UAAU,KAAK;EAClE,MAAM,WAAW;GAAE,OAAO,YAAY,QAAQ,MAAM,MAAM;GAAG,QAAQ,QAAQ;EAAO;EACpF,OAAO,CACL,IAAI,OAAO,EACT,OAAO,EACL,WAAW;GACT,aAAa,MAAM,MAAM,WAAW,IAAI,SAAS,MAAM,MAAM,QAAQ,QAAQ;GAC7E,YAAY,MAAM,MAAM,WAAW,IAAI,SAAS,MAAM,MAAM,QAAQ,QAAQ;EAC9E,EACF,EACF,CAAC,CACH;CACF;AACF,CAAC"}
@@ -0,0 +1,18 @@
1
+ interface KatexLike {
2
+ readonly version: string;
3
+ render(latex: string, element: HTMLElement, options: Readonly<Record<string, unknown>>): void;
4
+ }
5
+ type KatexModule = KatexLike | {
6
+ default: KatexLike;
7
+ };
8
+ type KatexLoader = () => Promise<KatexModule>;
9
+ type MathErrorCode = "KATEX_OUTDATED" | "KATEX_LOAD";
10
+ interface MathError {
11
+ code: MathErrorCode;
12
+ version?: string;
13
+ }
14
+ declare const MIN_KATEX_VERSION = "0.18.2";
15
+ declare const MAX_LATEX_LENGTH = 2e3;
16
+ declare function isSupportedKatex(version: unknown): boolean;
17
+ export { MIN_KATEX_VERSION as a, isSupportedKatex as c, MAX_LATEX_LENGTH as i, KatexLoader as n, MathError as o, KatexModule as r, MathErrorCode as s, KatexLike as t };
18
+ //# sourceMappingURL=katex-517YH_fa.d.ts.map
@@ -0,0 +1,73 @@
1
+ // src/katex.ts
2
+ const MIN_KATEX_VERSION = "0.18.2";
3
+ const MAX_LATEX_LENGTH = 2e3;
4
+ const MAX_DEPTH = 64;
5
+ const optionsFor = (displayMode) => Object.freeze({
6
+ displayMode,
7
+ throwOnError: false,
8
+ trust: false,
9
+ strict: "ignore",
10
+ maxSize: 50,
11
+ maxExpand: 1e3,
12
+ output: "htmlAndMathml"
13
+ });
14
+ const INLINE = optionsFor(false);
15
+ const DISPLAY = optionsFor(true);
16
+ function isSupportedKatex(version) {
17
+ if (typeof version !== "string") return false;
18
+ const actual = version.split(".").map(Number);
19
+ const minimum = MIN_KATEX_VERSION.split(".").map(Number);
20
+ for (let index = 0; index < minimum.length; index++) {
21
+ const part = actual[index] ?? 0;
22
+ const floor = minimum[index] ?? 0;
23
+ if (!Number.isInteger(part)) return false;
24
+ if (part !== floor) return part > floor;
25
+ }
26
+ return true;
27
+ }
28
+ function cleanLatex(value) {
29
+ if (typeof value !== "string") return null;
30
+ if (Array.from(value).length > 2e3) return null;
31
+ let depth = 0;
32
+ for (const character of value) {
33
+ if (character === "{") depth++;
34
+ else if (character === "}") depth = Math.max(0, depth - 1);
35
+ if (depth > MAX_DEPTH) return null;
36
+ }
37
+ return value;
38
+ }
39
+ function katexLoader(load, report) {
40
+ let pending = null;
41
+ return () => {
42
+ if (!load) return Promise.resolve(null);
43
+ pending ??= load().then((module) => {
44
+ const katex = "default" in module ? module.default : module;
45
+ if (!isSupportedKatex(katex?.version) || typeof katex.render !== "function") {
46
+ report({
47
+ code: "KATEX_OUTDATED",
48
+ version: String(katex?.version ?? "")
49
+ });
50
+ return null;
51
+ }
52
+ return katex;
53
+ }, () => {
54
+ report({ code: "KATEX_LOAD" });
55
+ pending = null;
56
+ return null;
57
+ });
58
+ return pending;
59
+ };
60
+ }
61
+ function renderLatex(katex, target, latex, display) {
62
+ const output = document.createElement("span");
63
+ try {
64
+ katex.render(latex, output, display ? DISPLAY : INLINE);
65
+ } catch {
66
+ return false;
67
+ }
68
+ target.replaceChildren(output);
69
+ return true;
70
+ }
71
+ export { katexLoader as a, isSupportedKatex as i, MIN_KATEX_VERSION as n, renderLatex as o, cleanLatex as r, MAX_LATEX_LENGTH as t };
72
+
73
+ //# sourceMappingURL=katex-ckeBhi54.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"katex-ckeBhi54.js","names":[],"sources":["../src/katex.ts"],"sourcesContent":["export interface KatexLike {\n readonly version: string\n render(latex: string, element: HTMLElement, options: Readonly<Record<string, unknown>>): void\n}\n\nexport type KatexModule = KatexLike | { default: KatexLike }\n\nexport type KatexLoader = () => Promise<KatexModule>\n\nexport type MathErrorCode = 'KATEX_OUTDATED' | 'KATEX_LOAD'\n\nexport interface MathError {\n code: MathErrorCode\n version?: string\n}\n\nexport const MIN_KATEX_VERSION = '0.18.2'\nexport const MAX_LATEX_LENGTH = 2000\nconst MAX_DEPTH = 64\n\nconst optionsFor = (displayMode: boolean): Readonly<Record<string, unknown>> =>\n Object.freeze({\n displayMode,\n throwOnError: false,\n trust: false,\n strict: 'ignore',\n maxSize: 50,\n maxExpand: 1000,\n output: 'htmlAndMathml',\n })\n\nconst INLINE = optionsFor(false)\nconst DISPLAY = optionsFor(true)\n\nexport function isSupportedKatex(version: unknown): boolean {\n if (typeof version !== 'string') return false\n const actual = version.split('.').map(Number)\n const minimum = MIN_KATEX_VERSION.split('.').map(Number)\n for (let index = 0; index < minimum.length; index++) {\n const part = actual[index] ?? 0\n const floor = minimum[index] ?? 0\n if (!Number.isInteger(part)) return false\n if (part !== floor) return part > floor\n }\n return true\n}\n\nexport function cleanLatex(value: unknown): string | null {\n if (typeof value !== 'string') return null\n if (Array.from(value).length > MAX_LATEX_LENGTH) return null\n let depth = 0\n for (const character of value) {\n if (character === '{') depth++\n else if (character === '}') depth = Math.max(0, depth - 1)\n if (depth > MAX_DEPTH) return null\n }\n return value\n}\n\nexport function katexLoader(\n load: KatexLoader | null,\n report: (error: MathError) => void,\n): () => Promise<KatexLike | null> {\n let pending: Promise<KatexLike | null> | null = null\n return () => {\n if (!load) return Promise.resolve(null)\n pending ??= load().then(\n (module) => {\n const katex = 'default' in module ? module.default : module\n if (!isSupportedKatex(katex?.version) || typeof katex.render !== 'function') {\n report({ code: 'KATEX_OUTDATED', version: String(katex?.version ?? '') })\n return null\n }\n return katex\n },\n () => {\n report({ code: 'KATEX_LOAD' })\n pending = null\n return null\n },\n )\n return pending\n }\n}\n\nexport function renderLatex(\n katex: KatexLike,\n target: HTMLElement,\n latex: string,\n display: boolean,\n): boolean {\n const output = document.createElement('span')\n try {\n katex.render(latex, output, display ? DISPLAY : INLINE)\n } catch {\n return false\n }\n target.replaceChildren(output)\n return true\n}\n"],"mappings":";AAgBA,MAAa,oBAAoB;AACjC,MAAa,mBAAmB;AAChC,MAAM,YAAY;AAElB,MAAM,cAAc,gBAClB,OAAO,OAAO;CACZ;CACA,cAAc;CACd,OAAO;CACP,QAAQ;CACR,SAAS;CACT,WAAW;CACX,QAAQ;AACV,CAAC;AAEH,MAAM,SAAS,WAAW,KAAK;AAC/B,MAAM,UAAU,WAAW,IAAI;AAE/B,SAAgB,iBAAiB,SAA2B;CAC1D,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,MAAM,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC5C,MAAM,UAAU,kBAAkB,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CACvD,KAAK,I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atexLoader, o as MathError } from "./katex-517YH_fa.js";
2
+ export interface RenderMathOptions {
3
+ load: KatexLoader;
4
+ onError?: (error: MathError) => void;
5
+ }
6
+ export declare function renderMath(root: ParentNode, options: RenderMathOptions): Promise<number>;
7
+ //# sourceMappingURL=render.d.ts.map
package/dist/render.js ADDED
@@ -0,0 +1,31 @@
1
+ import { a as katexLoader, o as renderLatex, r as cleanLatex } from "./katex-ckeBhi54.js";
2
+ // src/render.ts
3
+ const MAX_FORMULAS = 1e3;
4
+ const BATCH = 50;
5
+ const nextFrame = () => new Promise((resolve) => {
6
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(() => resolve());
7
+ else setTimeout(resolve, 0);
8
+ });
9
+ async function renderMath(root, options) {
10
+ const elements = Array.from(root.querySelectorAll("span[data-math=\"inline\"]:not([data-rendered]), div[data-math=\"block\"]:not([data-rendered])")).slice(0, MAX_FORMULAS);
11
+ if (elements.length === 0) return 0;
12
+ const katex = await katexLoader(options.load, (error) => options.onError?.(error))();
13
+ if (!katex) return 0;
14
+ let rendered = 0;
15
+ for (let index = 0; index < elements.length; index++) {
16
+ if (index > 0 && index % BATCH === 0) await nextFrame();
17
+ const element = elements[index];
18
+ if (!element) continue;
19
+ const latex = cleanLatex(element.textContent?.trim() ?? "");
20
+ const display = element.dataset.math === "block";
21
+ if (!latex || !renderLatex(katex, element, latex, display)) continue;
22
+ element.dataset.rendered = "";
23
+ element.setAttribute("aria-label", latex);
24
+ element.classList.add("vive-math");
25
+ rendered++;
26
+ }
27
+ return rendered;
28
+ }
29
+ export { renderMath };
30
+
31
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","names":[],"sources":["../src/render.ts"],"sourcesContent":["import { cleanLatex, type KatexLoader, katexLoader, type MathError, renderLatex } from './katex.js'\n\nexport interface RenderMathOptions {\n load: KatexLoader\n onError?: (error: MathError) => void\n}\n\nconst MAX_FORMULAS = 1000\nconst BATCH = 50\n\nconst nextFrame = (): Promise<void> =>\n new Promise((resolve) => {\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve())\n else setTimeout(resolve, 0)\n })\n\nexport async function renderMath(root: ParentNode, options: RenderMathOptions): Promise<number> {\n const elements = Array.from(\n root.querySelectorAll<HTMLElement>(\n 'span[data-math=\"inline\"]:not([data-rendered]), div[data-math=\"block\"]:not([data-rendered])',\n ),\n ).slice(0, MAX_FORMULAS)\n if (elements.length === 0) return 0\n const katex = await katexLoader(options.load, (error) => options.onError?.(error))()\n if (!katex) return 0\n let rendered = 0\n for (let index = 0; index < elements.length; index++) {\n if (index > 0 && index % BATCH === 0) await nextFrame()\n const element = elements[index]\n if (!element) continue\n const latex = cleanLatex(element.textContent?.trim() ?? '')\n const display = element.dataset.math === 'block'\n if (!latex || !renderLatex(katex, element, latex, display)) continue\n element.dataset.rendered = ''\n element.setAttribute('aria-label', latex)\n element.classList.add('vive-math')\n rendered++\n }\n return rendered\n}\n"],"mappings":";;AAOA,MAAM,eAAe;AACrB,MAAM,QAAQ;AAEd,MAAM,kBACJ,IAAI,SAAS,YAAY;CACvB,IAAI,OAAO,0BAA0B,YAAY,4BAA4B,QAAQ,CAAC;MACjF,WAAW,SAAS,CAAC;AAC5B,CAAC;AAEH,eAAsB,WAAW,MAAkB,SAA6C;CAC9F,MAAM,WAAW,MAAM,KACrB,KAAK,iBACH,gGACF,CACF,CAAC,CAAC,MAAM,GAAG,YAAY;CACvB,IAAI,SAAS,WAAW,GAAG,OAAO;CAClC,MAAM,QAAQ,MAAM,YAAY,QAAQ,OAAO,UAAU,QAAQ,UAAU,KAAK,CAAC,CAAC,CAAC;CACnF,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,WAAW;CACf,KAAK,IAAI,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS;EACpD,IAAI,QAAQ,KAAK,QAAQ,UAAU,GAAG,MAAM,UAAU;EACtD,MAAM,UAAU,SAAS;EACzB,IAAI,CAAC,SAAS;EACd,MAAM,QAAQ,WAAW,QAAQ,aAAa,KAAK,KAAK,EAAE;EAC1D,MAAM,UAAU,QAAQ,QAAQ,SAAS;EACzC,IAAI,CAAC,SAAS,CAAC,YAAY,OAAO,SAAS,OAAO,OAAO,GAAG;EAC5D,QAAQ,QAAQ,WAAW;EAC3B,QAAQ,aAAa,cAAc,KAAK;EACxC,QAAQ,UAAU,IAAI,WAAW;EACjC;CACF;CACA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,98 @@
1
1
  {
2
2
  "name": "@viveeditor/ext-math",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-rc.1",
4
+ "description": "LaTeX formulas for viveEditor, rendered with a KaTeX copy the site loads on demand.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "viveeditor",
8
+ "rich-text-editor",
9
+ "wysiwyg",
10
+ "editor",
11
+ "prosemirror",
12
+ "math",
13
+ "latex",
14
+ "katex",
15
+ "formula"
16
+ ],
17
+ "homepage": "https://editor.vivepdf.com/en/docs/formulas/",
18
+ "bugs": {
19
+ "url": "https://github.com/mtvrkan/viveeditor/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/mtvrkan/viveeditor.git",
24
+ "directory": "packages/ext-math"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": [
28
+ "*.css"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./render": {
37
+ "types": "./dist/render.d.ts",
38
+ "import": "./dist/render.js",
39
+ "default": "./dist/render.js"
40
+ },
41
+ "./style.css": "./style.css"
42
+ },
43
+ "files": [
44
+ "dist",
45
+ "style.css"
46
+ ],
47
+ "peerDependencies": {
48
+ "@viveeditor/core": "^1.0.0-rc.1"
49
+ },
50
+ "dependencies": {
51
+ "prosemirror-inputrules": "^1.5.1",
52
+ "prosemirror-model": "^1.25.12",
53
+ "prosemirror-state": "^1.4.4",
54
+ "prosemirror-view": "^1.42.7"
55
+ },
56
+ "devDependencies": {
57
+ "@size-limit/preset-small-lib": "^14.3.0",
58
+ "jsdom": "^30.1.3",
59
+ "katex": "0.19.1",
60
+ "size-limit": "^14.3.0",
61
+ "tsdown": "0.23.1",
62
+ "vitest": "^5.0.5",
63
+ "@viveeditor/ext-basic": "1.0.0-rc.1",
64
+ "@viveeditor/core": "1.0.0-rc.1"
65
+ },
66
+ "size-limit": [
67
+ {
68
+ "name": "@viveeditor/ext-math",
69
+ "path": "dist/index.js",
70
+ "ignore": [
71
+ "@viveeditor/core",
72
+ "prosemirror-inputrules",
73
+ "prosemirror-model",
74
+ "prosemirror-state",
75
+ "prosemirror-view"
76
+ ],
77
+ "limit": "3 KB"
78
+ },
79
+ {
80
+ "name": "@viveeditor/ext-math/render",
81
+ "path": "dist/render.js",
82
+ "limit": "1 KB"
83
+ }
84
+ ],
85
+ "engines": {
86
+ "node": ">=22.12"
87
+ },
88
+ "publishConfig": {
89
+ "access": "public",
90
+ "provenance": true
91
+ },
92
+ "scripts": {
93
+ "build": "tsdown",
94
+ "typecheck": "tsc -p tsconfig.json",
95
+ "test": "vitest run",
96
+ "size": "size-limit"
97
+ }
6
98
  }
package/style.css ADDED
@@ -0,0 +1,74 @@
1
+ .vive-math {
2
+ overflow: hidden;
3
+ contain: paint;
4
+ }
5
+
6
+ span.vive-math {
7
+ display: inline-block;
8
+ max-width: 100%;
9
+ vertical-align: middle;
10
+ }
11
+
12
+ div.vive-math {
13
+ display: block;
14
+ max-width: 100%;
15
+ margin: 0 0 0.9em;
16
+ padding: 0.5em 0;
17
+ overflow-x: auto;
18
+ text-align: center;
19
+ }
20
+
21
+ .vive-content .vive-math.is-empty {
22
+ padding: 0 0.4em;
23
+ border: 1px dashed var(--ve-border, hsl(220 13% 85%));
24
+ border-radius: 6px;
25
+ color: var(--ve-muted-fg, hsl(220 9% 40%));
26
+ }
27
+
28
+ .vive-content .vive-math-source {
29
+ font-family: var(--ve-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
30
+ }
31
+
32
+ .vive-content .vive-math.ProseMirror-selectednode {
33
+ outline: 2px solid var(--ve-primary, hsl(221 83% 53%));
34
+ outline-offset: 2px;
35
+ border-radius: 4px;
36
+ }
37
+
38
+ .vive-content .vive-math.is-editing {
39
+ display: inline-flex;
40
+ flex-direction: column;
41
+ gap: 4px;
42
+ overflow: visible;
43
+ contain: none;
44
+ }
45
+
46
+ .vive-content div.vive-math.is-editing {
47
+ display: flex;
48
+ text-align: start;
49
+ }
50
+
51
+ .vive-content .vive-math-field {
52
+ min-width: 12ch;
53
+ padding: 4px 6px;
54
+ border: 1px solid var(--ve-border, hsl(220 13% 85%));
55
+ border-radius: 6px;
56
+ background: var(--ve-bg, hsl(0 0% 100%));
57
+ color: inherit;
58
+ font: 14px / 1.4 var(--ve-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
59
+ }
60
+
61
+ .vive-content textarea.vive-math-field {
62
+ min-height: 4.5em;
63
+ resize: vertical;
64
+ }
65
+
66
+ .vive-content .vive-math-field:focus-visible {
67
+ outline: 2px solid var(--ve-primary, hsl(221 83% 53%));
68
+ outline-offset: 1px;
69
+ }
70
+
71
+ .vive-content .vive-math-preview {
72
+ overflow: hidden;
73
+ contain: paint;
74
+ }