Skip to content

Build your personal knowledge base with Trilium Notes

fix(attributes): keep an attribute's edits however the form is left

Elian Doran631d94e7115d
diff --git a/apps/client/src/widgets/react/master_detail.tsx b/apps/client/src/widgets/react/master_detail.tsx
index 987670bcd8..b33d9a591b 100644
--- a/apps/client/src/widgets/react/master_detail.tsx
+++ b/apps/client/src/widgets/react/master_detail.tsx
@@ -196,7 +196,9 @@ export function MasterDetailModal({ backTitle, listIcon, listActions, children,
const { isMasterDetail, mobileView, switchMobileView, resetMobileView } = useMobileMasterDetail(modalRef);
const showPage = useCallback((title: string | null, close: () => void) => {
- setPage((current) => title === null ? null : (current?.title === title ? current : { title, close }));
+ // Whatever was announced last, `close` included: two pages of the same name are still two pages,
+ // and holding on to the first one's would be closing something else than what is on show.
+ setPage(title === null ? null : { title, close });
switchMobileView(title === null ? "list" : "page");
}, [ switchMobileView ]);
diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
index f5417ee78b..47628e9c1c 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx
@@ -4,12 +4,27 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import FNote from "../../entities/fnote";
-// The panel follows whichever note is being read; the tests hand it one directly.
-const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));
-vi.mock("../react/hooks", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../react/hooks")>()),
- useActiveNoteContext: () => ({ note: shownNote.current })
-}));
+// The panel follows whichever note is being read; the tests hand it one directly. Handing it another
+// redraws it, as the real hook does by listening for the switch — rendering the panel a second time
+// would not: the same element with no props of its own is the same vnode to Preact, which skips it.
+const shownNote = vi.hoisted(() => ({ current: null as FNote | null, listeners: new Set<() => void>() }));
+vi.mock("../react/hooks", async (importOriginal) => {
+ const { useEffect, useState } = await import("preact/hooks");
+
+ return {
+ ...(await importOriginal<typeof import("../react/hooks")>()),
+ useActiveNoteContext: () => {
+ const [ , setRevision ] = useState(0);
+ useEffect(() => {
+ const listener = () => setRevision((revision) => revision + 1);
+ shownNote.listeners.add(listener);
+ return () => shownNote.listeners.delete(listener);
+ }, []);
+
+ return { note: shownNote.current };
+ }
+ };
+});
// Deleting is confirmed first, and adding goes through a menu; neither dialog belongs to this widget.
const confirm = vi.hoisted(() => vi.fn(async () => true));
@@ -230,6 +245,26 @@ describe("AttributeList", () => {
act(() => container.querySelector<HTMLElement>(".attribute-list-panel")?.click());
expect(document.querySelector(".attr-detail")).toBeNull();
+ // Closing keeps what was typed, whether the press landed beside the rows or clear of the panel:
+ // both are a press away from the form rather than a refusal of what is in it.
+ expect(put).toHaveBeenCalledOnce();
+ expect(put.mock.calls[0][0]).toBe("notes/subject/attributes");
+ });
+
+ it("saves an attribute left open for editing to the note it belongs to, on reading another", () => {
+ renderPanel(noteWithAttributes());
+ act(() => firstRow().click());
+
+ // Read another note without pressing away from the form first, as a keyboard shortcut does.
+ showNote(buildNote({ id: "elsewhere", title: "Elsewhere", "#other": "x" }));
+
+ expect(document.querySelector(".attr-detail")).toBeNull();
+ expect(namesIn(container)).toEqual([ "other" ]);
+ // Saved against the note it was typed on, not against the one now being read.
+ expect(put).toHaveBeenCalledOnce();
+ const [ url, saved ] = put.mock.calls[0] as [ string, { name: string }[] ];
+ expect(url).toBe("notes/subject/attributes");
+ expect(saved.map((attribute) => attribute.name)).toContain("author");
});
it("confirms a deletion before persisting what is left of the note's attributes", async () => {
@@ -314,6 +349,16 @@ describe("AttributeList", () => {
act(() => render(<AttributeList />, container));
}
+ /** Reads another note in the panel already rendered, as navigating to one does. */
+ function showNote(note: FNote) {
+ act(() => {
+ shownNote.current = note;
+ for (const listener of shownNote.listeners) {
+ listener();
+ }
+ });
+ }
+
function cardIds() {
return [ ...container.querySelectorAll(".card") ].map((card) => card.id);
}
diff --git a/apps/client/src/widgets/sidebar/AttributeList.tsx b/apps/client/src/widgets/sidebar/AttributeList.tsx
index d8dc1338e1..abb395ae1d 100644
--- a/apps/client/src/widgets/sidebar/AttributeList.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeList.tsx
@@ -55,18 +55,37 @@ export default function AttributeList() {
const [ , setRevision ] = useState(0);
const rerender = () => setRevision((revision) => revision + 1);
+ // The draft of the note being left, handed over by the check below for the effect to persist: the
+ // note it belongs to is no longer the one the list is showing, so it cannot be saved from here.
+ const draftToFlush = useRef<{ noteId: string; attributes: Attribute[] } | null>(null);
+
// Collected while rendering rather than in an effect, which would leave one frame listing the
// attributes of the note navigated away from. The initial `undefined` is what collects the first.
const shownNoteId = useRef<string | null>();
if (shownNoteId.current !== (note?.noteId ?? null)) {
+ // An attribute left open for editing is closed by the change of note, and closing keeps what
+ // was typed into it — as a press outside does — rather than dropping it. Which the list cannot
+ // do itself once it holds another note's attributes, hence the hand-over.
+ if (detail?.isOwned && shownNoteId.current) {
+ draftToFlush.current = { noteId: shownNoteId.current, attributes: owned.current };
+ }
+
shownNoteId.current = note?.noteId ?? null;
owned.current = collectOwned(note);
inherited.current = collectInherited(note);
internal.current = collectInternal(note);
}
- // The popup edits one attribute of the note being left, so it closes with the note.
- useEffect(() => setDetail(null), [ note ]);
+ // The form edits one attribute of the note being left, so it closes with the note.
+ useEffect(() => {
+ setDetail(null);
+
+ const draft = draftToFlush.current;
+ draftToFlush.current = null;
+ if (draft) {
+ void persist(draft.noteId, draft.attributes);
+ }
+ }, [ note ]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
// While the popup is open, the changes this widget itself made are skipped: its edits are the
@@ -85,10 +104,16 @@ export default function AttributeList() {
/** Persists the whole draft: the endpoint replaces the note's owned attributes with the list. */
async function save() {
if (note) {
- await server.put(`notes/${note.noteId}/attributes`, owned.current, componentId);
+ await persist(note.noteId, owned.current);
}
}
+ /** Named apart from {@link save} so a draft can be saved to the note it belongs to, whichever the
+ * list has moved on to. */
+ async function persist(noteId: string, attributes: Attribute[]) {
+ await server.put(`notes/${noteId}/attributes`, attributes, componentId);
+ }
+
function openDetail(attribute: Attribute, isOwned: boolean, anchor: HTMLElement | null, e: MouseEvent) {
setDetail({
allAttributes: isOwned ? owned.current : undefined,
@@ -215,7 +240,7 @@ export default function AttributeList() {
>
{/* Presses inside the sections do not dismiss the popup (see `parent` above), which
leaves closing on a press next to a row up to this handler. */}
- <div class="attribute-list-panel" ref={containerRef} onClick={() => setDetail(null)}>
+ <div class="attribute-list-panel" ref={containerRef} onClick={commit}>
{sections.owned.length > 0 ? (
<AttributeRowList rows={sections.owned} {...rowProps} />
) : (
@@ -229,7 +254,7 @@ export default function AttributeList() {
id="attributes-inherited"
title={t("attribute_list_panel.inherited", { count: sections.inherited.length })}
>
- <div class="attribute-list-panel" onClick={() => setDetail(null)}>
+ <div class="attribute-list-panel" onClick={commit}>
<AttributeRowList rows={sections.inherited} {...rowProps} />
</div>
</AttributeSection>
@@ -247,7 +272,7 @@ export default function AttributeList() {
/>
)}
>
- <div class="attribute-list-panel" onClick={() => setDetail(null)}>
+ <div class="attribute-list-panel" onClick={commit}>
<AttributeRowList rows={sections.definitions} {...rowProps} />
</div>
</AttributeSection>
@@ -258,7 +283,7 @@ export default function AttributeList() {
id="attributes-internal"
title={t("attribute_list_panel.internal", { count: internalRows.length })}
>
- <div class="attribute-list-panel" onClick={() => setDetail(null)}>
+ <div class="attribute-list-panel" onClick={commit}>
<AttributeRowList rows={internalRows} readOnly {...rowProps} />
</div>
</AttributeSection>