Skip to content

Build your personal knowledge base with Trilium Notes

fix(editor): follow the option when it moves underneath the page

Elian Doran405fb80b2636
diff --git a/apps/client/src/widgets/note_wrapper.ts b/apps/client/src/widgets/note_wrapper.ts
index 918404801d..861319cb1a 100644
--- a/apps/client/src/widgets/note_wrapper.ts
+++ b/apps/client/src/widgets/note_wrapper.ts
@@ -78,6 +78,9 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {
const noteId = this.noteContext?.noteId;
if (
loadResults.isNoteReloaded(noteId) ||
+ // The direction of a note carrying no `#language` comes from this option, so a change to it
+ // has to repaint the `rtl` class the same way a change to the label would.
+ loadResults.isOptionReloaded("defaultContentLanguage") ||
loadResults.getAttributeRows().find((attr) => attr.type === "label" && LABELS_CAUSING_REFRESH.includes(attr.name ?? "") && attributeService.isAffecting(attr, this.noteContext?.note))
) {
this.refresh();
diff --git a/apps/client/src/widgets/type_widgets/options/custom_replacements.spec.tsx b/apps/client/src/widgets/type_widgets/options/custom_replacements.spec.tsx
new file mode 100644
index 0000000000..b2ddd0486a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/custom_replacements.spec.tsx
@@ -0,0 +1,133 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+/** The option as the store holds it, every value written to it, and who is watching it. */
+const state = vi.hoisted(() => ({
+ stored: "[]",
+ writes: [] as string[],
+ watchers: new Set<(newValue: string) => void>()
+}));
+
+// Only `useTriliumOption` is replaced — the rest of the module stays real, so the buttons and text
+// boxes this renders keep the hooks they use.
+//
+// The stand-in holds the value in state and re-reads it when the store changes, as the real hook
+// does through `entitiesReloaded`. That is the whole point here: the bug is about the option moving
+// underneath a mounted page, and a stand-in that only returned the current value would never
+// reproduce it.
+vi.mock("../../react/hooks", async (importOriginal) => {
+ const { useEffect: onMount, useState: useLocal } = await import("preact/hooks");
+ return {
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: () => {
+ const [ value, setValue ] = useLocal(state.stored);
+ onMount(() => {
+ state.watchers.add(setValue);
+ return () => void state.watchers.delete(setValue);
+ }, []);
+ return [
+ value,
+ (newValue: string) => {
+ state.writes.push(newValue);
+ writeStore(newValue);
+ return Promise.resolve();
+ }
+ ];
+ }
+ };
+});
+
+/** Puts a value in the store and tells everyone reading it, the way an entity reload would. */
+function writeStore(newValue: string) {
+ state.stored = newValue;
+ for (const watcher of state.watchers) watcher(newValue);
+}
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+import { parseCustomReplacements } from "../text/replacements";
+import { CustomReplacements } from "./text_notes";
+
+/** Renders the editor and returns the container, so its inputs can be driven. */
+function renderEditor() {
+ const container = document.createElement("div");
+ document.body.append(container);
+ act(() => render(<CustomReplacements />, container));
+ return container;
+}
+
+const inputs = (container: HTMLElement) => [ ...container.querySelectorAll("input") ];
+
+/**
+ * Leaving a field, which is what commits the rows. Dispatched as `focusout`: preact/compat is loaded
+ * across the module graph and, like React, implements `onBlur` over the bubbling event rather than
+ * the native `blur`, which does not bubble.
+ */
+function blur(input: HTMLInputElement) {
+ act(() => {
+ input.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ });
+}
+
+afterEach(() => {
+ state.stored = "[]";
+ state.writes = [];
+ state.watchers.clear();
+ document.body.innerHTML = "";
+});
+
+describe("CustomReplacements", () => {
+ it("shows the stored pairs", () => {
+ state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+
+ expect(inputs(renderEditor()).map((input) => input.value)).toEqual([ "TN", "Trilium Notes" ]);
+ });
+
+ it("writes the rows when a field is left, not on every keystroke", () => {
+ state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ const container = renderEditor();
+ const [ from ] = inputs(container);
+
+ act(() => {
+ from.value = "TNX";
+ from.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect(state.writes, "typing alone must not reach the server").toEqual([]);
+
+ blur(from);
+ expect(parseCustomReplacements(state.writes.at(-1))).toEqual([ { from: "TNX", to: "Trilium Notes" } ]);
+ });
+
+ it("takes up a list that arrived from elsewhere instead of writing over it", () => {
+ // The reported case: the option changes underneath the open page — synced from another
+ // device, or saved by a second settings tab. Rows read once at mount would stay as they
+ // were, and the next blur would put the stale list back over the newer one.
+ state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ const container = renderEditor();
+
+ act(() => writeStore(`[{"from":"CT","to":"CherryTree"}]`));
+
+ expect(inputs(container).map((input) => input.value)).toEqual([ "CT", "CherryTree" ]);
+
+ // ...and leaving a field now writes what arrived, rather than resurrecting what it replaced.
+ blur(inputs(container)[0]);
+ expect(parseCustomReplacements(state.writes.at(-1))).toEqual([ { from: "CT", to: "CherryTree" } ]);
+ });
+
+ it("keeps what is being typed when the option settles to what we just wrote", () => {
+ // Our own save comes back through the same subscription; re-reading it then would throw away
+ // whatever had been typed since, and move the caret.
+ state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ const container = renderEditor();
+ const [ from ] = inputs(container);
+
+ act(() => {
+ from.value = "TNX";
+ from.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ blur(from);
+
+ expect(inputs(container).map((input) => input.value)).toEqual([ "TNX", "Trilium Notes" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.tsx
index d36e35f152..0d5b87c2e4 100644
--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx
@@ -279,11 +279,9 @@ interface EditableReplacement extends CustomReplacement {
* 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() {
+export function CustomReplacements() {
const [ storedJson, setStoredJson ] = useTriliumOption("textNoteCustomReplacements");
- const [ rows, setRows ] = useState<EditableReplacement[]>(
- () => parseCustomReplacements(storedJson).map((replacement) => ({ ...replacement, id: randomString(8) }))
- );
+ const [ rows, setRows ] = useState<EditableReplacement[]>(() => toRows(storedJson));
// The row to put the caret in once it has rendered — the one just added, and nothing afterwards.
const [ focusedId, setFocusedId ] = useState<string>();
@@ -292,8 +290,21 @@ function CustomReplacements() {
const rowsRef = useRef(rows);
rowsRef.current = rows;
+ // What we last wrote ourselves. Anything else the option becomes arrived from outside — another
+ // device, or a second settings tab — and has to replace what is on screen: without this the rows
+ // would keep their first value and the next blur would write it back over the newer list.
+ const ownWrite = useRef(storedJson);
+
+ useEffect(() => {
+ if (storedJson === ownWrite.current) return;
+ ownWrite.current = storedJson;
+ setRows(toRows(storedJson));
+ }, [ storedJson ]);
+
function persist(next: EditableReplacement[]) {
- void setStoredJson(JSON.stringify(next.map(({ from, to }) => ({ from, to }))));
+ const json = JSON.stringify(next.map(({ from, to }) => ({ from, to })));
+ ownWrite.current = json;
+ void setStoredJson(json);
}
function editRow(id: string, changes: Partial<CustomReplacement>) {
@@ -354,6 +365,11 @@ function CustomReplacements() {
);
}
+/** The stored pairs as editable rows, each given a key its neighbours moving cannot disturb. */
+function toRows(storedJson: string): EditableReplacement[] {
+ return parseCustomReplacements(storedJson).map((replacement) => ({ ...replacement, id: randomString(8) }));
+}
+
function Editor() {
const [headingStyle, setHeadingStyle] = useTriliumOption("headingStyle");
const [autoReadonlySize, setAutoReadonlySize] = useTriliumOption("autoReadonlySizeText");
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 5d5e07b758..2a707f98cb 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -141,7 +141,10 @@ function useNoteLanguage(note: FNote) {
const [ language ] = useNoteLabel(note, "language");
// Resolved rather than read straight off the label, so a note with no language of its own still
// lays out the way the default content language says it should.
- const isRtl = useMemo(() => isContentRightToLeft(language), [ language ]);
+ // The default is subscribed to as well: `isContentRightToLeft` reads the options store directly,
+ // so without it a note carrying no label of its own would keep its old direction until reopened.
+ const [ defaultContentLanguage ] = useTriliumOption("defaultContentLanguage");
+ const isRtl = useMemo(() => isContentRightToLeft(language), [ language, defaultContentLanguage ]);
return { isRtl };
}