Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(client): add MathLive visual editor option and related configurations
Meinzzzz788a849d9a7f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f8493e80a9..805d50195d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3288,6 +3288,8 @@},"editorfeatures": {"title": "Features",+ "mathlive_enabled": "MathLive visual editor",+ "mathlive_description": "Math equations can be edited using a visual editor.","emoji_completion_enabled": "Emoji auto-completion","emoji_completion_description": "Emojis can be easily inserted into text by typing `:`, followed by the name of an emoji.","note_completion_enabled": "Note auto-completion",diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsxindex d2f7de1ecb..011a2911e8 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx@@ -148,6 +148,7 @@ function ToolbarIcon({ wide }: { wide?: boolean }) {}function EditorFeatures() {+ const [mathFieldEnabled, setMathFieldEnabled] = useTriliumOptionBool("mathFieldEnabled");const [emojiCompletionEnabled, setEmojiCompletionEnabled] = useTriliumOptionBool("textNoteEmojiCompletionEnabled");const [noteCompletionEnabled, setNoteCompletionEnabled] = useTriliumOptionBool("textNoteCompletionEnabled");const [slashCommandsEnabled, setSlashCommandsEnabled] = useTriliumOptionBool("textNoteSlashCommandsEnabled");@@ -157,6 +158,14 @@ function EditorFeatures() {return (<Card heading={t("editorfeatures.title")}>+ <OptionCardSection+ name="mathlive-enabled"+ label={t("editorfeatures.mathlive_enabled")}+ description={t("editorfeatures.mathlive_description")}+ >+ <FormToggle currentValue={mathFieldEnabled} onChange={setMathFieldEnabled} />+ </OptionCardSection>+<OptionCardSectionname="emoji-completion-enabled"label={t("editorfeatures.emoji_completion_enabled")}diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 872da4593a..da4ba37e74 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -117,7 +117,7 @@ interface DynamicConfig {copyToClipboard(src: string): void;download(src: string): void;};- math: { lazyLoad(): Promise<void> };+ math: { enableMathField: boolean; lazyLoad(): Promise<void> };mermaid: { lazyLoad(): Promise<unknown> };syntaxHighlighting: { loadHighlightJs(): Promise<{ default: unknown }> };mention?: {@@ -620,6 +620,15 @@ function toolbarItems(config: EditorConfig): unknown[] {}describe("CK config - disabled plugins", () => {+ it("passes the MathLive option to the math editor", async () => {+ const defaultConfig = await buildDynamicConfig();+ expect(defaultConfig.math.enableMathField).toBe(true);++ optionsState.map["mathFieldEnabled"] = "false";+ const disabledConfig = await buildDynamicConfig();+ expect(disabledConfig.math.enableMathField).toBe(false);+ });+it("removes the emoji and slash-command plugins based on their option toggles", async () => {const disabled = await buildConfig(baseOpts());expect(disabled.removePlugins).toContain("TriliumEmojiMention");diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex ddf6652d8d..803750c1ea 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -61,7 +61,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfienablePreview: true, // Enable preview view// Map MathLive-only commands (e.g. \differentialD) onto KaTeX equivalents so// formulas produced by the visual editor render instead of erroring out (#9523).- katexRenderOptions: { macros: KATEX_MACROS }+ katexRenderOptions: { macros: KATEX_MACROS },+ enableMathField: options.get("mathFieldEnabled") !== "false"},mermaid: {lazyLoad: async () => (await import("mermaid")).default, // FIXMEdiff --git a/packages/ckeditor5/src/plugins/math/main_form_view.ts b/packages/ckeditor5/src/plugins/math/main_form_view.tsindex 99a8d961e6..552f63f18e 100644--- a/packages/ckeditor5/src/plugins/math/main_form_view.ts+++ b/packages/ckeditor5/src/plugins/math/main_form_view.ts@@ -22,13 +22,14 @@ export default class MainFormView extends View {locale: Locale,mathViewOptions: MathViewOptions,previewEnabled = false,- popupClassName: Array<string> = []+ popupClassName: Array<string> = [],+ enableMathField = true) {super( locale );const t = locale.t;// Create views- this.mathInputView = new MathInputView( locale );+ this.mathInputView = new MathInputView( locale, enableMathField );this.saveButtonView = this._createButton( t( 'Save' ), IconCheck, 'ck-button-save', 'submit' );this.cancelButtonView = this._createButton( t( 'Cancel' ), IconCancel, 'ck-button-cancel' );this.cancelButtonView.delegate( 'execute' ).to( this, 'cancel' );diff --git a/packages/ckeditor5/src/plugins/math/math.ts b/packages/ckeditor5/src/plugins/math/math.tsindex 3c80dd41c4..d69d80fc30 100644--- a/packages/ckeditor5/src/plugins/math/math.ts+++ b/packages/ckeditor5/src/plugins/math/math.ts@@ -48,6 +48,7 @@ declare module 'ckeditor5' {className?: string | undefined;forceOutputType?: boolean | undefined;enablePreview?: boolean | undefined;+ enableMathField?: boolean | undefined;previewClassName?: Array<string> | undefined;popupClassName?: Array<string> | undefined;katexRenderOptions?: Partial<KatexOptions> | undefined;diff --git a/packages/ckeditor5/src/plugins/math/math_editing.ts b/packages/ckeditor5/src/plugins/math/math_editing.tsindex ad9247e0e9..939987cf86 100644--- a/packages/ckeditor5/src/plugins/math/math_editing.ts+++ b/packages/ckeditor5/src/plugins/math/math_editing.ts@@ -19,6 +19,7 @@ export default class MathEditing extends Plugin {className: 'math-tex',forceOutputType: false,enablePreview: true,+ enableMathField: true,previewClassName: [],popupClassName: [],katexRenderOptions: {}diff --git a/packages/ckeditor5/src/plugins/math/math_input_view.spec.ts b/packages/ckeditor5/src/plugins/math/math_input_view.spec.tsindex 205a972955..8019b17269 100644--- a/packages/ckeditor5/src/plugins/math/math_input_view.spec.ts+++ b/packages/ckeditor5/src/plugins/math/math_input_view.spec.ts@@ -9,6 +9,7 @@ import MathInputView, { LatexTextAreaView, MathFieldFocusableView } from './mathinterface MathField extends HTMLElement {value: string;readOnly: boolean;+ inlineShortcuts?: Record<string, string | { value: string; after?: string }>;setValue?: ( value: string, options?: { silenceNotifications?: boolean } ) => void;}@@ -51,6 +52,27 @@ describe( 'MathInputView', () => {expect( mathfield.getAttribute( 'tabindex' ) ).toBe( '0' );} );+ it( 'renders only the LaTeX textarea when MathLive is disabled', () => {+ view = new MathInputView( new Locale(), false );+ view.render();+ document.body.appendChild( view.element as HTMLElement );++ expect( view.element?.querySelector( '.ck-mathlive-container' ) ).toBeNull();+ expect( view.mathfield ).toBeNull();+ expect( textarea().tagName ).toBe( 'TEXTAREA' );+ } );++ it( 'accepts custom MathLive inline shortcuts from a document event', async () => {+ const addShortcut = ( event: Event ) => {+ ( event as CustomEvent<Record<string, string>> ).detail.sq = '\\sqrt{#?}';+ };+ document.addEventListener( 'mathlive:custom-shortcuts', addShortcut, { once: true } );++ const mathfield = await renderAndWait();++ expect( mathfield.inlineShortcuts?.sq ).toBe( '\\sqrt{#?}' );+ } );+describe( 'syncing', () => {it( 'pushes a model value into both the textarea and the math field', async () => {const mathfield = await renderAndWait();@@ -301,6 +323,16 @@ describe( 'MathInputView', () => {expect( focus ).toHaveBeenCalled();} );++ it( 'focuses the textarea when MathLive is disabled', () => {+ view = new MathInputView( new Locale(), false );+ view.render();+ const focus = vi.spyOn( view.latexTextAreaView, 'focus' );++ view.focus();++ expect( focus ).toHaveBeenCalled();+ } );} );describe( 'the sub-views in isolation', () => {diff --git a/packages/ckeditor5/src/plugins/math/math_input_view.ts b/packages/ckeditor5/src/plugins/math/math_input_view.tsindex f99554bc58..7c8518faff 100644--- a/packages/ckeditor5/src/plugins/math/math_input_view.ts+++ b/packages/ckeditor5/src/plugins/math/math_input_view.ts@@ -1,6 +1,7 @@// Math input widget: wraps a MathLive <math-field> and a LaTeX textarea// and keeps them in sync for the CKEditor 5 math dialog.-import { View, type Locale, type FocusableView } from 'ckeditor5';+import { View, type Locale, type FocusableView, type TemplateDefinition } from 'ckeditor5';+import type { InlineShortcutDefinitions } from 'mathlive';import 'mathlive/fonts.css'; // Auto-bundles offline fontsimport 'mathlive/static.css'; // Static styles for mathlive@@ -11,7 +12,7 @@ interface MathFieldElement extends HTMLElement {value: string;readOnly: boolean;mathVirtualKeyboardPolicy: string;- inlineShortcuts?: Record<string, string>;+ inlineShortcuts?: InlineShortcutDefinitions;setValue?: ( value: string, options?: { silenceNotifications?: boolean } ) => void;}@@ -55,25 +56,32 @@ export default class MathInputView extends View {private _destroyed = false;private _vkGeometryHandler?: () => void;private _updating = false;+ private readonly _enableMathField: boolean;private static _configured = false;/** Replaces the editor when MathLive fails to load; resolved up front, while the locale is at hand. */private readonly _unavailableLabel: string;- constructor( locale: Locale ) {+ constructor( locale: Locale, enableMathField = true ) {super( locale );+ this._enableMathField = enableMathField;this._unavailableLabel = locale.t( 'Math editor unavailable' );this.latexTextAreaView = new LatexTextAreaView( locale );this.mathFieldFocusableView = new MathFieldFocusableView( locale, this );this.set( 'value', null );this.set( 'isReadOnly', false );+ const children: Array<TemplateDefinition | View> = [];+ // Only include the MathLive container in the DOM when the feature is enabled+ if ( this._enableMathField ) {+ children.push( { tag: 'div', attributes: { class: [ 'ck-mathlive-container' ] } } );+ }+ children.push(+ { tag: 'label', attributes: { class: [ 'ck-latex-label' ] }, children: [ locale.t( 'LaTeX' ) ] },+ { tag: 'div', attributes: { class: [ 'ck-latex-wrapper' ] }, children: [ this.latexTextAreaView ] }+ );this.setTemplate( {tag: 'div', attributes: { class: [ 'ck', 'ck-math-input' ] },- children: [- { tag: 'div', attributes: { class: [ 'ck-mathlive-container' ] } },- { tag: 'label', attributes: { class: [ 'ck-latex-label' ] }, children: [ locale.t( 'LaTeX' ) ] },- { tag: 'div', attributes: { class: [ 'ck-latex-wrapper' ] }, children: [ this.latexTextAreaView ] }- ]+ children} );}@@ -116,7 +124,7 @@ export default class MathInputView extends View {if ( this.mathfield.value.trim() !== newVal.trim() ) {this._setMathfieldValue( newVal );}- } else if ( newVal !== '' ) {+ } else if ( this._enableMathField && newVal !== '' ) {this._initMathField( false );}this._updating = false;@@ -147,7 +155,9 @@ export default class MathInputView extends View {if ( textarea.value !== initial ) {textarea.value = initial;}- this._loadMathLive();+ if ( this._enableMathField ) {+ this._loadMathLive();+ }}// Loads the MathLive library dynamically@@ -200,7 +210,10 @@ export default class MathInputView extends View {// Set shortcuts after mounting (accessing inlineShortcuts requires mounted element)try {if ( mf.inlineShortcuts ) {- mf.inlineShortcuts = { ...mf.inlineShortcuts, dx: 'dx', dy: 'dy', dt: 'dt' };+ // Allows external listeners to inject custom MathLive shortcuts by mutating event.detail.+ const customShortcuts: InlineShortcutDefinitions = {};+ document.dispatchEvent( new CustomEvent( 'mathlive:custom-shortcuts', { detail: customShortcuts } ) );+ mf.inlineShortcuts = { ...mf.inlineShortcuts, ...customShortcuts };}} catch {// Inline shortcut configuration is optional; ignore failures to avoid breaking the math field.@@ -255,7 +268,11 @@ export default class MathInputView extends View {}public focus(): void {- this.mathfield?.focus();+ if ( this.mathfield ) {+ this.mathfield.focus();+ } else {+ this.latexTextAreaView.focus();+ }}public override destroy(): void {diff --git a/packages/ckeditor5/src/plugins/math/math_ui.ts b/packages/ckeditor5/src/plugins/math/math_ui.tsindex 19d00feae1..303a3f1d28 100644--- a/packages/ckeditor5/src/plugins/math/math_ui.ts+++ b/packages/ckeditor5/src/plugins/math/math_ui.ts@@ -87,7 +87,8 @@ export default class MathUI extends Plugin {katexRenderOptions: mathConfig.katexRenderOptions!},mathConfig.enablePreview,- mathConfig.popupClassName!+ mathConfig.popupClassName!,+ mathConfig.enableMathField);formView.mathInputView.bind( 'value' ).to( mathCommand, 'value' );diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 22aa734f21..163bbaf64a 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -263,6 +263,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActitextNoteCompletionEnabled: boolean;/** Whether keyboard auto-completion for editing commands is triggered when typing `/`. */textNoteSlashCommandsEnabled: boolean;+ /** Whether the MathLive visual editor is shown when editing math. If false, only the LaTeX textarea is used. */+ mathFieldEnabled: boolean;/** Whether the editor surfaces content-area hints (bottom-corner popups that document how to interact with the element under the caret or pointer, e.g. task-state cycle, collapsible-summary shortcut, drag-handle label). */textNoteContentHintsEnabled: boolean;/** Whether a URL typed or pasted into a text note is automatically turned into a link preview. The "Link preview" dialog is unaffected and always inserts one on request. */diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 10b7a1f9d5..e275381159 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -133,6 +133,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["textNoteEmojiCompletionEnabled","textNoteCompletionEnabled","textNoteSlashCommandsEnabled",+ "mathFieldEnabled","textNoteContentHintsEnabled","textNoteAutoLinkPreviewsEnabled","textNoteHtmlSupportEnabled",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 0c2b563945..d9a5d9aba7 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -321,6 +321,7 @@ const defaultOptions: DefaultOption[] = [{ name: "textNoteEmojiCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteSlashCommandsEnabled", value: "true", isSynced: true },+ { name: "mathFieldEnabled", value: "true", isSynced: true },{ name: "textNoteContentHintsEnabled", value: "true", isSynced: true },{ name: "textNoteAutoLinkPreviewsEnabled", value: "true", isSynced: true },// Off: the tags this carries are the ones the editor has no feature for, and GHS's handling of