Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(client): show loading indicator when note content is slow to load
Elian Doran26bddd01eee2
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.tsindex 0dbc637db7..8b3b245894 100644--- a/apps/client/src/components/note_context.ts+++ b/apps/client/src/components/note_context.ts@@ -60,6 +60,13 @@ export interface NoteContextDataMap {saveState: {state: SaveState;};+ /** Published by content widgets (via `useNoteBlob`) while the note's content is being fetched,+ * so the note detail can show a loading state instead of the previous note's content. */+ contentLoad: {+ state: "loading" | "loaded" | "error";+ /** Re-attempts the content fetch (e.g. from a "Retry" button after an error). */+ retry: () => void;+ };}type ContextDataKey = keyof NoteContextDataMap;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 98aa3af230..773ad600e2 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1980,6 +1980,9 @@"window-on-top": "Keep Window on Top"},"note_detail": {+ "content_load_error": "The note's content could not be loaded.",+ "content_load_retry": "Retry",+ "content_load_stalled": "Still loading the note's content…","could_not_find_typewidget": "Could not find typeWidget for type '{{type}}'","printing": "Printing in progress...","printing_pdf": "Preparing print preview...",diff --git a/apps/client/src/widgets/NoteDetail.css b/apps/client/src/widgets/NoteDetail.cssindex b07c6aa061..453c463a57 100644--- a/apps/client/src/widgets/NoteDetail.css+++ b/apps/client/src/widgets/NoteDetail.css@@ -3,6 +3,7 @@font-family: var(--detail-font-family);font-size: var(--detail-font-size);contain: none;+ position: relative; /* anchor for the content-loading overlay */&.fixed-tree {display: flex;@@ -37,3 +38,36 @@ body.prefers-centered-content .note-detail {.note-detail > * {contain: none;}++.note-detail-loading-overlay {+ position: absolute;+ inset: 0;+ z-index: 10;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ background: var(--main-background-color);+ animation: note-detail-loading-overlay-fade-in 100ms ease-in;++ > .bx-loader-alt {+ font-size: 2em;+ color: var(--muted-text-color);+ }+}++/* Dialogs (e.g. the quick-edit popup) paint their content area with the modal background,+ so the overlay must match it there instead of the main background. */+.modal .note-detail-loading-overlay {+ background: var(--modal-background-color);+}++@keyframes note-detail-loading-overlay-fade-in {+ from {+ opacity: 0;+ }++ to {+ opacity: 1;+ }+}diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 199d1a9132..a5d4569561 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -16,7 +16,10 @@ import toast from "../services/toast.js";import { isElectron, isMobile } from "../services/utils";import NoteTreeWidget from "./note_tree";import { ExtendedNoteType, TYPE_MAPPINGS, TypeWidget } from "./note_types";-import { useLegacyWidget, useNoteContext, useTriliumEvent } from "./react/hooks";+import Button from "./react/Button";+import { useDelayedVisibility, useGetContextDataFrom, useLegacyWidget, useNoteContext, useTriliumEvent } from "./react/hooks";+import Icon from "./react/Icon";+import NoItems from "./react/NoItems";import { NoteListWithLinks } from "./react/NoteList";import { TypeWidgetProps } from "./type_widgets/type_widget";@@ -234,6 +237,8 @@ export default function NoteDetail() {props={props}/>;})}++ <NoteDetailLoadingOverlay noteContext={noteContext} /></div>);}@@ -284,6 +289,42 @@ function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: {);}+/**+ * Covers the note detail while the note's content is being fetched, so the user is not left+ * looking at (and typing into) the previous note's content when the blob is slow to arrive.+ *+ * Driven by the `contentLoad` context data published from `useNoteInfo` (type resolution,+ * which fetches the content for the auto-readonly check) and `useNoteBlob` (the editors'+ * own content fetch), and paced by {@link useDelayedVisibility}: fast loads never flash it,+ * slow loads fade it in, and loads stuck past the stall threshold (or failed outright)+ * offer a retry.+ */+function NoteDetailLoadingOverlay({ noteContext }: { noteContext: NoteContext | null | undefined }) {+ const contentLoad = useGetContextDataFrom(noteContext, "contentLoad");+ const phase = useDelayedVisibility(contentLoad?.state === "loading");+ const isError = contentLoad?.state === "error";++ if (!isError && phase === "hidden") {+ return null;+ }++ return (+ <div className="note-detail-loading-overlay">+ {isError ? (+ <NoItems icon="bx bx-error-circle" text={t("note_detail.content_load_error")}>+ <Button text={t("note_detail.content_load_retry")} onClick={() => contentLoad?.retry()} />+ </NoItems>+ ) : phase === "stalled" ? (+ <NoItems icon="bx bx-loader-alt bx-spin" text={t("note_detail.content_load_stalled")}>+ <Button text={t("note_detail.content_load_retry")} onClick={() => contentLoad?.retry()} />+ </NoItems>+ ) : (+ <Icon icon="bx bx-loader-alt bx-spin" />+ )}+ </div>+ );+}+/** Manages both note changes and changes to the widget type, which are asynchronous. */function useNoteInfo() {const { note: actualNote, noteContext, parentComponent } = useNoteContext();@@ -295,11 +336,21 @@ function useNoteInfo() {function refresh() {const refreshId = ++refreshIdRef.current;+ // The type resolution below can take a while (the auto-readonly check of+ // getExtendedWidgetType fetches the note's content), during which the previously+ // rendered note stays visible — cover it with the content-loading overlay.+ if (actualNote) {+ noteContext?.setContextData("contentLoad", { state: "loading", retry: refresh });+ }+getExtendedWidgetType(actualNote, noteContext).then(type => {if (refreshId !== refreshIdRef.current) return;setNote(actualNote);setType(type);setMime(actualNote?.mime);+ if (actualNote) {+ noteContext?.setContextData("contentLoad", { state: "loaded", retry: refresh });+ }});}diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsxnew file mode 100644index 0000000000..ff111272fa--- /dev/null+++ b/apps/client/src/widgets/react/hooks.spec.tsx@@ -0,0 +1,83 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { type DelayedVisibilityPhase, useDelayedVisibility } from "./hooks";++let currentPhase: DelayedVisibilityPhase | undefined;++function Probe({ active }: { active: boolean }) {+ currentPhase = useDelayedVisibility(active, { graceMs: 150, minVisibleMs: 280, stalledMs: 8000 });+ return null;+}++describe("useDelayedVisibility", () => {+ let container: HTMLElement;++ beforeEach(() => {+ vi.useFakeTimers();+ currentPhase = undefined;+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+ });++ async function show(active: boolean) {+ await act(async () => {+ render(<Probe active={active} />, container);+ });+ }++ async function advance(ms: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+ }++ it("never shows when loading finishes within the grace period", async () => {+ await show(true);+ expect(currentPhase).toBe("hidden");++ await advance(100); // still within the 150ms grace window+ await show(false);+ await advance(1000);++ expect(currentPhase).toBe("hidden");+ });++ it("shows after the grace period and stays for the minimum visible time", async () => {+ await show(true);+ await advance(150);+ expect(currentPhase).toBe("visible");++ // Loading finishes shortly after the indicator appeared...+ await advance(10);+ await show(false);++ // ...but the indicator must not flicker away before the minimum visible time.+ await advance(200);+ expect(currentPhase).toBe("visible");++ await advance(100);+ expect(currentPhase).toBe("hidden");+ });++ it("escalates to stalled after continuous loading, then hides immediately once loading ends", async () => {+ await show(true);+ await advance(150);+ expect(currentPhase).toBe("visible");++ await advance(8000);+ expect(currentPhase).toBe("stalled");++ // The minimum visible time has long passed, so deactivation hides without further delay.+ await show(false);+ await advance(0);+ expect(currentPhase).toBe("hidden");+ });+});diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 99c2fea552..78bfa7fecc 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -112,7 +112,7 @@ export function useEditorSpacedUpdate({ note, noteType, noteContext, getData, onupdateInterval?: number;}) {const parentComponent = useContext(ParentComponent);- const blob = useNoteBlob(note, parentComponent?.componentId);+ const blob = useNoteBlob(note, parentComponent?.componentId, { reportLoadStateTo: noteContext });// The note whose content is currently loaded in the editor. Editor instances are reused// across note switches, so until the new note's blob arrives the editor still holds the@@ -211,7 +211,7 @@ export function useBlobEditorSpacedUpdate({ note, noteType, noteContext, getDatareplaceWithoutRevision?: boolean;}) {const parentComponent = useContext(ParentComponent);- const blob = useNoteBlob(note, parentComponent?.componentId);+ const blob = useNoteBlob(note, parentComponent?.componentId, { reportLoadStateTo: noteContext });// Same provenance guard as useEditorSpacedUpdate: never save content under a note it// was not loaded from (#9614).@@ -752,17 +752,34 @@ export function useNoteLabelInt(note: FNote | undefined | null, labelName: Filte];}-export function useNoteBlob(note: FNote | null | undefined, componentId?: string): FBlob | null | undefined {+export function useNoteBlob(note: FNote | null | undefined, componentId?: string, opts?: {+ /** Publish the fetch progress as `contentLoad` context data on the given note context, so+ * the note detail can show a loading state instead of the previous note's content. Should+ * only be set by widgets whose main content display is gated on this blob. (Passed+ * explicitly because NoteContextContext is only provided in dialogs, not the main window.) */+ reportLoadStateTo?: NoteContext | null;+}): FBlob | null | undefined {const [ blob, setBlob ] = useState<FBlob | null>();const requestIdRef = useRef(0);+ function reportLoadState(state: "loading" | "loaded" | "error") {+ opts?.reportLoadStateTo?.setContextData("contentLoad", { state, retry: () => refresh() });+ }+async function refresh() {const requestId = ++requestIdRef.current;+ if (note) {+ reportLoadState("loading");+ }const newBlob = await note?.getBlob();// Only update if this is the latest request.if (requestId === requestIdRef.current) {setBlob(newBlob);+ if (note) {+ // froca.getBlob() resolves to null when the fetch failed.+ reportLoadState(newBlob ? "loaded" : "error");+ }}}@@ -1698,3 +1715,57 @@ export function useContainedLinkNavigation(return () => container.removeEventListener("click", onClick, true);}, [ containerRef, onNavigate ]);}++export type DelayedVisibilityPhase = "hidden" | "visible" | "stalled";++export interface DelayedVisibilityOpts {+ /** The indicator is never shown if `active` clears within this window (fast loads never flash). */+ graceMs?: number;+ /** Once shown, the indicator stays at least this long, even if `active` clears sooner (no two-frame flicker). */+ minVisibleMs?: number;+ /** After this much continuous activity the phase escalates to "stalled" so the UI can offer a retry. */+ stalledMs?: number;+}++/**+ * Drives a flicker-free loading indicator from a boolean "is loading" signal:+ *+ * - **grace period**: nothing is shown if loading finishes within {@link DelayedVisibilityOpts.graceMs},+ * so fast loads never flash a loading state;+ * - **minimum visibility**: once shown, the indicator stays for at least+ * {@link DelayedVisibilityOpts.minVisibleMs}, preventing a skeleton that appears for two frames;+ * - **escalation**: after {@link DelayedVisibilityOpts.stalledMs} of continuous loading the phase+ * becomes `"stalled"`, letting the UI switch to a "still loading / retry" presentation.+ */+export function useDelayedVisibility(active: boolean, { graceMs = 150, minVisibleMs = 280, stalledMs = 8000 }: DelayedVisibilityOpts = {}): DelayedVisibilityPhase {+ const [ phase, setPhase ] = useState<DelayedVisibilityPhase>("hidden");+ const shownAtRef = useRef(0);++ useEffect(() => {+ if (active) {+ if (phase === "hidden") {+ const graceTimer = setTimeout(() => {+ shownAtRef.current = Date.now();+ setPhase("visible");+ }, graceMs);+ return () => clearTimeout(graceTimer);+ }++ if (phase === "visible") {+ const stalledTimer = setTimeout(+ () => setPhase("stalled"),+ Math.max(0, shownAtRef.current + stalledMs - Date.now())+ );+ return () => clearTimeout(stalledTimer);+ }+ } else if (phase !== "hidden") {+ const hideTimer = setTimeout(+ () => setPhase("hidden"),+ Math.max(0, shownAtRef.current + minVisibleMs - Date.now())+ );+ return () => clearTimeout(hideTimer);+ }+ }, [ active, phase, graceMs, minVisibleMs, stalledMs ]);++ return phase;+}diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex b27ed58f4d..05a19e0f48 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -22,7 +22,7 @@ import { applyReferenceLinks } from "./read_only_helper";import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";export default function ReadOnlyText({ note, noteContext, ntxId }: TypeWidgetProps) {- const blob = useNoteBlob(note);+ const blob = useNoteBlob(note, undefined, { reportLoadStateTo: noteContext });const { isRtl } = useNoteLanguage(note);const readOnlyContentRef = usePreactRef<HTMLDivElement>(null);