Skip to content

Build your personal knowledge base with Trilium Notes

refactor(collections/dashboard): simplify handling of external changes

Elian Doran008a55160dcb
diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsx
index 01d9a1e13e..1a09effd99 100644
--- a/apps/client/src/widgets/collections/NoteList.tsx
+++ b/apps/client/src/widgets/collections/NoteList.tsx
@@ -230,20 +230,38 @@ export function useViewModeConfig<T extends object>(note: FNote | null | undefin
storeFn: (data: T) => void;
note: FNote;
}>();
+ const storageRef = useRef<{ storage: ViewModeStorage<T>, storeFn: (data: T) => void, note: FNote }>();
useEffect(() => {
if (!note || !viewType) return;
setViewConfig(undefined);
const viewStorage = new ViewModeStorage<T>(note, viewType);
+ const storeFn = (config: T) => {
+ setViewConfig({ note, config, storeFn });
+ viewStorage.store(config);
+ };
+ storageRef.current = { storage: viewStorage, storeFn, note };
viewStorage.restore().then(config => {
- const storeFn = (config: T) => {
- setViewConfig({ note, config, storeFn });
- viewStorage.store(config);
- };
setViewConfig({ note, config, storeFn });
});
}, [ note, viewType ]);
+ // Reload the config when the underlying attachment changes externally
+ // (e.g. the same view opened in another split, or synced from another instance).
+ // Echoes of our own saves are filtered out by the storage, so views are never handed
+ // a fresh config object for content they already have.
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ const current = storageRef.current;
+ if (!current || current.note !== note) return;
+ if (!loadResults.getAttachmentRows().some(att => att.ownerId === current.note.noteId && att.title === current.storage.attachmentName)) {
+ return;
+ }
+ current.storage.restoreIfChanged().then(config => {
+ if (config === undefined) return;
+ setViewConfig({ note: current.note, config, storeFn: current.storeFn });
+ });
+ });
+
// Only expose config for the current note, avoid leaking notes when switching between them.
if (viewConfig?.note !== note) return undefined;
return viewConfig;
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 7267b27a75..04d1eba76a 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -124,8 +124,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
loadResults.getBranchRows().some(branch => noteIds.includes(branch.noteId!)) ||
// React to changes in note icon or color.
loadResults.getAttributeRows().some(attr => [ "iconClass", "color" ].includes(attr.name ?? "") && noteIds.includes(attr.noteId ?? "")) ||
- // React to attachment change
- loadResults.getAttachmentRows().some(att => att.ownerId === parentNote.noteId && att.title === "board.json") ||
+ // External changes to the board.json attachment arrive via the viewConfig prop
+ // (see useViewModeConfig), which re-triggers the refresh effect.
// React to changes in "groupBy"
loadResults.getAttributeRows().some(attr => attr.name === "board:groupBy" && attr.noteId === parentNote.noteId);
diff --git a/apps/client/src/widgets/collections/dashboard/index.tsx b/apps/client/src/widgets/collections/dashboard/index.tsx
index ed01a6ad1f..5aaf141e7f 100644
--- a/apps/client/src/widgets/collections/dashboard/index.tsx
+++ b/apps/client/src/widgets/collections/dashboard/index.tsx
@@ -11,12 +11,11 @@ import linkContextMenuService from "../../../menus/link_context_menu";
import froca from "../../../services/froca";
import CollectionProperties from "../../note_bars/CollectionProperties";
import ActionButton from "../../react/ActionButton";
-import { useNoteLabelBoolean, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";
+import { useNoteLabelBoolean, useSpacedUpdate } from "../../react/hooks";
import Icon from "../../react/Icon";
import NoteLink from "../../react/NoteLink";
import { ViewModeProps } from "../interface";
import { getNotePath, NoteContent } from "../legacy/ListOrGridView";
-import ViewModeStorage from "../view_mode_storage";
interface DashboardWidgetLayout {
x: number;
@@ -31,7 +30,6 @@ export interface DashboardViewConfig {
const DEFAULT_WIDGET_SIZE = { w: 4, h: 3 };
const INITIALIZED_CLASS = "dashboard-widget-initialized";
-const CONFIG_ATTACHMENT_TITLE = "dashboard.json";
export default function DashboardView({ note, noteIds, viewConfig, saveConfig, highlightedTokens, showTextRepresentation }: ViewModeProps<DashboardViewConfig>) {
const [ notes, setNotes ] = useState<FNote[]>([]);
@@ -126,22 +124,18 @@ export default function DashboardView({ note, noteIds, viewConfig, saveConfig, h
persistLayout(grid);
}, [ notes ]);
- // React to external changes of the layout attachment (e.g. the same dashboard open in
- // another split or synced from another instance).
- useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- if (!loadResults.getAttachmentRows().some((att) => att.ownerId === note.noteId && att.title === CONFIG_ATTACHMENT_TITLE)) {
+ // React to external changes of the layout (e.g. the same dashboard open in another split
+ // or synced from another instance) propagated through the viewConfig prop.
+ useEffect(() => {
+ const widgets = viewConfig?.widgets ?? {};
+ if (pendingConfigRef.current || sameLayout(widgets, savedWidgetsRef.current)) {
+ // Local changes take precedence; identical layouts (e.g. our own save echoing back)
+ // need no re-apply.
return;
}
- new ViewModeStorage<DashboardViewConfig>(note, "dashboard").restore().then((config) => {
- const widgets = config?.widgets ?? {};
- if (sameLayout(widgets, savedWidgetsRef.current)) {
- // Our own save echoing back, or no effective change.
- return;
- }
- savedWidgetsRef.current = widgets;
- applyLayout(widgets);
- });
- });
+ savedWidgetsRef.current = widgets;
+ applyLayout(widgets);
+ }, [ viewConfig ]);
function applyLayout(widgets: Record<string, DashboardWidgetLayout>) {
const grid = gridRef.current;
diff --git a/apps/client/src/widgets/collections/view_mode_storage.ts b/apps/client/src/widgets/collections/view_mode_storage.ts
index b8c3b94f25..88609a7390 100644
--- a/apps/client/src/widgets/collections/view_mode_storage.ts
+++ b/apps/client/src/widgets/collections/view_mode_storage.ts
@@ -9,7 +9,9 @@ export type ViewModeStorageType = ViewTypeOptions | "pdfHistory";
export default class ViewModeStorage<T extends object> {
private note: FNote;
- private attachmentName: string;
+ readonly attachmentName: string;
+ /** The serialized content last stored or restored, used to tell our own echoes apart from external changes. */
+ private lastKnownContent?: string;
constructor(note: FNote, viewType: ViewModeStorageType) {
this.note = note;
@@ -17,17 +19,42 @@ export default class ViewModeStorage<T extends object> {
}
async store(data: T) {
+ const content = JSON.stringify(data);
+ this.lastKnownContent = content;
const payload = {
role: ATTACHMENT_ROLE,
title: this.attachmentName,
mime: "application/json",
- content: JSON.stringify(data),
+ content,
position: 0
};
await server.post(`notes/${this.note.noteId}/attachments?matchBy=title`, payload);
}
async restore() {
+ const content = await this.fetchContent();
+ if (content === undefined) {
+ return undefined;
+ }
+ this.lastKnownContent = content;
+ return JSON.parse(content) as T;
+ }
+
+ /**
+ * Like {@link restore}, but resolves to `undefined` if the stored content matches what was last
+ * stored or restored, so that callers only react to genuinely external changes (e.g. the same
+ * view opened in another split, or synced from another instance).
+ */
+ async restoreIfChanged() {
+ const content = await this.fetchContent();
+ if (content === undefined || content === this.lastKnownContent) {
+ return undefined;
+ }
+ this.lastKnownContent = content;
+ return JSON.parse(content) as T;
+ }
+
+ private async fetchContent() {
const existingAttachments = (await this.note.getAttachmentsByRole(ATTACHMENT_ROLE))
.filter(a => a.title === this.attachmentName);
if (existingAttachments.length === 0) {
@@ -41,6 +68,6 @@ export default class ViewModeStorage<T extends object> {
const attachment = existingAttachments[0];
const attachmentData = await server.get<{ content: string } | null>(`attachments/${attachment.attachmentId}/blob`);
- return JSON.parse(attachmentData?.content ?? "{}") as T;
+ return attachmentData?.content ?? "{}";
}
}