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): drive the splash bar from weighted startup phases
Claude0539532df22a
diff --git a/apps/client/index.html b/apps/client/index.htmlindex 943f9f4d43..426f62057b 100644--- a/apps/client/index.html+++ b/apps/client/index.html@@ -49,7 +49,7 @@color: #333333;}#splash .splash-bar {- width: 176px;+ width: 240px;height: 3px;margin-top: 24px;border-radius: 2px;@@ -63,6 +63,32 @@background: #72b755;animation: splash-slide 1.4s ease-in-out infinite;}+ /* Segmented state, installed by splash.ts once the startup phases are known: one+ segment per phase, each as wide as that phase is expensive. */+ #splash .splash-bar.is-segmented {+ display: flex;+ gap: 2px;+ background: none;+ overflow: visible;+ }+ #splash .splash-bar.is-segmented .splash-bar-fill {+ display: none;+ }+ #splash .splash-seg {+ flex-basis: 0;+ height: 100%;+ border-radius: 2px;+ background: rgba(128, 128, 128, 0.2);+ transition: background-color 0.3s ease;+ }+ #splash .splash-seg.is-done {+ background: #72b755;+ }+ #splash .splash-seg.is-active {+ background: linear-gradient(90deg, rgba(114, 183, 85, 0.25) 0%, #72b755 50%, rgba(114, 183, 85, 0.25) 100%);+ background-size: 250% 100%;+ animation: splash-seg-sweep 1.2s ease-in-out infinite;+ }#splash-status {min-height: 1.5em;margin-top: 12px;@@ -87,6 +113,10 @@0%, 100% { opacity: 0.3; }50% { opacity: 1; }}+ @keyframes splash-seg-sweep {+ 0% { background-position: 100% 0; }+ 100% { background-position: 0 0; }+ }@media (prefers-color-scheme: dark) {#splash { background: #242424; color: #999999; }#splash .splash-title { color: #cccccc; }@@ -94,6 +124,7 @@@media (prefers-reduced-motion: reduce) {#splash .splash-content { opacity: 1; animation: none; }#splash .splash-bar-fill { width: 100%; animation: splash-pulse 1.8s ease-in-out infinite; }+ #splash .splash-seg.is-active { background: rgba(114, 183, 85, 0.55); animation: none; }}@media print {#splash { display: none; }diff --git a/apps/client/src/index.ts b/apps/client/src/index.tsindex 9d0df69a9b..d4af94102c 100644--- a/apps/client/src/index.ts+++ b/apps/client/src/index.ts@@ -1,11 +1,14 @@import { createFontStylesheetLink } from "./services/font";-import { hideSplash, showSplashError, updateSplashStatus } from "./services/splash";+import {+ CLIENT_STARTUP_PHASES, hideSplash, initSplashProgress, reportSplashPhase, showSplashError+} from "./services/splash";import { buildThemeStylesheetRefs, createStylesheetLink, getThemeStyle, initThemeChangeNotifier, StylesheetRef } from "./services/theme";async function bootstrap() {- // The splash from index.html covers the page until hideSplash(). In standalone mode this- // fetch waits for the SQLite worker to open the database, which can take a while.- updateSplashStatus("Opening your notes…");+ // The splash from index.html covers the page until hideSplash(). Standalone reports a longer+ // sequence of its own before this one, so these phases only take effect on server and desktop.+ initSplashProgress(CLIENT_STARTUP_PHASES);+ reportSplashPhase("bootstrap");await setupGlob();await Promise.all([initJQuery(),@@ -15,7 +18,7 @@ async function bootstrap() {initThemeChangeNotifier();loadIcons();setBodyAttributes();- updateSplashStatus("Loading the application…");+ reportSplashPhase("application");await loadScripts();hideSplash();}diff --git a/apps/client/src/services/splash.spec.ts b/apps/client/src/services/splash.spec.tsindex bebb7fb179..37d267c18d 100644--- a/apps/client/src/services/splash.spec.ts+++ b/apps/client/src/services/splash.spec.ts@@ -1,17 +1,37 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { hideSplash, showSplashError, updateSplashStatus } from "./splash";+import type { SplashPhase } from "./splash";++const PHASES: SplashPhase[] = [+ { id: "first", weight: 1, status: "First…" },+ { id: "second", weight: 3, status: "Second…" },+ { id: "third", weight: 2, status: "Third…" }+];++/** The module tracks the reported phase, so each test needs a fresh copy of it. */+async function freshSplash(): Promise<typeof import("./splash")> {+ vi.resetModules();+ return import("./splash");+}function renderSplash() {document.body.innerHTML = `<div id="splash">- <div class="splash-bar"></div>+ <div class="splash-bar"><div class="splash-bar-fill"></div></div><div id="splash-status"></div></div>`;}+function segmentClasses() {+ return [ ...document.querySelectorAll(".splash-seg") ].map((seg) => ({+ done: seg.classList.contains("is-done"),+ active: seg.classList.contains("is-active")+ }));+}+beforeEach(() => {vi.useFakeTimers();+ renderSplash();});afterEach(() => {@@ -20,8 +40,8 @@ afterEach(() => {});describe("splash", () => {- it("updates the status line and switches to the error state", () => {- renderSplash();+ it("updates the status line and switches to the error state", async () => {+ const { updateSplashStatus, showSplashError } = await freshSplash();updateSplashStatus("Opening your notes…");expect(document.getElementById("splash-status")?.textContent).toBe("Opening your notes…");@@ -31,19 +51,75 @@ describe("splash", () => {expect(document.getElementById("splash-status")?.textContent).toBe("something broke");});- it("fades the splash out and removes it once the transition has run", () => {- renderSplash();+ it("draws one segment per phase, sized by weight", async () => {+ const { initSplashProgress } = await freshSplash();+ initSplashProgress(PHASES);++ const bar = document.querySelector(".splash-bar");+ expect(bar?.classList.contains("is-segmented")).toBe(true);++ const segments = [ ...document.querySelectorAll<HTMLElement>(".splash-seg") ];+ expect(segments.map((seg) => seg.style.flexGrow)).toEqual([ "1", "3", "2" ]);+ });++ it("keeps the sequence the first caller installed", async () => {+ const { initSplashProgress, reportSplashPhase } = await freshSplash();+ initSplashProgress(PHASES);+ // Standalone claims the bar before the client's own, shorter list is offered.+ initSplashProgress([ { id: "other", weight: 1, status: "Other…" } ]);++ expect(document.querySelectorAll(".splash-seg")).toHaveLength(3);+ reportSplashPhase("other");+ expect(document.getElementById("splash-status")?.textContent).toBe("");+ });++ it("marks earlier phases done, the reported one active, and shows its status", async () => {+ const { initSplashProgress, reportSplashPhase } = await freshSplash();+ initSplashProgress(PHASES);++ reportSplashPhase("second");+ expect(segmentClasses()).toEqual([+ { done: true, active: false },+ { done: false, active: true },+ { done: false, active: false }+ ]);+ expect(document.getElementById("splash-status")?.textContent).toBe("Second…");+ });++ it("never moves backwards, and ignores an unknown phase", async () => {+ const { initSplashProgress, reportSplashPhase } = await freshSplash();+ initSplashProgress(PHASES);++ reportSplashPhase("third");+ // A phase reported late — or, in a follower tab, out of order — must not undo progress.+ reportSplashPhase("first");+ reportSplashPhase("nonexistent");+ expect(document.getElementById("splash-status")?.textContent).toBe("Third…");+ expect(segmentClasses()[2]).toEqual({ done: false, active: true });+ });++ it("fills the bar, then fades the splash out and removes it", async () => {+ const { initSplashProgress, reportSplashPhase, hideSplash } = await freshSplash();+ initSplashProgress(PHASES);+ reportSplashPhase("second");hideSplash();- const splash = document.getElementById("splash");- expect(splash?.classList.contains("splash-hidden")).toBe(true);+ expect(segmentClasses().every((seg) => seg.done && !seg.active)).toBe(true);+ expect(document.getElementById("splash")?.classList.contains("splash-hidden")).toBe(true);vi.runAllTimers();expect(document.getElementById("splash")).toBeNull();});- it("does nothing when the splash is not in the document", () => {+ it("does nothing when the splash is not in the document", async () => {+ const {+ initSplashProgress, reportSplashPhase, updateSplashStatus, showSplashError, hideSplash+ } = await freshSplash();+ document.body.innerHTML = "";+expect(() => {+ initSplashProgress(PHASES);+ reportSplashPhase("first");updateSplashStatus("status");showSplashError("error");hideSplash();diff --git a/apps/client/src/services/splash.ts b/apps/client/src/services/splash.tsindex 6bce3ba02d..be25fb4a55 100644--- a/apps/client/src/services/splash.ts+++ b/apps/client/src/services/splash.ts@@ -2,7 +2,7 @@* Drives the startup splash screen that index.html renders inline, before any script or* stylesheet is fetched. Status strings are English-only, as in the standalone error overlay:* the splash runs while the backend that serves the translation catalogues is still starting,- * so no catalogue can be loaded yet.+ * so `initLocale()` has neither a locale nor an `assetPath` to fetch one with.** Kept free of imports: index.ts loads it before setupGlob() populates window.glob, which most* client modules read at module scope.@@ -11,6 +11,77 @@/** Matches the `#splash` opacity transition in index.html. */const SPLASH_FADE_MS = 400;+/** One step of the startup sequence, drawn as its own segment of the progress bar. */+export interface SplashPhase {+ /** Name {@link reportSplashPhase} uses to announce that the step has started. */+ id: string;+ /** Relative cost of the step, which sets how wide its segment is. */+ weight: number;+ /** Shown under the bar while the step runs. */+ status: string;+}++/**+ * What a server or desktop client passes through, where the backend is already running and only+ * the frontend has to start. Standalone reports a longer sequence of its own first — see+ * `STANDALONE_STARTUP_PHASES` in apps/standalone/src/main.ts.+ */+export const CLIENT_STARTUP_PHASES: SplashPhase[] = [+ { id: "bootstrap", weight: 1, status: "Opening your notes…" },+ { id: "application", weight: 2, status: "Loading the application…" }+];++let phases: SplashPhase[] = [];++/** Index of the phase now running. Every earlier phase is drawn as complete. */+let currentPhase = -1;++/**+ * Splits the progress bar into one segment per phase, each sized by its weight. The first caller+ * wins, so standalone's longer sequence survives the client's own call later in the same startup.+ */+export function initSplashProgress(startupPhases: SplashPhase[]): void {+ if (phases.length) {+ return;+ }+ phases = startupPhases;++ const bar = document.querySelector("#splash .splash-bar");+ if (!bar) {+ return;+ }++ bar.classList.add("is-segmented");+ for (const phase of phases) {+ const segment = document.createElement("div");+ segment.className = "splash-seg";+ // The one genuinely computed value here: a segment is as wide as its phase is costly.+ segment.style.flexGrow = String(phase.weight);+ bar.append(segment);+ }+}++/**+ * Advances the bar to the named phase and shows its status. Never moves backwards, so a phase+ * that is reported late — or, in a follower tab, not at all — cannot undo the progress shown.+ */+export function reportSplashPhase(id: string): void {+ const index = phases.findIndex((phase) => phase.id === id);+ const phase = phases[index];+ if (!phase || index <= currentPhase) {+ return;+ }+ currentPhase = index;++ const segments = document.querySelectorAll<HTMLElement>("#splash .splash-seg");+ for (const [ segmentIndex, segment ] of segments.entries()) {+ segment.classList.toggle("is-done", segmentIndex < index);+ segment.classList.toggle("is-active", segmentIndex === index);+ }++ updateSplashStatus(phase.status);+}+/** Replaces the status line under the progress bar. */export function updateSplashStatus(status: string): void {const statusEl = document.getElementById("splash-status");@@ -35,6 +106,14 @@ export function hideSplash(): void {if (!splashEl) {return;}++ // Fill the bar before it goes, so the last phase is not left mid-flight behind the fade.+ for (const segment of splashEl.querySelectorAll<HTMLElement>(".splash-seg")) {+ segment.classList.remove("is-active");+ segment.classList.add("is-done");+ }+splashEl.classList.add("splash-hidden");setTimeout(() => splashEl.remove(), SPLASH_FADE_MS);}+diff --git a/apps/standalone/src/index.html b/apps/standalone/src/index.htmlindex eedf279c59..0de1cbe0bb 100644--- a/apps/standalone/src/index.html+++ b/apps/standalone/src/index.html@@ -49,7 +49,7 @@color: #333333;}#splash .splash-bar {- width: 176px;+ width: 240px;height: 3px;margin-top: 24px;border-radius: 2px;@@ -63,6 +63,32 @@background: #72b755;animation: splash-slide 1.4s ease-in-out infinite;}+ /* Segmented state, installed by splash.ts once the startup phases are known: one+ segment per phase, each as wide as that phase is expensive. */+ #splash .splash-bar.is-segmented {+ display: flex;+ gap: 2px;+ background: none;+ overflow: visible;+ }+ #splash .splash-bar.is-segmented .splash-bar-fill {+ display: none;+ }+ #splash .splash-seg {+ flex-basis: 0;+ height: 100%;+ border-radius: 2px;+ background: rgba(128, 128, 128, 0.2);+ transition: background-color 0.3s ease;+ }+ #splash .splash-seg.is-done {+ background: #72b755;+ }+ #splash .splash-seg.is-active {+ background: linear-gradient(90deg, rgba(114, 183, 85, 0.25) 0%, #72b755 50%, rgba(114, 183, 85, 0.25) 100%);+ background-size: 250% 100%;+ animation: splash-seg-sweep 1.2s ease-in-out infinite;+ }#splash-status {min-height: 1.5em;margin-top: 12px;@@ -87,6 +113,10 @@0%, 100% { opacity: 0.3; }50% { opacity: 1; }}+ @keyframes splash-seg-sweep {+ 0% { background-position: 100% 0; }+ 100% { background-position: 0 0; }+ }@media (prefers-color-scheme: dark) {#splash { background: #242424; color: #999999; }#splash .splash-title { color: #cccccc; }@@ -94,6 +124,7 @@@media (prefers-reduced-motion: reduce) {#splash .splash-content { opacity: 1; animation: none; }#splash .splash-bar-fill { width: 100%; animation: splash-pulse 1.8s ease-in-out infinite; }+ #splash .splash-seg.is-active { background: rgba(114, 183, 85, 0.55); animation: none; }}@media print {#splash { display: none; }diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex 25b3ad9937..0f2d778f3e 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -61,6 +61,32 @@ afterEach(() => {vi.restoreAllMocks();});+describe("startup progress", () => {+ it("advances the splash as the worker reports its startup phases", async () => {+ document.body.innerHTML = `+ <div id="splash">+ <div class="splash-bar"></div>+ <div id="splash-status"></div>+ </div>`;+ const bridge = await freshBridge();+ const { initSplashProgress } = await import("../../client/src/services/splash.js");+ initSplashProgress([+ { id: "sqlite", weight: 1, status: "Loading the database engine…" },+ { id: "core", weight: 1, status: "Loading Trilium…" }+ ]);++ bridge.startLocalServerWorker();+ lastWorker().onmessage?.({ data: { type: "STARTUP_PROGRESS", phase: "core" } });++ expect(document.getElementById("splash-status")?.textContent).toBe("Loading Trilium…");+ const segments = [ ...document.querySelectorAll(".splash-seg") ];+ expect(segments[0]?.classList.contains("is-done")).toBe(true);+ expect(segments[1]?.classList.contains("is-active")).toBe(true);++ document.body.innerHTML = "";+ });+});+describe("startLocalServerWorker", () => {it("creates the worker once and sends an INIT message", async () => {const bridge = await freshBridge();diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex d50632713e..83a5e52a92 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -4,6 +4,7 @@ import type {StandaloneRestoreResult} from "@triliumnext/commons";+import { reportSplashPhase } from "../../client/src/services/splash.js";import { showErrorOverlay } from "./error-overlay.js";import { isLeader } from "./leader_election.js";import LocalServerWorker from "./local-server-worker?worker";@@ -303,6 +304,13 @@ export function startLocalServerWorker() {localWorker.onmessage = (event) => {const msg = event.data;+ // How far the worker has got through its own startup, which the splash draws as progress.+ // Only the leader tab has a worker, so only it sees these.+ if (msg?.type === "STARTUP_PROGRESS") {+ reportSplashPhase(msg.phase);+ return;+ }+// Restore progress and outcome, which travel on their own channel rather than as a response// to a request: the backup that started them never went through one.if (msg?.type === "RESTORE_PROGRESS") {diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 61914335c9..1cb8efd0c0 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -38,6 +38,15 @@ function reportEscapedError(label: string, message: string, stack?: string) {}}+/**+ * Tell the page which startup step the worker has reached, so the splash's progress bar can+ * advance. Import-free for the same reason as {@link reportEscapedError}: the first of these+ * fires before any module has loaded. Ids match `STANDALONE_STARTUP_PHASES` in main.ts.+ */+function reportStartupPhase(phase: string) {+ self.postMessage({ type: "STARTUP_PROGRESS", phase });+}+self.onerror = (message, source, lineno, colno, error) => {reportEscapedError("Uncaught error",@@ -228,6 +237,7 @@ async function initialize(): Promise<void> {await logService.initialize();logService.info("[Worker] Log service initialized with OPFS");+ reportStartupPhase("sqlite");logService.info("[Worker] Initializing SQLite WASM...");await sqlProvider!.initWasm();@@ -247,6 +257,7 @@ async function initialize(): Promise<void> {// Which pool entry holds the database is a stored answer rather than a constant: a// restore cannot rename an entry, so it writes the new database in beside the old one// and changes this. Unrestored instances read the name they have always used.+ reportStartupPhase("database");const { readCurrentDatabaseName } = await import('./lightweight/database_restore.js');const dbName = await readCurrentDatabaseName();@@ -277,6 +288,7 @@ async function initialize(): Promise<void> {removeBackupLeftovers(backupPool);}+ reportStartupPhase("core");logService.info("[Worker] Loading @triliumnext/core...");const schemaModule = await import("@triliumnext/core/src/assets/schema.sql?raw");coreModule = await import("@triliumnext/core");@@ -345,6 +357,7 @@ async function initialize(): Promise<void> {coreModule.sql_init.initializeDb();if (coreModule.sql_init.isDbInitialized()) {+ reportStartupPhase("becca");logService.info("[Worker] Database already initialized, loading becca...");await coreModule.becca_loader.beccaLoaded;@@ -578,6 +591,7 @@ self.onmessage = async (event) => {if (!initReceived) {initReceived = true;console.log("[Worker] Starting initialization...");+ reportStartupPhase("worker-modules");initialize().catch(err => {console.error("[Worker] Initialization failed:", err);self.postMessage({diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.tsindex fccf2955a0..19a444d0ad 100644--- a/apps/standalone/src/main.spec.ts+++ b/apps/standalone/src/main.spec.ts@@ -118,7 +118,11 @@ describe("bootstrap", () => {});it("reports progress on the splash while the SW installs", async () => {- document.body.innerHTML = `<div id="splash"><div id="splash-status"></div></div>`;+ document.body.innerHTML = `+ <div id="splash">+ <div class="splash-bar"></div>+ <div id="splash-status"></div>+ </div>`;const sw: ServiceWorkerLike = {controller: null, register: vi.fn(), ready: Promise.resolve()};@@ -128,6 +132,10 @@ describe("bootstrap", () => {await vi.waitFor(() => expect(sw.register).toHaveBeenCalled());expect(document.getElementById("splash-status")?.textContent).toBe("Setting up offline support…");+ // One segment per startup phase, the first of them active.+ const segments = [ ...document.querySelectorAll(".splash-seg") ];+ expect(segments).toHaveLength(8);+ expect(segments[0]?.classList.contains("is-active")).toBe(true);});it("reloads the page when the SW installs but does not take control", async () => {diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.tsindex 1ac24f4891..1ae4e6a8a6 100644--- a/apps/standalone/src/main.ts+++ b/apps/standalone/src/main.ts@@ -1,9 +1,31 @@-import { updateSplashStatus } from "../../client/src/services/splash.js";+import {+ initSplashProgress, reportSplashPhase, type SplashPhase+} from "../../client/src/services/splash.js";import { showErrorOverlay } from "./error-overlay.js";import { installIosInterceptors } from "./ios-interceptors.js";import { claimLeadership } from "./leader_election.js";import { announceLeadership, attachServiceWorkerBridge, downloadDatabase, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";+/**+ * What a cold standalone start passes through, drawn as the splash's progress bar. Weights are+ * the relative cost of each step on a first visit, where the two large downloads — the SQLite+ * WASM binary and the core bundle — dominate; a warm start runs the same sequence from cache.+ *+ * The worker reports the middle of this sequence over `STARTUP_PROGRESS` (see local-bridge.ts).+ * A follower tab has no worker of its own, so it sits on the first phase until the leader answers+ * its `/bootstrap` and the client's own phases carry the bar the rest of the way.+ */+const STANDALONE_STARTUP_PHASES: SplashPhase[] = [+ { id: "service-worker", weight: 1, status: "Setting up offline support…" },+ { id: "worker-modules", weight: 1, status: "Starting the database engine…" },+ { id: "sqlite", weight: 3, status: "Loading the database engine…" },+ { id: "database", weight: 2, status: "Opening the database…" },+ { id: "core", weight: 4, status: "Loading Trilium…" },+ { id: "becca", weight: 2, status: "Reading your notes…" },+ { id: "bootstrap", weight: 1, status: "Preparing the workspace…" },+ { id: "application", weight: 4, status: "Loading the application…" }+];+async function waitForServiceWorkerControl(): Promise<void> {if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {const isSecure = location.protocol === "https:" || location.hostname === "localhost" || location.hostname === "127.0.0.1";@@ -28,7 +50,7 @@ async function waitForServiceWorkerControl(): Promise<void> {}console.log("[Bootstrap] Waiting for service worker to take control...");- updateSplashStatus("Setting up offline support…");+ reportSplashPhase("service-worker");await navigator.serviceWorker.register("./sw.js", { scope: "/" });await navigator.serviceWorker.ready;@@ -48,6 +70,10 @@ async function bootstrap() {/* fixes https://github.com/webpack/webpack/issues/10035 */window.global = globalThis;+ // Claimed before the client loads, so standalone's longer sequence is the one the bar shows+ // rather than the two client-side phases index.ts would otherwise install.+ initSplashProgress(STANDALONE_STARTUP_PHASES);+// The client's way to the worker for the few things that carry a file, which the request path// would serialise whole and time out on. The desktop's `window.electronApi` is the same idea.window.standaloneApi = {