Skip to content

Build your personal knowledge base with Trilium Notes

refactor(editor): hold the custom replacements as chips over a row each

Elian Doran953814c3d5c5
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
index 5ffbc110e2..f02076246c 100644
--- a/apps/client/src/widgets/type_widgets/options/custom_replacements.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/custom_replacements.spec.tsx
@@ -9,13 +9,12 @@ const state = vi.hoisted(() => ({
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.
+// Only `useTriliumOption` is replaced — the rest of the module stays real, so the chips and 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.
+// The stand-in holds the value in state and re-reads it when the store changes, as the real hook does
+// through `entitiesReloaded`: the cases below turn on the option moving underneath a mounted page,
+// which a stand-in only returning the current value could not reproduce.
vi.mock("../../react/hooks", async (importOriginal) => {
const { useEffect: onMount, useState: useLocal } = await import("preact/hooks");
return {
@@ -49,7 +48,6 @@ 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);
@@ -57,19 +55,38 @@ function renderEditor() {
return container;
}
-const inputs = (container: HTMLElement) => [ ...container.querySelectorAll("input") ];
+/** The replacements as the chips show them, each read as the `from → to` it stands for. */
+const chips = (container: HTMLElement) =>
+ [ ...container.querySelectorAll(".tn-chip > span") ].map((chip) => chip.textContent);
-/**
- * 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) {
+/** The two boxes the next pair is typed into. */
+const draftBoxes = (container: HTMLElement) => [ ...container.querySelectorAll("input") ];
+
+/** Types into a box, as a keystroke rather than an assignment. */
+function type(input: HTMLInputElement, value: string) {
act(() => {
- input.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
+/** Enter, which is what takes the pair. */
+function pressEnter(input: HTMLInputElement) {
+ act(() => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ });
+}
+
+/** Types a whole pair and takes it. */
+function addPair(container: HTMLElement, from: string, to: string) {
+ const [ fromBox, toBox ] = draftBoxes(container);
+ type(fromBox, from);
+ type(toBox, to);
+ pressEnter(toBox);
+}
+
+const stored = () => parseCustomReplacements(state.writes.at(-1));
+
afterEach(() => {
state.stored = "[]";
state.writes = [];
@@ -78,89 +95,95 @@ afterEach(() => {
});
describe("CustomReplacements", () => {
- it("shows the stored pairs", () => {
- state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ it("shows what is held as chips, and offers empty boxes for the next", () => {
+ state.stored = `[{"from":"TN","to":"Trilium Notes"},{"from":"teh","to":"the"}]`;
+ const container = renderEditor();
- expect(inputs(renderEditor()).map((input) => input.value)).toEqual([ "TN", "Trilium Notes" ]);
+ expect(chips(container)).toEqual([ "TN → Trilium Notes", "teh → the" ]);
+ expect(draftBoxes(container).map((box) => box.value)).toEqual([ "", "" ]);
});
- it("writes the rows when a field is left, not on every keystroke", () => {
- state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ it("takes a pair on Enter and clears the boxes for the next one", () => {
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([]);
+ addPair(container, "TN", "Trilium Notes");
- blur(from);
- expect(parseCustomReplacements(state.writes.at(-1))).toEqual([ { from: "TNX", to: "Trilium Notes" } ]);
+ expect(stored()).toEqual([ { from: "TN", to: "Trilium Notes" } ]);
+ expect(chips(container)).toEqual([ "TN → Trilium Notes" ]);
+ expect(draftBoxes(container).map((box) => box.value)).toEqual([ "", "" ]);
});
- 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"}]`;
+ it("will not take half a pair", () => {
const container = renderEditor();
+ const [ fromBox ] = draftBoxes(container);
- act(() => writeStore(`[{"from":"CT","to":"CherryTree"}]`));
+ type(fromBox, "TN");
+ pressEnter(fromBox);
- expect(inputs(container).map((input) => input.value)).toEqual([ "CT", "CherryTree" ]);
+ // Storing it would put an entry in the set that could never fire.
+ expect(state.writes).toEqual([]);
+ expect(chips(container)).toEqual([]);
+ });
+
+ it("replaces an entry typed a second time rather than holding both", () => {
+ state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
+ const container = renderEditor();
+
+ addPair(container, "TN", "Trilium");
- // ...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" } ]);
+ expect(stored()).toEqual([ { from: "TN", to: "Trilium" } ]);
});
- it("does not delete a half-written row when a list arrives mid-edit", () => {
- // Adopting the arriving list outright would take the caret's row with it. What is on screen
- // is the later intent of the two, and the blur that ends the edit is what writes it.
+ it("counts a shortcut as the same one whatever case it is typed in", () => {
+ // Matching ignores case, so two entries differing only by it would leave the second unable
+ // ever to fire.
state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
const container = renderEditor();
- const [ from ] = inputs(container);
- from.focus();
- act(() => {
- from.value = "TNX";
- from.dispatchEvent(new Event("input", { bubbles: true }));
- });
+ addPair(container, "tn", "Trilium");
- act(() => writeStore(`[{"from":"CT","to":"CherryTree"}]`));
+ expect(stored()).toEqual([ { from: "tn", to: "Trilium" } ]);
+ });
+
+ it("removes the chip that was pressed, keeping its neighbours", () => {
+ state.stored = `[{"from":"TN","to":"Trilium Notes"},{"from":"teh","to":"the"}]`;
+ const container = renderEditor();
- expect(inputs(container).map((input) => input.value)).toEqual([ "TNX", "Trilium Notes" ]);
+ const [ , removeSecond ] = [ ...container.querySelectorAll<HTMLButtonElement>(".tn-chip-remove") ];
+ act(() => removeSecond.click());
- blur(from);
- expect(parseCustomReplacements(state.writes.at(-1))).toEqual([ { from: "TNX", to: "Trilium Notes" } ]);
+ expect(stored()).toEqual([ { from: "TN", to: "Trilium Notes" } ]);
+ expect(chips(container)).toEqual([ "TN → Trilium Notes" ]);
});
- it("still takes the list when a field only holds the focus", () => {
- // Focus alone is not an edit — there is nothing under the caret to lose, so waiting for a
- // blur that may never come would leave the page showing a list that no longer exists.
+ it("shows a list that arrived from elsewhere without being asked twice", () => {
+ // What is held is read back from the option on every render rather than copied into state at
+ // mount, so there is no second list to fall behind — nor to be written back over this one.
state.stored = `[{"from":"TN","to":"Trilium Notes"}]`;
const container = renderEditor();
- inputs(container)[0].focus();
act(() => writeStore(`[{"from":"CT","to":"CherryTree"}]`));
- expect(inputs(container).map((input) => input.value)).toEqual([ "CT", "CherryTree" ]);
+ expect(chips(container)).toEqual([ "CT → 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"}]`;
+ it("leaves a pair being typed alone when a list arrives", () => {
+ // Only the pair being typed is held locally, and an arriving list is not written into it.
const container = renderEditor();
- const [ from ] = inputs(container);
+ const [ fromBox, toBox ] = draftBoxes(container);
+ type(fromBox, "TN");
+ type(toBox, "Trilium No");
+
+ act(() => writeStore(`[{"from":"CT","to":"CherryTree"}]`));
- act(() => {
- from.value = "TNX";
- from.dispatchEvent(new Event("input", { bubbles: true }));
- });
- blur(from);
+ expect(chips(container)).toEqual([ "CT → CherryTree" ]);
+ expect(draftBoxes(container).map((box) => box.value)).toEqual([ "TN", "Trilium No" ]);
- expect(inputs(container).map((input) => input.value)).toEqual([ "TNX", "Trilium Notes" ]);
+ // ...and taking it keeps what arrived rather than replacing it.
+ pressEnter(toBox);
+ expect(stored()).toEqual([
+ { from: "CT", to: "CherryTree" },
+ { from: "TN", to: "Trilium No" }
+ ]);
});
});
diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.css b/apps/client/src/widgets/type_widgets/options/text_notes.css
index 3119379544..721f16a70f 100644
--- a/apps/client/src/widgets/type_widgets/options/text_notes.css
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.css
@@ -134,17 +134,76 @@
gap: 8px;
padding-top: 0.75em;
- .custom-replacement-row {
+ /*
+ * The two boxes, the arrow between them and the button asking for what they hold, kept together
+ * as the one thing they are: a pair is entered, not a value, so they move and wrap as a unit
+ * rather than the `to` box stranding itself under the chips.
+ *
+ * Given the whole line at the foot of the field rather than a place in among the chips. A pair
+ * needs two boxes and reads as a row of its own, where a single value's box can sit at the end
+ * of the set it adds to; and where the next one is entered stays put as chips are taken and
+ * dropped, instead of moving with the end of a set that wraps.
+ */
+ .custom-replacement-entry {
display: flex;
align-items: center;
- gap: 8px;
+ gap: 6px;
+ flex: 0 0 100%;
+ min-width: 0;
}
- /* 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;
+ /*
+ * Told apart from the set above it, once there is one: what is held and what is being added are
+ * two different things, and the field would otherwise read as a single run of controls. Nothing
+ * to divide it from while the set is empty, where the bar is the whole of the field.
+ */
+ .custom-replacement-entry:not(:first-child) {
+ margin-top: 4px;
+ padding-top: 8px;
+ border-top: 1px solid var(--main-border-color);
+ }
+
+ /*
+ * The boxes keep an edge of their own, which the chips above them give up. `.tn-field` strips it
+ * from the boxes it holds directly so they read as lying on the field rather than sitting in it —
+ * but that is for a box standing among chips, which would otherwise read as another one. This bar
+ * is a row apart below them and is the only place a pair can be entered, so it says where to type
+ * the way `values_input` does for the same reason: with neither edge nor ground, a box reads as a
+ * gap rather than as somewhere to write. Said here rather than left to Bootstrap, whose border
+ * this happens to inherit only because the child selector above does not reach a nested box.
+ */
+ .custom-replacement-entry > .form-control {
+ flex: 1 1 0;
+ min-width: 6ch;
+ background-color: var(--input-background-color);
+ border: 1px solid var(--main-border-color);
+ border-radius: var(--badge-radius, 12px);
+ padding: 4px 10px;
+
+ /* The same ring the field wears, so a box showing its own focus looks no different from the
+ field having shown it. Bootstrap's shadow is cleared rather than left under it, two focus
+ treatments on one box being what this whole rule set is avoiding. */
+ &:focus {
+ outline: 2px solid var(--input-focus-outline-color);
+ box-shadow: none;
+ }
+ }
+
+ /* Roomier than a chip field packed for a note's side pane: this one sits on a settings page with
+ width to spare, and holds a set to read as well as a bar to type in. */
+ > .tn-field {
+ gap: 6px;
+ padding: 6px 8px;
+
+ /*
+ * The field rings itself when something inside takes the focus, standing in for boxes that
+ * have given up frames of their own. These have kept theirs and ring themselves, so the
+ * field doing it too draws a second ring around the first. Only for the boxes: a chip's
+ * remove button has nothing of its own to show focus with, and still needs the field for it.
+ */
+ &:focus-within:has(> .custom-replacement-entry > .form-control:focus) {
+ outline: none;
+ }
}
.custom-replacement-arrow {
@@ -152,7 +211,20 @@
opacity: 0.5;
}
+ /*
+ * Sized to the button a chip is removed by rather than to an icon button anywhere else, so the
+ * field does not grow the moment a pair is complete and shrink again once it is taken — a field
+ * is as tall as the tallest thing in it.
+ */
.custom-replacement-add {
- align-self: flex-start;
+ --icon-button-size: 20px;
+ --icon-button-icon-ratio: 0.9;
+
+ flex-shrink: 0;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ font-size: 18px;
+ line-height: 1;
}
}
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 c99b1b7b86..370ec0b13e 100644
--- a/apps/client/src/widgets/type_widgets/options/text_notes.tsx
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.tsx
@@ -8,9 +8,9 @@ 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, randomString, toggleBodyClass } from "../../../services/utils";
+import { formatDateTime, toggleBodyClass } from "../../../services/utils";
import ActionButton from "../../react/ActionButton";
-import Button from "../../react/Button";
+import Chip from "../../react/Chip";
import Dropdown from "../../react/Dropdown";
import FormGroup from "../../react/FormGroup";
import { FormListItem } from "../../react/FormList";
@@ -266,125 +266,113 @@ function QuoteStyleSelect({ currentValue, onChange }: { currentValue: string, on
);
}
-/** 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 user's own replacements: those already held as chips, and a pair of boxes after them for the
+ * next one.
+ *
+ * Nothing is copied into local state but the pair being typed. What is held *is* the option, read
+ * back on every render, so a list arriving from another device or a second settings tab is simply
+ * what is drawn next — there is no second copy to fall behind it, and none to be written back over
+ * it. The rows this replaced needed a guard for each of those; a set that is added to and removed
+ * from rather than edited in place has neither problem to guard against.
*
- * 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.
+ * A pair cannot be edited once taken, which is what a chip costs. Typing a `from` already held
+ * replaces that entry instead of adding a second one, which gives the editing back without an
+ * affordance for it — and a second entry under the same `from` would in any case be dead weight,
+ * since the first match is the one that fires.
*/
export function CustomReplacements() {
const [ storedJson, setStoredJson ] = useTriliumOption("textNoteCustomReplacements");
- 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>();
+ const replacements = parseCustomReplacements(storedJson);
- // 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;
+ const [ draftFrom, setDraftFrom ] = useState("");
+ const [ draftTo, setDraftTo ] = useState("");
+ const fromRef = useRef<HTMLInputElement>(null);
+ const entryRef = useRef<HTMLDivElement>(null);
- // 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);
- const containerRef = useRef<HTMLDivElement>(null);
+ const isComplete = draftFrom.trim().length > 0 && draftTo.trim().length > 0;
- useEffect(() => {
- if (storedJson === ownWrite.current) return;
-
- // ...except over a field being typed into, where taking the arriving list would delete the
- // half-written row under the caret. What is on screen is then the later intent of the two,
- // and the blur that ends the edit writes it. Only an edit defers it: a field merely holding
- // the focus has nothing to lose, so the list arrives at once.
- const isEditing = containerRef.current?.contains(document.activeElement)
- && serialize(rowsRef.current) !== ownWrite.current;
- if (isEditing) return;
-
- ownWrite.current = storedJson;
- setRows(toRows(storedJson));
- }, [ storedJson ]);
-
- function persist(next: EditableReplacement[]) {
- const json = serialize(next);
- ownWrite.current = json;
- void setStoredJson(json);
+ function save(next: CustomReplacement[]) {
+ 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 take() {
+ const from = draftFrom.trim();
+ const to = draftTo.trim();
+ if (!from || !to) return;
- function addRow() {
- const row: EditableReplacement = { id: randomString(8), from: "", to: "" };
- setRows((current) => [ ...current, row ]);
- setFocusedId(row.id);
- }
+ // Matching ignores case, so what counts as the same shortcut has to as well — otherwise
+ // `TN` and `tn` would sit there as two entries of which only the first could ever fire.
+ const kept = replacements.filter((replacement) => replacement.from.toLowerCase() !== from.toLowerCase());
+ save([ ...kept, { from, to } ]);
- function removeRow(id: string) {
- const next = rowsRef.current.filter((row) => row.id !== id);
- setRows(next);
- persist(next);
+ setDraftFrom("");
+ setDraftTo("");
+ fromRef.current?.focus();
}
return (
- <div className="custom-replacements" ref={containerRef}>
+ <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}>
+ <div className="tn-field">
+ {replacements.map((replacement) => (
+ <Chip
+ key={replacement.from}
+ removeButtonText={t("automatic_replacements.custom_remove")}
+ onRemove={() => save(replacements.filter((held) => held.from !== replacement.from))}
+ >
+ <span>{replacement.from} → {replacement.to}</span>
+ </Chip>
+ ))}
+
+ {/* The two boxes and the button asking for what they hold are one thing on the page,
+ so they wrap as one rather than the button stranding itself on a line of its own. */}
+ <div
+ className="custom-replacement-entry"
+ ref={entryRef}
+ onFocusOut={(e) => {
+ // Moving between the two boxes is not leaving the pair. Only a complete one
+ // is taken on the way out: half of a replacement is not a replacement, and
+ // storing it would put an entry in the set that could never fire.
+ if (e.relatedTarget instanceof Node && entryRef.current?.contains(e.relatedTarget)) return;
+ if (isComplete) take();
+ }}
+ >
<FormTextBox
- currentValue={row.from}
+ inputRef={fromRef}
+ currentValue={draftFrom}
placeholder={t("automatic_replacements.custom_from_placeholder")}
- autoFocus={row.id === focusedId}
- onChange={(newValue) => editRow(row.id, { from: newValue })}
- onBlur={() => persist(rowsRef.current)}
+ onChange={setDraftFrom}
+ onKeyDown={(e) => e.key === "Enter" && take()}
/>
<span className="custom-replacement-arrow" aria-hidden="true">→</span>
<FormTextBox
- currentValue={row.to}
+ currentValue={draftTo}
placeholder={t("automatic_replacements.custom_to_placeholder")}
- onChange={(newValue) => editRow(row.id, { to: newValue })}
- onBlur={() => persist(rowsRef.current)}
+ onChange={setDraftTo}
+ onKeyDown={(e) => e.key === "Enter" && take()}
/>
- <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}
- />
+ {/* Enter takes the pair, but nothing on the page says so — so once there is a
+ whole one to take, the same offer appears where it can be seen. */}
+ {isComplete && (
+ <ActionButton
+ className="custom-replacement-add"
+ icon="bx bx-plus"
+ text={t("automatic_replacements.custom_add")}
+ onClick={take}
+ />
+ )}
+ </div>
+ </div>
</div>
);
}
-/** 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) }));
-}
-
-/** The rows as the option stores them, which is also how "unchanged" is told from "edited". */
-function serialize(rows: EditableReplacement[]): string {
- return JSON.stringify(rows.map(({ from, to }) => ({ from, to })));
-}
-
function Editor() {
const [headingStyle, setHeadingStyle] = useTriliumOption("headingStyle");
const [autoReadonlySize, setAutoReadonlySize] = useTriliumOption("autoReadonlySizeText");