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(editor): let the user add replacements of their own
Elian Doran32d6da25acd6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 02bcdb7194..94a7c76edd 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3163,7 +3163,13 @@"math": "Mathematical symbols","math_description": "Turns fractions such as 1/2 into ½, and the operators <=, >=, !=, <- and -> into ≤, ≥, ≠, ← and →.","symbols": "Copyright and trademark",- "symbols_description": "Turns (c), (r) and (tm) into ©, ® and ™."+ "symbols_description": "Turns (c), (r) and (tm) into ©, ® and ™.",+ "custom": "Your own replacements",+ "custom_description": "Each is replaced once you have typed it as a whole word and followed it with a space, so longer words starting with it are left alone.",+ "custom_from_placeholder": "When I type…",+ "custom_to_placeholder": "…replace it with",+ "custom_add": "Add replacement",+ "custom_remove": "Remove this replacement"},"editorfeatures": {"title": "Features",diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.css b/apps/client/src/widgets/type_widgets/options/text_notes.cssindex 2185d318a0..3119379544 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.css+++ b/apps/client/src/widgets/type_widgets/options/text_notes.css@@ -127,3 +127,32 @@.code-sample-wrapper {padding-top: 0.75em;}++.custom-replacements {+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding-top: 0.75em;++ .custom-replacement-row {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ /* min-width lets the boxes shrink with the pane; without it flex refuses to go below the+ intrinsic input width and the delete button is pushed out of the card. */+ .custom-replacement-row input {+ flex: 1;+ min-width: 0;+ }++ .custom-replacement-arrow {+ flex-shrink: 0;+ opacity: 0.5;+ }++ .custom-replacement-add {+ align-self: flex-start;+ }+}diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsxindex 0cb5d5c991..b4c4bf5493 100644--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx@@ -3,12 +3,14 @@ import "./text_notes.css";import { normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import { getThemeVariant, Themes } from "@triliumnext/highlightjs";import type { CSSProperties } from "preact/compat";-import { useEffect, useMemo, useState } from "preact/hooks";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";import { isExperimentalFeatureEnabled } from "../../../services/experimental_features";import { t } from "../../../services/i18n";import { ensureMimeTypesForHighlighting, loadHighlightingTheme } from "../../../services/syntax_highlight";-import { formatDateTime, toggleBodyClass } from "../../../services/utils";+import { formatDateTime, randomString, toggleBodyClass } from "../../../services/utils";+import ActionButton from "../../react/ActionButton";+import Button from "../../react/Button";import Dropdown from "../../react/Dropdown";import FormGroup from "../../react/FormGroup";import { FormListItem } from "../../react/FormList";@@ -17,6 +19,7 @@ import FormText from "../../react/FormText";import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";import { useColorScheme, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { getHtml } from "../../react/RawHtml";+import { type CustomReplacement, parseCustomReplacements } from "../text/replacements";import OptionsPageHeader from "./components/OptionsPageHeader";import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";import OptionsSection from "./components/OptionsSection";@@ -222,10 +225,100 @@ function AutomaticReplacements() {currentValue={symbolsEnabled}onChange={setSymbolsEnabled}/>++ <CustomReplacements /></OptionsSection>);}+/** A row while it is being edited: the stored pair plus a key that survives its neighbours moving. */+interface EditableReplacement extends CustomReplacement {+ id: string;+}++/**+ * The user's own replacements, edited in place.+ *+ * The rows are held locally and written to the option when a field is left rather than on every+ * keystroke, so typing a replacement is not a request per character. A half-written row is stored as+ * it stands — {@link buildCustomTransformations} ignores a pair with either side blank — so nothing+ * the user is in the middle of typing is thrown away or acts before it is finished.+ */+function CustomReplacements() {+ const [ storedJson, setStoredJson ] = useTriliumOption("textNoteCustomReplacements");+ const [ rows, setRows ] = useState<EditableReplacement[]>(+ () => parseCustomReplacements(storedJson).map((replacement) => ({ ...replacement, id: randomString(8) }))+ );+ // The row to put the caret in once it has rendered — the one just added, and nothing afterwards.+ const [ focusedId, setFocusedId ] = useState<string>();++ // Blur handlers are created in the render that made the row, so reading `rows` from their closure+ // would persist a stale list. The ref always holds what is on screen now.+ const rowsRef = useRef(rows);+ rowsRef.current = rows;++ function persist(next: EditableReplacement[]) {+ void setStoredJson(JSON.stringify(next.map(({ from, to }) => ({ from, to }))));+ }++ function editRow(id: string, changes: Partial<CustomReplacement>) {+ setRows((current) => current.map((row) => (row.id === id ? { ...row, ...changes } : row)));+ }++ function addRow() {+ const row: EditableReplacement = { id: randomString(8), from: "", to: "" };+ setRows((current) => [ ...current, row ]);+ setFocusedId(row.id);+ }++ function removeRow(id: string) {+ const next = rowsRef.current.filter((row) => row.id !== id);+ setRows(next);+ persist(next);+ }++ return (+ <div className="custom-replacements">+ <div className="option-row-label">+ <label>{t("automatic_replacements.custom")}</label>+ <small className="option-row-description">{t("automatic_replacements.custom_description")}</small>+ </div>++ {rows.map((row) => (+ <div className="custom-replacement-row" key={row.id}>+ <FormTextBox+ currentValue={row.from}+ placeholder={t("automatic_replacements.custom_from_placeholder")}+ autoFocus={row.id === focusedId}+ onChange={(newValue) => editRow(row.id, { from: newValue })}+ onBlur={() => persist(rowsRef.current)}+ />+ <span className="custom-replacement-arrow" aria-hidden="true">→</span>+ <FormTextBox+ currentValue={row.to}+ placeholder={t("automatic_replacements.custom_to_placeholder")}+ onChange={(newValue) => editRow(row.id, { to: newValue })}+ onBlur={() => persist(rowsRef.current)}+ />+ <ActionButton+ icon="bx bx-trash"+ text={t("automatic_replacements.custom_remove")}+ onClick={() => removeRow(row.id)}+ />+ </div>+ ))}++ <Button+ className="custom-replacement-add"+ icon="bx-plus"+ text={t("automatic_replacements.custom_add")}+ size="micro"+ onClick={addRow}+ />+ </div>+ );+}+function Editor() {const [headingStyle, setHeadingStyle] = useTriliumOption("headingStyle");const [autoReadonlySize, setAutoReadonlySize] = useTriliumOption("autoReadonlySizeText");diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 4318653411..7887b84062 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -62,6 +62,9 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReconst [ punctuationReplacements ] = useTriliumOptionBool("textNotePunctuationReplacementsEnabled");const [ mathReplacements ] = useTriliumOptionBool("textNoteMathReplacementsEnabled");const [ symbolReplacements ] = useTriliumOptionBool("textNoteSymbolReplacementsEnabled");+ // The raw JSON, deliberately: `useTriliumOptionJson` parses on every render and would hand back a+ // new array each time, rebuilding the editor continuously. A string compares by value.+ const [ customReplacements ] = useTriliumOption("textNoteCustomReplacements");// Which language a note with no `#language` of its own is written in, and so which quotes it// gets. The UI locale it can fall back to is already covered by `uiLanguage` above.const [ defaultContentLanguage ] = useTriliumOption("defaultContentLanguage");@@ -293,7 +296,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe}, [contentLanguage, uiLanguage, isClassicEditor, multilineToolbar,quoteReplacements, punctuationReplacements, mathReplacements, symbolReplacements,- defaultContentLanguage+ customReplacements, defaultContentLanguage]);// Push snippet ("template") definitions into the live editor instead of rebuilding it. The premiumdiff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 891b89e03f..dd3f2707a7 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -304,6 +304,26 @@ describe("CK config - language & emoji", () => {expect(allOff.typing?.transformations.remove).toEqual(["typography", "mathematical", "symbols", "quotes"]);});+ it("adds the user's own replacements alongside the quote ones", async () => {+ optionsState.map.textNoteCustomReplacements = `[{"from":"TN","to":"Trilium Notes"},{"from":"half","to":""}]`;++ const config = await buildConfig(baseOpts({ contentLanguage: "de" }));++ // Two quote transformations plus the one finished custom pair; the half-written row compiles+ // to nothing rather than acting before it is done.+ expect(config.typing?.transformations.extra).toHaveLength(3);+ expect(String((config.typing?.transformations.extra?.[2] as { from: RegExp }).from)).toContain("TN");+ });++ it("survives a custom replacements option that cannot be read", async () => {+ optionsState.map.textNoteCustomReplacements = "}} not json {{";++ const config = await buildConfig(baseOpts({ contentLanguage: "de" }));++ // The editor still builds, with the quotes intact and no custom pairs.+ expect(config.typing?.transformations.extra).toHaveLength(2);+ });+it("drops the quote replacements entirely when their toggle is off", async () => {optionsState.map.textNoteQuoteReplacementsEnabled = "false";diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex e0e4522097..b815029471 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -16,6 +16,7 @@ import { isMac } from "../../../services/utils.js";import { resolveContentLanguage } from "../../../utils/formatters.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import { buildQuoteTransformations, resolveQuoteStyle } from "./quotes.js";+import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";/**@@ -332,10 +333,15 @@ function buildTransformationsConfig(contentLanguage: string | null): TextTransforemove.push("quotes");}+ const extra = [+ ...(quoteStyle ? buildQuoteTransformations(quoteStyle) : []),+ ...buildCustomTransformations(parseCustomReplacements(options.get("textNoteCustomReplacements")))+ ];+// `include` is typed as required even though upstream's own documented examples pass `remove`// alone, and the plugin defines the default set in its constructor. Narrowed here rather than// restating the default groups, so that a group upstream adds later keeps working.- return { remove, extra: quoteStyle ? buildQuoteTransformations(quoteStyle) : [] } as TextTransformationConfig;+ return { remove, extra } as TextTransformationConfig;}/**diff --git a/apps/client/src/widgets/type_widgets/text/replacements.spec.ts b/apps/client/src/widgets/type_widgets/text/replacements.spec.tsnew file mode 100644index 0000000000..a01bdbb9aa--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/replacements.spec.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from "vitest";++import { buildCustomTransformations, type CustomReplacement, parseCustomReplacements } from "./replacements.js";++/**+ * Applies a transformation the way CKEditor's `TextTransformation` does — match the text before the+ * caret, then swap in every group the `to` array names — so the pattern and the replacement are+ * asserted together rather than by eyeballing the regex.+ */+function transform(replacement: CustomReplacement, text: string) {+ const [ transformation ] = buildCustomTransformations([ replacement ]);+ if (!transformation) return null;++ const { from, to } = transformation;+ if (!(from instanceof RegExp) || !Array.isArray(to)) {+ throw new Error("custom replacements are built as a RegExp plus a replacement array");+ }++ const matches = from.exec(text);+ if (!matches) return null;++ let result = text.slice(0, matches.index);+ for (let i = 1; i < matches.length; i++) {+ result += to[i - 1] ?? matches[i];+ }+ return result + text.slice(matches.index + matches[0].length);+}++describe("parseCustomReplacements", () => {+ it("reads the stored pairs", () => {+ expect(parseCustomReplacements(`[{"from":"TN","to":"Trilium Notes"}]`)).toEqual([+ { from: "TN", to: "Trilium Notes" }+ ]);+ });++ it("degrades to none for anything the option is not", () => {+ // It is user-entered content that syncs between devices, so a value that cannot be read has+ // to leave the editor working rather than take it down with it.+ for (const stored of [ "", null, undefined, "not json", "null", "42", `{"from":"a"}` ]) {+ expect(parseCustomReplacements(stored), String(stored)).toEqual([]);+ }+ });++ it("drops entries that are not a pair of strings, keeping the ones that are", () => {+ const stored = `[{"from":"TN","to":"Trilium Notes"},{"from":"x"},null,42,{"from":1,"to":2},{"from":"a","to":"b"}]`;++ expect(parseCustomReplacements(stored)).toEqual([+ { from: "TN", to: "Trilium Notes" },+ { from: "a", to: "b" }+ ]);+ });+});++describe("buildCustomTransformations", () => {+ it("replaces the text once it is followed by a space, keeping the space", () => {+ expect(transform({ from: "TN", to: "Trilium Notes" }, "about TN ")).toBe("about Trilium Notes ");+ // Opening the line counts as a boundary too.+ expect(transform({ from: "TN", to: "Trilium Notes" }, "TN ")).toBe("Trilium Notes ");+ });++ it("leaves a longer word that merely starts or ends with the text alone", () => {+ // Passing a bare string to CKEditor compiles to /(TN)$/, which would rewrite the tail of this.+ expect(transform({ from: "TN", to: "Trilium Notes" }, "BTN ")).toBeNull();+ // Firing on the closing space rather than the last letter is what keeps this typeable.+ expect(transform({ from: "TN", to: "Trilium Notes" }, "TNT ")).toBeNull();+ // ...and until that space arrives, nothing happens.+ expect(transform({ from: "TN", to: "Trilium Notes" }, "about TN")).toBeNull();+ });++ it("treats the typed text as literal, never as a pattern", () => {+ // A regular expression would match "xyz" here; a literal only matches the characters typed.+ expect(transform({ from: ".+", to: "…" }, "xyz ")).toBeNull();+ expect(transform({ from: ".+", to: "…" }, "a .+ ")).toBe("a … ");+ // The classic catastrophic-backtracking shape is inert, being matched character for character.+ expect(transform({ from: "(a+)+$", to: "ok" }, "x (a+)+$ ")).toBe("x ok ");+ });++ it("ignores a row that is still half-written", () => {+ expect(buildCustomTransformations([ { from: "", to: "Trilium Notes" } ])).toEqual([]);+ expect(buildCustomTransformations([ { from: "TN", to: "" } ])).toEqual([]);+ expect(buildCustomTransformations([ { from: " ", to: " " } ])).toEqual([]);+ // A finished row beside an unfinished one still compiles.+ expect(buildCustomTransformations([ { from: "TN", to: "" }, { from: "a", to: "b" } ])).toHaveLength(1);+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/replacements.ts b/apps/client/src/widgets/type_widgets/text/replacements.tsnew file mode 100644index 0000000000..f992e080c8--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/replacements.ts@@ -0,0 +1,62 @@+import type { TextTypingTransformationDescription } from "@triliumnext/ckeditor5";++import { escapeRegExp } from "../../../services/utils.js";++/** One replacement the user wrote: the text they type, and what it becomes. */+export interface CustomReplacement {+ from: string;+ to: string;+}++/**+ * Reads the stored replacements, tolerating anything the option is not.+ *+ * It is user-entered content that syncs between devices, so a value that is malformed — hand-edited,+ * written by an older version, corrupted in transit — must degrade to "no custom replacements"+ * rather than break the editor it is read by.+ */+export function parseCustomReplacements(json: string | null | undefined): CustomReplacement[] {+ if (!json) return [];++ let parsed: unknown;+ try {+ parsed = JSON.parse(json);+ } catch {+ return [];+ }++ if (!Array.isArray(parsed)) return [];+ return parsed+ .filter((entry): entry is CustomReplacement =>+ !!entry && typeof entry === "object"+ && typeof (entry as CustomReplacement).from === "string"+ && typeof (entry as CustomReplacement).to === "string");+}++/**+ * Compiles the replacements into the transformations CKEditor's `typing.transformations.extra` takes.+ *+ * Two things are decided here rather than left to the user:+ *+ * The pattern is built from the typed text as a literal — never taken as a regular expression. It is+ * `.test()`-ed against the text before the caret on every keystroke and syncs to every device, so one+ * catastrophically backtracking pattern would hang the editor everywhere. There is no user demand+ * this would serve that plain text does not.+ *+ * And it matches a whole word: the text has to start the line or follow a space, and be followed by+ * one. Passing a bare string to CKEditor compiles to `/(text)$/`, which fires mid-word — a `TN`+ * replacement would rewrite the tail of `BTN` — and firing on the closing space rather than on the+ * last letter is what lets `TNT` still be typed. It is the same shape upstream gives its en dash,+ * and the behaviour every office suite's autocorrect has taught people to expect.+ *+ * A half-written row (either side still blank) compiles to nothing, so a replacement being typed in+ * the settings does not act until it is finished.+ */+export function buildCustomTransformations(replacements: CustomReplacement[]): TextTypingTransformationDescription[] {+ return replacements+ .filter(({ from, to }) => from.trim().length > 0 && to.trim().length > 0)+ .map(({ from, to }) => ({+ from: new RegExp(`(^|\\s)(${escapeRegExp(from)})(\\s)$`),+ to: [null, to, null]+ }));+}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 61e8c2f009..50344d84d1 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -252,6 +252,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActitextNoteMathReplacementsEnabled: boolean;/** Whether `(c)`, `(r)` and `(tm)` become `©`, `®` and `™` as they are typed. */textNoteSymbolReplacementsEnabled: boolean;+ /** JSON: the user's own replacements, as `{ from, to }` pairs — see `CustomReplacement`. */+ textNoteCustomReplacements: string;/** Whether keyboard auto-completion for emojis is triggered when typing `:`. */textNoteEmojiCompletionEnabled: boolean;/** Whether keyboard auto-completion for notes is triggered when typing `@` in text notes (attribute editing is not affected). */diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex ba201d8499..4b26179338 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -128,6 +128,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["textNotePunctuationReplacementsEnabled","textNoteMathReplacementsEnabled","textNoteSymbolReplacementsEnabled",+ "textNoteCustomReplacements","textNoteEmojiCompletionEnabled","textNoteCompletionEnabled","textNoteSlashCommandsEnabled",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 993c718a0b..565cedd104 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -312,6 +312,7 @@ const defaultOptions: DefaultOption[] = [{ name: "textNotePunctuationReplacementsEnabled", value: "true", isSynced: true },{ name: "textNoteMathReplacementsEnabled", value: "true", isSynced: true },{ name: "textNoteSymbolReplacementsEnabled", value: "true", isSynced: true },+ { name: "textNoteCustomReplacements", value: "[]", isSynced: true },{ name: "textNoteEmojiCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteCompletionEnabled", value: "true", isSynced: true },{ name: "textNoteSlashCommandsEnabled", value: "true", isSynced: true },