Skip to content

Build your personal knowledge base with Trilium Notes

client: fix some issues

Adorian Doranc2b1be826f67
diff --git a/apps/client/src/widgets/react/SortableCard.spec.tsx b/apps/client/src/widgets/react/SortableCard.spec.tsx
index f54375c619..7779f8c15f 100644
--- a/apps/client/src/widgets/react/SortableCard.spec.tsx
+++ b/apps/client/src/widgets/react/SortableCard.spec.tsx
@@ -482,6 +482,22 @@ describe("SortableCard", () => {
expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "a", "b", "c", "d" ]);
});
+ it("reports to the caller's latest onChange, after the list changed while it asked",
+ async () => {
+ let answer: (item: SortableItem | undefined) => void = () => {};
+ const stale = vi.fn();
+ const props = { itemCreationButtons: [ { label: "Add", onCreateItem: () =>
+ new Promise<SortableItem | undefined>((resolve) => { answer = resolve; }) } ] };
+ draw({ ...props, onChange: stale });
+
+ await click(adder());
+ redraw(items.slice(1), props);
+ await act(async () => { answer({ key: "d", caption: "Delta" }); });
+
+ expect(stale).not.toHaveBeenCalled();
+ expect(changed.at(-1)?.map((item) => item.key)).toEqual([ "b", "c", "d" ]);
+ });
+
it("offers a button for each way of making one, each the width of the others", async () => {
draw({ itemCreationButtons: [
makes("d", "Delta", "Add a note"),
@@ -620,6 +636,49 @@ describe("SortableCard", () => {
});
});
+ /** The caller removes it, from Delete, a button inside it, or a change made elsewhere. */
+ describe("removing the focused entry", () => {
+ it("moves the focus to the entry in its place, else the one before, else the creation row",
+ () => {
+ const props = { itemCreationButtons: [ makes("d", "Delta") ] };
+ draw(props);
+
+ focus(segmentOf("b"));
+ redraw([ items[0], items[2] ], props);
+ expect(document.activeElement).toBe(segmentOf("c"));
+
+ redraw([ items[0] ], props);
+ expect(document.activeElement).toBe(segmentOf("a"));
+
+ redraw([], props);
+ expect(document.activeElement).toBe(adder());
+ });
+
+ it("moves the focus from a control inside the entry too", () => {
+ const props = { renderItem: (item: SortableItem) =>
+ <button type="button" className="own">{item.caption}</button> };
+ draw(props);
+
+ focus(segmentOf("a")?.querySelector<HTMLElement>(".own") ?? null);
+ redraw(items.slice(1), props);
+
+ expect(document.activeElement).toBe(segmentOf("b"));
+ });
+
+ it("leaves the focus where it went once it left the card", () => {
+ draw();
+ const outside = document.createElement("button");
+ document.body.append(outside);
+
+ focus(segmentOf("b"));
+ focus(outside);
+ redraw([ items[0], items[2] ]);
+
+ expect(document.activeElement).toBe(outside);
+ outside.remove();
+ });
+ });
+
/** For a caller that sorts the entries itself, such as by name. */
describe("with the order fixed", () => {
it("draws no grip", () => {
diff --git a/apps/client/src/widgets/react/SortableCard.tsx b/apps/client/src/widgets/react/SortableCard.tsx
index 7dd61a3ff8..1eadd255d7 100644
--- a/apps/client/src/widgets/react/SortableCard.tsx
+++ b/apps/client/src/widgets/react/SortableCard.tsx
@@ -165,9 +165,13 @@ export function SortableCard<T extends SortableItem>({
const pendingFocus = useRef<string | undefined>(undefined);
const shown = draft ?? items;
- /** The current list, for a callback that resumes after an await. */
+ // The current list and `onChange`, for a callback that resumes after an await.
const shownRef = useRef(shown);
+ const onChangeRef = useRef(onChange);
+ /** Read before the commit, which can remove the focused segment. */
+ const focused = focusedEntry(listRef.current, shownRef.current);
shownRef.current = shown;
+ onChangeRef.current = onChange;
const selected = selectedKey ?? ownSelection;
useEffect(() => {
@@ -219,6 +223,21 @@ export function SortableCard<T extends SortableItem>({
segmentOf(key)?.focus();
}, [ segmentOf, select, shown ]);
+ // Removing the focused segment leaves the focus on `document.body`, so it moves to the entry
+ // in its place, else the one before it, else the creation row.
+ useLayoutEffect(() => {
+ if (!focused || shown.some((item) => item.key === focused.key)
+ || (document.activeElement && document.activeElement !== document.body)) {
+ return;
+ }
+
+ if (shown.length) {
+ focusEntry(Math.min(focused.index, shown.length - 1));
+ } else {
+ adderRef.current?.querySelector<HTMLElement>(".tn-sortable-adder")?.focus();
+ }
+ });
+
/** Moves the entry at `from` to `to`, keeping the focus on it. */
const moveItem = useCallback((from: number, to: number) => {
const order = moved(shown, from, to);
@@ -409,8 +428,8 @@ export function SortableCard<T extends SortableItem>({
return;
}
- // Read again instead of closed over: `create` can open a dialog, and an order built from
- // the stale list would undo a reorder made meanwhile.
+ // Both read again instead of closed over: `create` can open a dialog, and the stale list or
+ // `onChange` would undo a change made meanwhile.
const order = [ ...shownRef.current ];
order.splice(at ?? order.length, 0, created);
setAddedKey(created.key);
@@ -419,8 +438,8 @@ export function SortableCard<T extends SortableItem>({
pendingFocus.current = created.key;
}
- onChange(order);
- }, [ onChange ]);
+ onChangeRef.current(order);
+ }, []);
/**
* Ends what `event.pointerId` was doing, and nothing else: a second finger pressed and lifted
@@ -621,6 +640,15 @@ export function SortableCard<T extends SortableItem>({
);
}
+/** The entry whose segment holds the focus, directly or through a control, and its index. */
+function focusedEntry(list: HTMLElement | null, shown: SortableItem[]) {
+ const segment = document.activeElement?.closest<HTMLElement>(".tn-sortable-segment");
+ const index = segment && segment.parentElement === list
+ ? shown.findIndex((item) => item.key === segment.dataset.key)
+ : -1;
+ return index < 0 ? undefined : { key: shown[index].key, index };
+}
+
/**
* How much of the viewport's top and bottom edges fixed chrome covers, a toolbar or a tab bar.
*
diff --git a/apps/client/src/widgets/type_widgets/options/code_mime_types_card.spec.tsx b/apps/client/src/widgets/type_widgets/options/code_mime_types_card.spec.tsx
index b7663ae6fb..df65de2222 100644
--- a/apps/client/src/widgets/type_widgets/options/code_mime_types_card.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/code_mime_types_card.spec.tsx
@@ -160,8 +160,10 @@ describe("CodeMimeTypesCard", () => {
await click(removeButton(container, "Java"));
expect(stored()).toEqual([ PLAIN, FRONTEND, C ]);
+ act(() => segment(container, "C")?.focus());
press(segment(container, "C"), "Delete");
expect(stored()).toEqual([ PLAIN, FRONTEND ]);
+ expect(document.activeElement).toBe(segment(container, "JavaScript (Trilium frontend)"));
press(segment(container, "Plain text"), "Delete");
expect(stored()).toEqual([ PLAIN, FRONTEND ]);
diff --git a/apps/client/src/widgets/type_widgets/options/content_languages_card.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_languages_card.spec.tsx
index c0d17b9961..4cd7852aed 100644
--- a/apps/client/src/widgets/type_widgets/options/content_languages_card.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_languages_card.spec.tsx
@@ -2,10 +2,13 @@ import { LOCALES } from "@triliumnext/commons";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type Component from "../../../components/component";
import dialog from "../../../services/dialog";
+import type LoadResults from "../../../services/load_results";
import options from "../../../services/options";
import { renderInto } from "../../../test/render";
import type { PickerItem } from "../../dialogs/item_picker";
+import { ParentComponent } from "../../react/react_utils";
import { ContentLanguagesCard } from "./content_languages_card";
vi.mock("../../../services/i18n", async (importOriginal) => ({
@@ -74,6 +77,24 @@ describe("ContentLanguagesCard", () => {
expect(names(container)).toEqual([ "Deutsch", "Français", "Italiano", "Română" ]);
});
+ it("keeps a language removed elsewhere while the picker is open", async () => {
+ let answer: (item: PickerItem | null) => void = () => {};
+ vi.spyOn(dialog, "pickSingleItem")
+ .mockReturnValue(new Promise((resolve) => { answer = resolve; }));
+ const container = draw();
+
+ await click(container.querySelector(".tn-sortable-adder"));
+ act(() => {
+ options.set("languages", JSON.stringify([ "ro", "de" ]));
+ reloadOption("languages");
+ });
+ await act(async () => { answer({ key: "it", caption: "Italiano" }); });
+ await act(async () => {});
+
+ expect(stored()).toEqual([ "ro", "de", "it" ]);
+ expect(names(container)).toEqual([ "Deutsch", "Italiano", "Română" ]);
+ });
+
it("says how many languages are left to add, as the first one or another", () => {
expect(draw().querySelector(".tn-sortable-adder")?.textContent?.trim())
.toBe(`content_language.add_another ${LOCALES.length - 3}`);
@@ -84,26 +105,53 @@ describe("ContentLanguagesCard", () => {
});
});
- it("removes a language with its button or Delete", async () => {
+ it("removes a language with its button or Delete, focusing the next one", async () => {
const container = draw();
await click(segment(container, "Français")?.querySelector(".content-languages-remove")
?? null);
expect(stored()).toEqual([ "ro", "de" ]);
+ act(() => segment(container, "Deutsch")?.focus());
press(segment(container, "Deutsch"), "Delete");
expect(stored()).toEqual([ "ro" ]);
expect(names(container)).toEqual([ "Română" ]);
+ expect(document.activeElement).toBe(segment(container, "Română"));
});
});
+type ReloadHandler = (data: { loadResults: LoadResults }) => void;
+
+/** The card's `entitiesReloaded` handlers, which `reloadOption()` calls. */
+const reloadHandlers = new Set<ReloadHandler>();
+
function draw() {
+ const parent = {
+ registerHandler: (name: string, handler: ReloadHandler) => {
+ if (name === "entitiesReloaded") reloadHandlers.add(handler);
+ },
+ removeHandler: (name: string, handler: ReloadHandler) => {
+ if (name === "entitiesReloaded") reloadHandlers.delete(handler);
+ }
+ } as unknown as Component;
+
let container: HTMLElement | undefined;
- act(() => { container = renderInto(<ContentLanguagesCard heading="Languages" />); });
+ act(() => {
+ container = renderInto(
+ <ParentComponent.Provider value={parent}>
+ <ContentLanguagesCard heading="Languages" />
+ </ParentComponent.Provider>);
+ });
if (!container) throw new Error("The card did not render");
return container;
}
+/** Announces a changed option, the way a change made in another window arrives. */
+function reloadOption(name: string) {
+ const loadResults = { getOptionNames: () => [ name ] } as unknown as LoadResults;
+ for (const handler of reloadHandlers) handler({ loadResults });
+}
+
function stored() {
return JSON.parse(options.get("languages"));
}