Skip to content

Build your personal knowledge base with Trilium Notes

client/backup import: tweak UI

Adorian Doranfb40a412de37
diff --git a/apps/client/src/services/database_files.ts b/apps/client/src/services/database_files.ts
index 440d76009b..f296342c81 100644
--- a/apps/client/src/services/database_files.ts
+++ b/apps/client/src/services/database_files.ts
@@ -25,6 +25,26 @@ export interface DatabaseFile {
* Shared by every list of these files — the backups in the options, the backups the setup screen
* offers to restore from — so that one line reads the same wherever it appears.
*/
+/**
+ * What a backup was written as, as short labels: compressed, encrypted, or neither.
+ *
+ * Read from the file's own header rather than from today's settings, so it describes the backup as
+ * it is. Shared by every list of these files, so that the same file is described the same way
+ * wherever it is shown.
+ */
+export function describeDatabaseFormat(file: { compressed?: boolean; encrypted?: boolean }): string[] {
+ const badges: string[] = [];
+
+ if (file.compressed) {
+ badges.push(t("backup.compressed"));
+ }
+ if (file.encrypted) {
+ badges.push(t("backup.encrypted"));
+ }
+
+ return badges;
+}
+
export function describeDatabaseFile(file: DatabaseFile): string {
const parts = [ file.mtime ? formatDateTime(file.mtime) : "-" ];
diff --git a/apps/client/src/setup.css b/apps/client/src/setup.css
index e31b65dcb1..cdd65c7ae0 100644
--- a/apps/client/src/setup.css
+++ b/apps/client/src/setup.css
@@ -57,7 +57,7 @@ body.setup {
}
.setup-option-card {
- padding: 1.5em;
+ padding: .75em 1.5em;
cursor: pointer;
display: flex;
align-items: center;
@@ -82,16 +82,18 @@ body.setup {
}
h3 {
+ margin-bottom: 4px;
font-size: 1.15em;
font-weight: normal;
body.desktop & {
- font-size: 1.5em;
+ font-size: 1.3em;
}
}
p:last-of-type {
margin-bottom: 0;
+ font-size: .85em;
color: var(--muted-text-color);
}
}
@@ -348,52 +350,6 @@ body.setup .bx-spin {
}
/* Slide transitions */
-.slide-page {
- position: absolute;
- inset: 0;
-}
-
-.slide-out-forward,
-.slide-out-backward,
-.slide-in-forward,
-.slide-in-backward {
- animation-duration: 0.35s;
- animation-timing-function: ease-in-out;
- animation-fill-mode: forwards;
-}
-
-.slide-out-forward {
- animation-name: slide-out-left;
-}
-
-.slide-out-backward {
- animation-name: slide-out-right;
-}
-
-.slide-in-forward {
- animation-name: slide-in-right;
-}
-
-.slide-in-backward {
- animation-name: slide-in-left;
-}
-
-body[dir=rtl] .slide-out-forward {
- animation-name: slide-out-right;
-}
-
-body[dir=rtl] .slide-out-backward {
- animation-name: slide-out-left;
-}
-
-body[dir=rtl] .slide-in-forward {
- animation-name: slide-in-left;
-}
-
-body[dir=rtl] .slide-in-backward {
- animation-name: slide-in-right;
-}
-
.page.select-language {
main {
min-height: 0;
@@ -519,23 +475,3 @@ body[dir=rtl] .slide-in-backward {
font-size: 0.9em;
}
}
-
-@keyframes slide-out-left {
- from { transform: translateX(0); opacity: 1; }
- to { transform: translateX(-100%); opacity: 0; }
-}
-
-@keyframes slide-out-right {
- from { transform: translateX(0); opacity: 1; }
- to { transform: translateX(100%); opacity: 0; }
-}
-
-@keyframes slide-in-right {
- from { transform: translateX(100%); opacity: 0; }
- to { transform: translateX(0); opacity: 1; }
-}
-
-@keyframes slide-in-left {
- from { transform: translateX(-100%); opacity: 0; }
- to { transform: translateX(0); opacity: 1; }
-}
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index cdd55ce95c..24fce7b3ba 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -19,6 +19,7 @@ import { FormListItem } from "./widgets/react/FormList";
import FormTextBox from "./widgets/react/FormTextBox";
import Icon from "./widgets/react/Icon";
import SetupPage from "./widgets/react/SetupPage";
+import SlidePages from "./widgets/react/SlidePages";
async function main() {
await initLocale();
@@ -65,9 +66,6 @@ function App() {
// resumes straight on the progress screen instead of restarting the wizard.
const resuming = window.glob.syncInProgress === true;
const [state, setState] = useState<State>(resuming ? "syncFromServerInProgress" : "selectLanguage");
- const [prevState, setPrevState] = useState<State | null>(null);
- const [transitioning, setTransitioning] = useState(false);
- const prevStateRef = useRef<State>(state);
useEffect(() => {
if (!resuming) {
@@ -81,34 +79,13 @@ function App() {
});
}, [resuming]);
- function handleSetState(newState: State) {
- setPrevState(prevStateRef.current);
- prevStateRef.current = newState;
- setTransitioning(true);
- setState(newState);
- }
-
- const direction = prevState !== null
- ? STATE_ORDER.indexOf(state) > STATE_ORDER.indexOf(prevState) ? "forward" : "backward"
- : "forward";
-
return (
<div class="setup-container">
<div class="drag-region" />
- {transitioning && prevState !== null && (
- <div
- class={`slide-page slide-out-${direction}`}
- onAnimationEnd={() => {
- setTransitioning(false);
- setPrevState(null);
- }}
- >
- {renderState(prevState, handleSetState)}
- </div>
- )}
- <div class={`slide-page ${transitioning ? `slide-in-${direction}` : "slide-current"}`} key={state}>
- {renderState(state, handleSetState)}
- </div>
+
+ <SlidePages current={state} order={STATE_ORDER}>
+ {(page) => renderState(page, setState)}
+ </SlidePages>
</div>
);
}
diff --git a/apps/client/src/setup_restore.css b/apps/client/src/setup_restore.css
index 9746a0db61..519329900c 100644
--- a/apps/client/src/setup_restore.css
+++ b/apps/client/src/setup_restore.css
@@ -21,18 +21,35 @@
gap: 0.75em;
cursor: pointer;
+ /* The leading icon only: the chevron at the other end stays the size of the text. */
+ > .tn-icon:first-child {
+ font-size: 2em;
+ }
+
> .bx-chevron-right {
margin-left: auto;
opacity: 0.5;
}
}
+ /* Set apart from the backups below it: the same kind of row, but not one of them. */
+ .tn-card:has(.restore-choose-file) {
+ margin-bottom: 12px;
+ }
+
.restore-backup-details {
display: flex;
flex-direction: column;
min-width: 0;
}
+ .restore-backup-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ }
+
.restore-backup-name {
overflow: hidden;
text-overflow: ellipsis;
@@ -51,23 +68,15 @@
opacity: 0.7;
}
- .restore-file-section {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- gap: 0.75em;
-
- p {
- margin: 0;
- opacity: 0.7;
- }
- }
-
- /* Driven by the button next to it, which is the only thing the user should be aiming at. */
+ /* Driven by the row above it, which is the only thing the user should be aiming at. */
.restore-file-input {
display: none;
}
+ .restore-passphrase input {
+ margin-block: 8px;
+ }
+
.restore-passphrase-actions {
display: flex;
justify-content: flex-end;
@@ -87,48 +96,54 @@
}
.restore-progress-detail {
+ display: flex;
+ gap: 1em;
margin-top: 0.35em;
font-size: 0.85em;
opacity: 0.7;
+
+ /* Pushed over rather than spaced apart, so how much has gone stays on the left whether
+ or not there is a rate to put opposite it. */
+ .restore-upload-speed {
+ margin-inline-start: auto;
+ font-variant-numeric: tabular-nums;
+ }
}
}
- .restore-stages .tn-card-section {
+ .restore-current-step {
display: flex;
+ flex-direction: column;
align-items: center;
- gap: 0.5em;
- opacity: 0.5;
- transition: opacity 150ms ease;
+ gap: 0.75em;
+ text-align: center;
+ }
- &.active,
- &.completed {
- opacity: 1;
- }
+ .restore-step-name {
+ font-size: 1.1em;
}
- /* Takes the rest of the row, so the bar does not depend on how long the step is named. */
.restore-stage-progress {
display: flex;
- flex: 1;
align-items: center;
- gap: 0.5em;
- margin-left: auto;
+ gap: 0.75em;
+ /* Wide enough to read as a measure of the whole step, whatever the step is called, and
+ never wider than the page it is centred on. */
+ width: min(100%, 27.5em);
progress {
flex: 1;
- min-width: 4em;
}
span {
min-width: 3em;
- font-size: 0.85em;
font-variant-numeric: tabular-nums;
text-align: right;
opacity: 0.7;
}
}
- .restore-banner {
- margin-top: 1em;
+ .restore-do-not-close {
+ opacity: 0.6;
}
}
diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsx
index 4a846d818b..03b8a6edb2 100644
--- a/apps/client/src/setup_restore.spec.tsx
+++ b/apps/client/src/setup_restore.spec.tsx
@@ -1,8 +1,11 @@
import { render } from "preact";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-// t() returns the key so assertions are deterministic and not tied to English text.
-vi.mock("./services/i18n", () => ({ t: (key: string) => key }));
+// t() returns the key so assertions are deterministic and not tied to English text, with any
+// interpolated values after it: those are ours to get right, unlike the sentence around them.
+vi.mock("./services/i18n", () => ({
+ t: (key: string, values?: Record<string, unknown>) => [ key, ...Object.values(values ?? {}) ].join(" ")
+}));
const serverMock = vi.hoisted(() => ({
// The default serves what transitively imported modules ask for as they load (keyboard_actions
@@ -19,7 +22,7 @@ import RestoreFromBackup from "./setup_restore";
const BACKUPS = [
{ fileName: "backup-daily.db", filePath: "/data/backup/backup-daily.db", mtime: "2026-08-01T10:00:00Z", fileSize: 2048, encrypted: false },
- { fileName: "backup-weekly.tnbackup", filePath: "/data/backup/backup-weekly.tnbackup", mtime: "2026-08-05T10:00:00Z", fileSize: 1024, encrypted: true }
+ { fileName: "backup-weekly.tnbackup", filePath: "/data/backup/backup-weekly.tnbackup", mtime: "2026-08-05T10:00:00Z", fileSize: 1024, compressed: true, encrypted: true }
];
let container: HTMLDivElement;
@@ -42,6 +45,8 @@ function backupRow(name: string) {
.find((row) => row.textContent?.includes(name));
}
+const goBack = () => container.querySelector<HTMLElement>(".back-button")?.click();
+
beforeEach(() => {
vi.useFakeTimers();
restore = null;
@@ -65,11 +70,24 @@ afterEach(() => {
});
describe("picking a backup", () => {
+ it("says what a backup was written as, in the same words the options use", async () => {
+ renderRestore();
+ await flushEffects();
+
+ const encrypted = backupRow("backup-weekly.tnbackup");
+ expect([ ...(encrypted?.querySelectorAll(".database-file-badge") ?? []) ].map((b) => b.textContent))
+ .toEqual([ "backup.compressed", "backup.encrypted" ]);
+ // Nothing to say about a plain copy, so nothing is said.
+ expect(backupRow("backup-daily.db")?.querySelectorAll(".database-file-badge")).toHaveLength(0);
+ });
+
it("lists what is on the device, newest first, and starts restoring the one that is picked", async () => {
renderRestore();
await flushEffects();
- const names = [ ...container.querySelectorAll(".restore-backup-name") ].map((row) => row.textContent);
+ // Everything but the row that opens a file, which is the same kind of row without being a backup.
+ const names = [ ...container.querySelectorAll(".restore-backup-row:not(.restore-choose-file) .restore-backup-name") ]
+ .map((row) => row.textContent);
expect(names).toEqual([ "backup-weekly.tnbackup", "backup-daily.db" ]);
backupRow("backup-daily.db")?.click();
@@ -80,7 +98,7 @@ describe("picking a backup", () => {
filePath: "/data/backup/backup-daily.db",
passphrase: undefined
});
- expect(container.querySelector(".restore-stages")).toBeTruthy();
+ expect(container.querySelector(".restore-current-step")).toBeTruthy();
});
it("asks for the password first when the backup is encrypted, and sends it with the restore", async () => {
@@ -115,8 +133,108 @@ describe("picking a backup", () => {
renderRestore();
await flushEffects();
+ expect(container.querySelector(".restore-choose-file")).toBeTruthy();
expect(container.querySelector(".restore-file-input")).toBeTruthy();
- expect(container.textContent).toContain("setup.restore-no-backups");
+ });
+
+ it("says nothing about existing backups when there are none, rather than an empty card", async () => {
+ serverMock.get.mockImplementation(async (url: string) =>
+ (url === "database/backups" ? { backups: [], backupFolderPath: "/data/backup" } : []));
+
+ renderRestore();
+ await flushEffects();
+
+ expect(container.textContent).not.toContain("setup.restore-existing-backups");
+ // A device being set up for the first time usually has none, and the way in still has to be there.
+ expect(container.querySelector(".restore-choose-file")).toBeTruthy();
+ });
+
+ it("says it is looking while it does not yet know", async () => {
+ let listBackups: (value: unknown) => void = () => {};
+ serverMock.get.mockImplementation(async (url: string) =>
+ (url === "database/backups" ? new Promise((resolve) => { listBackups = resolve; }) : []));
+
+ renderRestore();
+ await flushEffects();
+
+ expect(container.querySelector(".restore-loading")).toBeTruthy();
+
+ listBackups({ backups: BACKUPS, backupFolderPath: "/data/backup" });
+ await flushEffects();
+
+ expect(container.querySelector(".restore-loading")).toBeFalsy();
+ expect(container.querySelectorAll(".restore-backup-row:not(.restore-choose-file)")).toHaveLength(2);
+ });
+});
+
+describe("going back", () => {
+ it("leaves the restore altogether from the first step, since there is nothing before it", async () => {
+ const onBack = vi.fn();
+ renderRestore({ onBack });
+ await flushEffects();
+
+ goBack();
+
+ expect(onBack).toHaveBeenCalled();
+ });
+
+ it("returns to the backups from the password prompt, rather than out of the flow", async () => {
+ const onBack = vi.fn();
+ renderRestore({ onBack });
+ await flushEffects();
+ backupRow("backup-weekly.tnbackup")?.click();
+ await flushEffects();
+ expect(container.querySelector("input[type=password]")).toBeTruthy();
+
+ goBack();
+ await flushEffects();
+
+ expect(onBack).not.toHaveBeenCalled();
+ expect(container.querySelector(".restore-choose-file")).toBeTruthy();
+ });
+
+ it("carries no stale wrong-password warning back into the next attempt", async () => {
+ renderRestore();
+ await flushEffects();
+ backupRow("backup-weekly.tnbackup")?.click();
+ await flushEffects();
+
+ // The server refuses the password, which puts the prompt back with a warning on it.
+ restore = { stage: "failed", reason: "wrong-passphrase-or-damaged-header", error: "Verifier tag did not match." };
+ container.querySelector("input[type=password]")?.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextPoll();
+
+ goBack();
+ await flushEffects();
+ backupRow("backup-weekly.tnbackup")?.click();
+ await flushEffects();
+
+ expect(container.textContent).not.toContain("setup.restore-wrong-passphrase");
+ });
+
+ it("stops an upload it walks away from, and says nothing about it", async () => {
+ let uploadSignal: AbortSignal | undefined;
+ uploadMock.uploadInChunks.mockImplementation(async ({ signal }: { signal: AbortSignal }) => {
+ uploadSignal = signal;
+
+ // Never settles on its own: only the abort can end it, which is the point.
+ return new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(signal.reason)));
+ });
+ renderRestore();
+ await flushEffects();
+
+ const input = container.querySelector<HTMLInputElement>(".restore-file-input");
+ Object.defineProperty(input, "files", { value: [ new File([ "bytes" ], "backup.db") ], configurable: true });
+ input?.dispatchEvent(new Event("change", { bubbles: true }));
+ await flushEffects();
+
+ goBack();
+ await flushEffects();
+
+ expect(uploadSignal?.aborted).toBe(true);
+ expect(container.querySelector(".restore-choose-file")).toBeTruthy();
+ // Cancelling is not a failure, so it is not reported as one.
+ expect(container.querySelector(".restore-error-headline")).toBeFalsy();
});
});
@@ -131,7 +249,7 @@ describe("uploading a backup", () => {
it("sends the file in chunks, shows how far it has got, and restores it once it is there", async () => {
uploadMock.uploadInChunks.mockImplementation(async ({ onProgress }: { onProgress: (p: unknown) => void }) => {
- onProgress({ sentBytes: 512, totalBytes: 1024, fraction: 0.5 });
+ onProgress({ sentBytes: 512, totalBytes: 1024, fraction: 0.5, bytesPerSecond: 0 });
return { fileName: "backup.db", encrypted: false };
});
renderRestore();
@@ -150,6 +268,33 @@ describe("uploading a backup", () => {
});
});
+ it("shows how much has gone and how fast, once there is a rate to report", async () => {
+ let report: (progress: unknown) => void = () => {};
+ uploadMock.uploadInChunks.mockImplementation(async ({ onProgress }: { onProgress: (p: unknown) => void }) => {
+ report = onProgress;
+ report({ sentBytes: 0, totalBytes: 4 * 1024 * 1024, fraction: 0, bytesPerSecond: 0 });
+
+ return new Promise(() => {});
+ });
+ renderRestore();
+ await flushEffects();
+
+ await chooseFile(new File([ "database bytes" ], "backup.db"));
+
+ // Nothing has gone out yet, so there is no rate to divide into anything.
+ expect(container.querySelector(".restore-upload-speed")).toBeFalsy();
+
+ report({ sentBytes: 1024 * 1024, totalBytes: 4 * 1024 * 1024, fraction: 0.25, bytesPerSecond: 512 * 1024 });
+ await flushEffects();
+
+ expect(container.querySelector(".restore-progress-detail")?.textContent)
+ .toContain("setup.restore-uploaded-so-far 1 MiB 4 MiB");
+ // Its own element, since it is pushed to the far side of the line rather than read on from
+ // what came before it.
+ expect(container.querySelector(".restore-upload-speed")?.textContent?.trim())
+ .toBe("setup.restore-upload-speed 512 KiB");
+ });
+
it("asks for the password when what arrived turns out to be encrypted", async () => {
uploadMock.uploadInChunks.mockResolvedValue({ fileName: "backup.tnbackup", encrypted: true });
renderRestore();
@@ -192,7 +337,7 @@ describe("choosing a backup on the desktop", () => {
// Nothing to upload: the file never leaves the disk it is already on.
expect(container.querySelector(".restore-file-input")).toBeFalsy();
- container.querySelector<HTMLElement>(".restore-file-section button")?.click();
+ container.querySelector<HTMLElement>(".restore-choose-file")?.click();
await flushEffects();
expect(uploadMock.uploadInChunks).not.toHaveBeenCalled();
@@ -208,7 +353,7 @@ describe("choosing a backup on the desktop", () => {
renderRestore();
await flushEffects();
- container.querySelector<HTMLElement>(".restore-file-section button")?.click();
+ container.querySelector<HTMLElement>(".restore-choose-file")?.click();
await flushEffects();
expect(serverMock.post).not.toHaveBeenCalled();
@@ -220,7 +365,7 @@ describe("choosing a backup on the desktop", () => {
renderRestore();
await flushEffects();
- container.querySelector<HTMLElement>(".restore-file-section button")?.click();
+ container.querySelector<HTMLElement>(".restore-choose-file")?.click();
await flushEffects();
expect(serverMock.post).not.toHaveBeenCalled();
@@ -232,7 +377,7 @@ describe("choosing a backup on the desktop", () => {
renderRestore();
await flushEffects();
- container.querySelector<HTMLElement>(".restore-file-section button")?.click();
+ container.querySelector<HTMLElement>(".restore-choose-file")?.click();
await flushEffects();
expect(container.querySelector(".restore-error-detail")?.textContent).toBe("setup is already busy with 'new-document'");
@@ -251,27 +396,27 @@ describe("following the restore", () => {
beforeEach(() => { onRestored = vi.fn(); });
- it("moves through the stages the server reports", async () => {
+ it("shows the step it is on, and only that one", async () => {
await startRestore();
restore = { stage: "validating" };
await nextPoll();
- const active = container.querySelector(".restore-stages .active");
- expect(active?.textContent).toContain("setup.restore-stage-validating");
+ expect(container.querySelector(".restore-step-name")?.textContent).toBe("setup.restore-stage-validating");
+ // The steps it is not on say nothing: they go by too quickly to be read, and listing them
+ // mostly shows the user things they will never see happen.
+ expect(container.textContent).not.toContain("setup.restore-stage-swapping");
});
- it("shows how far the running step has got, and only on that step", async () => {
+ it("shows how far the running step has got", async () => {
await startRestore();
restore = { stage: "staging", fraction: 0.42 };
await nextPoll();
- const bar = container.querySelector<HTMLProgressElement>(".restore-stages .active progress");
+ const bar = container.querySelector<HTMLProgressElement>(".restore-current-step progress");
expect(bar?.value).toBe(0.42);
- expect(container.querySelector(".restore-stages .active .restore-stage-progress")?.textContent).toContain("42%");
- // One bar, on the step that is running.
- expect(container.querySelectorAll(".restore-stages progress")).toHaveLength(1);
+ expect(container.querySelector(".restore-stage-progress")?.textContent).toContain("42%");
});
it("drops the bar for a step that cannot say how far it has got", async () => {
@@ -279,14 +424,14 @@ describe("following the restore", () => {
restore = { stage: "staging", fraction: 0.9 };
await nextPoll();
- expect(container.querySelector(".restore-stages progress")).toBeTruthy();
+ expect(container.querySelector(".restore-current-step progress")).toBeTruthy();
// Checking a database reads it from end to end with nothing to report along the way; the
// previous step's bar must not be left sitting under it.
restore = { stage: "validating" };
await nextPoll();
- expect(container.querySelector(".restore-stages progress")).toBeFalsy();
+ expect(container.querySelector(".restore-current-step progress")).toBeFalsy();
});
it("finishes setup once the restore is done", async () => {
@@ -304,7 +449,7 @@ describe("following the restore", () => {
serverMock.get.mockRejectedValueOnce(new Error("DB not open."));
await nextPoll();
- expect(container.querySelector(".restore-stages")).toBeTruthy();
+ expect(container.querySelector(".restore-current-step")).toBeTruthy();
restore = { stage: "done" };
await nextPoll();
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsx
index 4d19ebee29..4ee8b9529f 100644
--- a/apps/client/src/setup_restore.tsx
+++ b/apps/client/src/setup_restore.tsx
@@ -5,18 +5,18 @@ import type { ComponentChildren } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { uploadInChunks } from "./services/chunked_upload";
-import { describeDatabaseFile } from "./services/database_files";
+import { describeDatabaseFile, describeDatabaseFormat } from "./services/database_files";
import { t } from "./services/i18n";
import server from "./services/server";
import { formatSize } from "./services/utils";
-import Admonition from "./widgets/react/Admonition";
import Button from "./widgets/react/Button";
import { Card, CardSection } from "./widgets/react/Card";
+import DatabaseFileBadges from "./widgets/react/DatabaseFileBadges";
import FormGroup from "./widgets/react/FormGroup";
import FormTextBox from "./widgets/react/FormTextBox";
import Icon from "./widgets/react/Icon";
-import NoItems from "./widgets/react/NoItems";
import SetupPage from "./widgets/react/SetupPage";
+import SlidePages from "./widgets/react/SlidePages";
/**
* The setup screen's "restore from backup" path, from picking a backup to the restored database
@@ -32,6 +32,18 @@ import SetupPage from "./widgets/react/SetupPage";
/** What the restore is waiting on, as far as this screen is concerned. */
type Step = "picking" | "uploading" | "passphrase" | "restoring";
+/**
+ * Where "Back" goes from each step. A step with no entry here leaves the restore flow altogether,
+ * which is what the first one does and what any later step does if it has nothing to return to.
+ */
+const PREVIOUS_STEP: Partial<Record<Step, Step>> = {
+ uploading: "picking",
+ passphrase: "picking"
+};
+
+/** The steps in the order they are reached, which is what decides the way a slide goes. */
+const STEP_ORDER: Step[] = [ "picking", "uploading", "passphrase", "restoring" ];
+
/** Failures the same backup can still get past, which send the user back to the passphrase rather than to the start. */
const PASSPHRASE_FAILURES = new Set([ "passphrase-required", "wrong-passphrase-or-damaged-header" ]);
@@ -42,6 +54,20 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
const [ error, setError ] = useState<ComponentChildren>(null);
const [ errorId, setErrorId ] = useState(0);
const [ wrongPassphrase, setWrongPassphrase ] = useState(false);
+ /** Stops the upload in flight, for the one thing that can interrupt it: the user going back. */
+ const uploadCancellation = useRef<AbortController | null>(null);
+ /**
+ * Fetched here rather than by the step that lists them, which is mounted afresh every time it is
+ * returned to: asking again would show "looking for backups" for the length of each slide back.
+ */
+ const [ backups, setBackups ] = useState<DatabaseBackup[] | null>(null);
+
+ useEffect(() => {
+ server.get<ExistingBackupsResponse>("database/backups")
+ .then((response) => setBackups(response.backups))
+ // An unreadable backup directory is not a reason to lose the way in from a file.
+ .catch(() => setBackups([]));
+ }, []);
const raiseError = useCallback((headline: string, detail?: string) => {
setError(<Failure headline={headline} detail={detail} />);
@@ -71,21 +97,52 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
}, [ raiseError ]);
async function uploadAndRestore(file: File) {
+ const cancellation = new AbortController();
+ uploadCancellation.current = cancellation;
+
setStep("uploading");
- setUpload({ sentBytes: 0, totalBytes: file.size, fraction: 0 });
+ setUpload({ sentBytes: 0, totalBytes: file.size, fraction: 0, bytesPerSecond: 0 });
try {
const uploaded = await uploadInChunks<{ fileName: string; encrypted: boolean }>({
endpoint: "setup/restore/upload",
blob: file,
fileName: file.name,
- onProgress: ({ sentBytes, totalBytes, fraction }) => setUpload({ sentBytes, totalBytes, fraction })
+ signal: cancellation.signal,
+ onProgress: ({ sentBytes, totalBytes, fraction, bytesPerSecond }) =>
+ setUpload({ sentBytes, totalBytes, fraction, bytesPerSecond })
});
await restore({ source: "pending", fileName: uploaded.fileName, encrypted: uploaded.encrypted });
} catch (e) {
setStep("picking");
- raiseError(t("setup.restore-error-upload-failed"), detailOf(e));
+
+ // An upload the user walked away from ends in a failure they chose, and being told
+ // about it would read as something having gone wrong.
+ if (!cancellation.signal.aborted) {
+ raiseError(t("setup.restore-error-upload-failed"), detailOf(e));
+ }
+ } finally {
+ uploadCancellation.current = null;
+ }
+ }
+
+ /**
+ * Goes back a step, or out of the restore altogether from the step that has nothing before it.
+ *
+ * An upload in flight is stopped on the way: left running it would finish in the background and
+ * pull the user forward into the restore they had just walked away from.
+ */
+ function goBack() {
+ uploadCancellation.current?.abort();
+ // Belongs to the attempt being left behind, not to the next one.
+ setWrongPassphrase(false);
+
+ const previous = PREVIOUS_STEP[step];
+ if (previous) {
+ setStep(previous);
+ } else {
+ onBack();
}
}
@@ -109,23 +166,33 @@ export default function RestoreFromBackup({ onBack, onRestored }: { onBack: () =
illustration={<Icon icon="bx bx-archive-in" className="illustration-icon" />}
error={error}
errorId={errorId}
- onBack={step === "restoring" ? undefined : onBack}
+ // Nothing to go back to once the database is being replaced.
+ onBack={step === "restoring" ? undefined : goBack}
>
- {step === "picking" && <PickBackup onPick={restore} onUpload={uploadAndRestore} onFailure={raiseError} />}
- {step === "uploading" && upload && <UploadProgress upload={upload} />}
- {step === "passphrase" && selection && (
- <AskPassphrase
- fileName={selection.fileName}
- wrong={wrongPassphrase}
- onSubmit={(passphrase) => {
- setWrongPassphrase(false);
- void restore(selection, passphrase);
- }}
- />
- )}
- {step === "restoring" && (
- <RestoreProgress onRestored={onRestored} onFailed={onRestoreFailed} />
- )}
+ {/* In the flow rather than filling the page: each step is a different height, and the
+ one arriving is what the page should be as tall as. */}
+ <SlidePages current={step} order={STEP_ORDER} inFlow>
+ {(shown) => (
+ <>
+ {shown === "picking" && (
+ <PickBackup backups={backups} onPick={restore} onUpload={uploadAndRestore} onFailure={raiseError} />
+ )}
+ {shown === "uploading" && upload && <UploadProgress upload={upload} />}
+ {shown === "passphrase" && selection && (
+ <AskPassphrase
+ wrong={wrongPassphrase}
+ onSubmit={(passphrase) => {
+ setWrongPassphrase(false);
+ void restore(selection, passphrase);
+ }}
+ />
+ )}
+ {shown === "restoring" && (
+ <RestoreProgress onRestored={onRestored} onFailed={onRestoreFailed} />
+ )}
+ </>
+ )}
+ </SlidePages>
</SetupPage>
);
}
@@ -188,15 +255,18 @@ interface UploadState {
sentBytes: number;
totalBytes: number;
fraction: number;
+ /** Averaged over the transfer so far, so it settles rather than jumping about between pieces. */
+ bytesPerSecond: number;
}
-/** The backups already on this device, and the way to a file that is not. */
-function PickBackup({ onPick, onUpload, onFailure }: {
+/** The backups already here, and the way to a file that is not. */
+function PickBackup({ backups, onPick, onUpload, onFailure }: {
+ /** What was found, or `null` while that is still being asked. */
+ backups: DatabaseBackup[] | null;
onPick: (selection: Selection) => void;
onUpload: (file: File) => void;
onFailure: (headline: string, detail?: string) => void;
}) {
- const [ backups, setBackups ] = useState<DatabaseBackup[] | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
// The desktop can read the file where it lies; a browser has to be handed it first.
const nativePicker = window.electronApi?.restore;
@@ -215,24 +285,59 @@ function PickBackup({ onPick, onUpload, onFailure }: {
onPick({ source: "pending", fileName: picked.fileName, encrypted: picked.encrypted });
}
- useEffect(() => {
- server.get<ExistingBackupsResponse>("database/backups")
- .then((response) => setBackups(response.backups))
- // An unreadable backup directory is not a reason to lose the "choose a file" path.
- .catch(() => setBackups([]));
- }, []);
-
const sorted = [ ...(backups ?? []) ].sort((a, b) => (a.mtime < b.mtime ? 1 : -1));
return (
<>
- <Card heading={t("setup.restore-existing-backups")}>
- {backups === null ? (
+ {/* A row rather than a section of its own: choosing a file and choosing one of the
+ backups already here are the same decision, so they read as one list of ways in. */}
+ <Card>
+ <CardSection
+ className="restore-backup-row restore-choose-file"
+ onAction={nativePicker ? pickNatively : () => fileInput.current?.click()}
+ >
+ <Icon icon="bx bx-folder-open" />
+
+ <div class="restore-backup-details">
+ <div class="restore-backup-name">{t("setup.restore-choose-file")}</div>
+ {/* One line for both ways in: selecting the file is the same act whether it
+ is then uploaded or read where it lies. */}
+ <div class="restore-backup-description">{t("setup.restore-choose-file-description")}</div>
+ </div>
+
+ <Icon icon="bx bx-chevron-right" />
+ </CardSection>
+
+ {/* Outside the row it belongs to: a hidden input inside it would have its own click
+ bubble back to the row that opened it, and open it again. */}
+ {!nativePicker && (
+ <input
+ ref={fileInput}
+ type="file"
+ accept=".db,.tnbackup"
+ class="restore-file-input"
+ onChange={(e) => {
+ const file = (e.target as HTMLInputElement).files?.[0];
+ if (file) {
+ onUpload(file);
+ }
+ }}
+ />
+ )}
+ </Card>
+
+ {/* Absent until there is something to list, which on a device being set up for the first
+ time is the usual case: an empty card would only take up the screen to say that a
+ place the user has never been to holds nothing. */}
+ {backups === null ? (
+ <Card heading={t("setup.restore-existing-backups")}>
<CardSection className="restore-loading">
<Icon icon="bx bx-loader-circle bx-spin" /> {t("setup.restore-looking-for-backups")}
</CardSection>
- ) : sorted.length > 0 ? (
- sorted.map((backup) => (
+ </Card>
+ ) : sorted.length > 0 && (
+ <Card heading={t("setup.restore-existing-backups")}>
+ {sorted.map((backup) => (
<CardSection
key={backup.filePath}
className="restore-backup-row"
@@ -246,47 +351,19 @@ function PickBackup({ onPick, onUpload, onFailure }: {
<Icon icon={backup.encrypted ? "bx bx-lock-alt" : "bx bx-data"} />
<div class="restore-backup-details">
- <div class="restore-backup-name">{backup.fileName}</div>
+ <div class="restore-backup-title">
+ <span class="restore-backup-name">{backup.fileName}</span>
+ <DatabaseFileBadges badges={describeDatabaseFormat(backup)} />
+ </div>
+
<div class="restore-backup-description">{describeDatabaseFile(backup)}</div>
</div>
<Icon icon="bx bx-chevron-right" />
</CardSection>
- ))
- ) : (
- <CardSection>
- <NoItems icon="bx bx-archive" text={t("setup.restore-no-backups")} />
- </CardSection>
- )}
- </Card>
-
- <Card heading={t("setup.restore-from-a-file")}>
- <CardSection className="restore-file-section">
- <p>{nativePicker ? t("setup.restore-from-a-file-description-native") : t("setup.restore-from-a-file-description")}</p>
-
- {!nativePicker && (
- <input
- ref={fileInput}
- type="file"
- accept=".db,.tnbackup"
- class="restore-file-input"
- onChange={(e) => {
- const file = (e.target as HTMLInputElement).files?.[0];
- if (file) {
- onUpload(file);
- }
- }}
- />
- )}
-
- <Button
- kind="primary"
- icon="bx bx-folder-open"
- text={t("setup.restore-choose-file")}
- onClick={nativePicker ? pickNatively : () => fileInput.current?.click()}
- />
- </CardSection>
- </Card>
+ ))}
+ </Card>
+ )}
</>
);
}
@@ -302,21 +379,34 @@ function UploadProgress({ upload }: { upload: UploadState }) {
<progress value={upload.sentBytes} max={upload.totalBytes} />
<div class="restore-progress-detail">
- {t("setup.restore-uploaded-so-far", {
- sent: formatSize(upload.sentBytes),
- total: formatSize(upload.totalBytes)
- })}
+ <span>
+ {t("setup.restore-uploaded-so-far", {
+ sent: formatSize(upload.sentBytes),
+ total: formatSize(upload.totalBytes)
+ })}
+ </span>
+
+ {/* Only once something has actually gone out: before the first piece lands there
+ is no elapsed time to divide by, and a rate of nothing says nothing. */}
+ {upload.bytesPerSecond > 0 && (
+ <span class="restore-upload-speed">
+ {t("setup.restore-upload-speed", { speed: formatSize(upload.bytesPerSecond) })}
+ </span>
+ )}
</div>
</CardSection>
</Card>
);
}
-function AskPassphrase({ fileName, wrong, onSubmit }: { fileName: string; wrong: boolean; onSubmit: (passphrase: string) => void }) {
+function AskPassphrase({ wrong, onSubmit }: { wrong: boolean; onSubmit: (passphrase: string) => void }) {
const [ passphrase, setPassphrase ] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
- useEffect(() => inputRef.current?.focus(), []);
+ // Without `preventScroll` the browser scrolls the page to reveal a field that is still sliding
+ // in from off-screen, which drags the heading along with it and fights the animation the whole
+ // way. The field is about to be in view on its own.
+ useEffect(() => inputRef.current?.focus({ preventScroll: true }), []);
return (
<form onSubmit={(e) => {
@@ -325,8 +415,8 @@ function AskPassphrase({ fileName, wrong, onSubmit }: { fileName: string; wrong:
onSubmit(passphrase);
}
}}>
- <Card heading={fileName}>
- <CardSection>
+ <Card>
+ <CardSection className="restore-passphrase">
<FormGroup
name="backupPassphrase"
label={t("setup.restore-passphrase")}
@@ -351,9 +441,6 @@ function AskPassphrase({ fileName, wrong, onSubmit }: { fileName: string; wrong:
);
}
-/** The stages the server works through, and which one it is on. */
-const STAGES = [ "staging", "validating", "swapping", "migrating" ] as const;
-
/** What the server says about the restore it is running. */
interface RestoreStatus {
stage: string;
@@ -399,31 +486,23 @@ function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onF
return () => clearInterval(interval);
}, [ onRestored, onFailed ]);
- const currentIndex = STAGES.indexOf(stage as typeof STAGES[number]);
-
+ // Only what is happening now, rather than the four steps as a list. Preparing the backup is the
+ // one that takes any time; the rest go by too quickly to be read, so a list of them mostly shows
+ // the user three things they will never see happen.
return (
- <>
- <Card className="restore-stages">
- {STAGES.map((name, index) => (
- <CardSection key={name} className={index < currentIndex ? "completed" : index === currentIndex ? "active" : ""}>
- <Icon icon={index < currentIndex ? "bx bx-check-circle" : index === currentIndex ? "bx bx-loader-circle bx-spin" : "bx bx-circle"} />{" "}
- {t(`setup.restore-stage-${name}`)}
-
- {/* Only the step that is running, and only where it can say how far it has
- got. The steps that cannot show nothing rather than an empty bar. */}
- {index === currentIndex && fraction !== null && (
- <div class="restore-stage-progress">
- <progress value={fraction} max={1} />
- <span>{Math.floor(fraction * 100)}%</span>
- </div>
- )}
- </CardSection>
- ))}
- </Card>
+ <div class="restore-current-step">
+ <div class="restore-step-name">{t(`setup.restore-stage-${stage}`)}</div>
+
+ {/* Only where the step can say how far it has got. The ones that cannot show nothing,
+ rather than an empty bar that never moves. */}
+ {fraction !== null && (
+ <div class="restore-stage-progress">
+ <progress value={fraction} max={1} />
+ <span>{Math.floor(fraction * 100)}%</span>
+ </div>
+ )}
- <Admonition type="warning" className="restore-banner">
- {t("setup.restore-do-not-close")}
- </Admonition>
- </>
+ <small class="restore-do-not-close">{t("setup.restore-do-not-close")}</small>
+ </div>
);
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 350eeeea7f..186d432992 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3683,35 +3683,33 @@
"continue": "Continue",
"your-ip-addresses": "Addresses for this device",
"restore-from-backup": "Restore from backup",
- "restore-from-backup-description": "You have a backup of a Trilium database. This device will start from the contents of that backup.",
- "restore-from-backup-page-description": "Pick one of the backups found on this device, or open a backup file from elsewhere.",
- "restore-existing-backups": "Backups on this device",
+ "restore-from-backup-description": "Continue using an existing knowledge base, restored from a backup file.",
+ "restore-from-backup-page-description": "Choose the backup to restore from.",
+ "restore-existing-backups": "Existing backups",
"restore-looking-for-backups": "Looking for backups...",
- "restore-no-backups": "No backups were found on this device.",
- "restore-from-a-file": "From a file",
- "restore-from-a-file-description": "Choose a .db or .tnbackup file. Large backups are sent in pieces, so an interrupted transfer carries on rather than starting again.",
- "restore-from-a-file-description-native": "Choose a .db or .tnbackup file from this computer.",
"restore-choose-file": "Choose a backup file",
- "restore-uploading": "Sending the backup...",
+ "restore-choose-file-description": "Select a database backup file (.db, .tnbackup) from your device",
+ "restore-uploading": "Uploading the backup...",
"restore-uploaded-so-far": "{{sent}} of {{total}}",
+ "restore-upload-speed": "{{speed}}/s",
"restore-error-unusable": "Unsupported or corrupted Trilium backup.",
"restore-error-too-new": "This backup is from a newer version of Trilium. Update Trilium and try again.",
"restore-error-too-old": "This backup is from a version of Trilium that is too old to be restored.",
"restore-error-unfinished": "This backup was taken from a setup that was never finished, so there is nothing in it to restore.",
"restore-error-swap-failed": "The database could not be replaced. Your previous database is back in place.",
"restore-error-would-not-open": "The restored database could not be opened. Your previous database is back in place.",
- "restore-error-refused": "Another setup step is already running on this device.",
+ "restore-error-refused": "Another setup step is already running.",
"restore-error-could-not-start": "The restore could not be started.",
- "restore-error-upload-failed": "The backup could not be sent.",
- "restore-passphrase": "Backup password",
- "restore-passphrase-description": "This backup is encrypted. Enter the password it was created with.",
+ "restore-error-upload-failed": "The backup could not be uploaded.",
+ "restore-passphrase": "Encryption password",
+ "restore-passphrase-description": "This backup is encrypted. Enter the password used to create this backup.",
"restore-wrong-passphrase": "That password does not open this backup. Please try again.",
"restore-continue": "Restore",
"restore-stage-staging": "Preparing the backup",
"restore-stage-validating": "Checking the database",
"restore-stage-swapping": "Putting it in place",
"restore-stage-migrating": "Opening the database",
- "restore-do-not-close": "Don't close this window until the restore has finished. On a server, you will sign in with the password that the backup was made with."
+ "restore-do-not-close": "Do not close this window."
},
"mind-map": {
"addChild": "Add child",
diff --git a/apps/client/src/widgets/react/DatabaseFileBadges.css b/apps/client/src/widgets/react/DatabaseFileBadges.css
new file mode 100644
index 0000000000..93156785af
--- /dev/null
+++ b/apps/client/src/widgets/react/DatabaseFileBadges.css
@@ -0,0 +1,4 @@
+.database-file-badge {
+ --color: var(--muted-text-color);
+ flex-shrink: 0;
+}
diff --git a/apps/client/src/widgets/react/DatabaseFileBadges.tsx b/apps/client/src/widgets/react/DatabaseFileBadges.tsx
new file mode 100644
index 0000000000..6b0106485d
--- /dev/null
+++ b/apps/client/src/widgets/react/DatabaseFileBadges.tsx
@@ -0,0 +1,20 @@
+import "./DatabaseFileBadges.css";
+
+import { Badge } from "./Badge";
+
+/**
+ * The labels that tell one database file apart from another at a glance: the format it was written
+ * in, and anything else worth saying about where it came from.
+ *
+ * Shared by every list of these files — the backups in the options, the ones the setup screen offers
+ * to restore from — so that a badge looks and reads the same wherever a file is shown.
+ */
+export default function DatabaseFileBadges({ badges }: { badges: string[] }) {
+ return (
+ <>
+ {badges.map((badge) => (
+ <Badge key={badge} className="database-file-badge" text={badge} outline />
+ ))}
+ </>
+ );
+}
diff --git a/apps/client/src/widgets/react/SlidePages.css b/apps/client/src/widgets/react/SlidePages.css
new file mode 100644
index 0000000000..9365b78059
--- /dev/null
+++ b/apps/client/src/widgets/react/SlidePages.css
@@ -0,0 +1,99 @@
+/*
+ * Adds no box of its own, so the pages fill whatever the caller already positioned them against
+ * rather than a wrapper that would inset them by its own padding.
+ */
+.slide-pages {
+ display: contents;
+}
+
+.slide-page {
+ position: absolute;
+ inset: 0;
+}
+
+/*
+ * Pages that keep their place in the flow, so the container is as tall as whatever is arriving
+ * rather than as tall as it was told to be. Only the page leaving is lifted out, since two pages in
+ * the flow at once would stack into the height of both.
+ */
+.slide-pages-in-flow {
+ display: block;
+ position: relative;
+ /*
+ * The page on its way out is translated a full width sideways, which would otherwise reach past
+ * the container and give the scrolling ancestor something to scroll to. Anything that then asks
+ * to be revealed, a field taking focus most of all, scrolls the whole screen sideways mid-slide.
+ */
+ overflow: clip;
+
+ > .slide-page {
+ position: static;
+ }
+
+ > .slide-page.slide-out-forward,
+ > .slide-page.slide-out-backward {
+ position: absolute;
+ inset: 0 0 auto;
+ }
+}
+
+.slide-out-forward,
+.slide-out-backward,
+.slide-in-forward,
+.slide-in-backward {
+ animation-duration: 0.35s;
+ animation-timing-function: ease-in-out;
+ animation-fill-mode: forwards;
+}
+
+.slide-out-forward {
+ animation-name: slide-out-left;
+}
+
+.slide-out-backward {
+ animation-name: slide-out-right;
+}
+
+.slide-in-forward {
+ animation-name: slide-in-right;
+}
+
+.slide-in-backward {
+ animation-name: slide-in-left;
+}
+
+body[dir=rtl] .slide-out-forward {
+ animation-name: slide-out-right;
+}
+
+body[dir=rtl] .slide-out-backward {
+ animation-name: slide-out-left;
+}
+
+body[dir=rtl] .slide-in-forward {
+ animation-name: slide-in-left;
+}
+
+body[dir=rtl] .slide-in-backward {
+ animation-name: slide-in-right;
+}
+
+@keyframes slide-out-left {
+ from { transform: translateX(0); opacity: 1; }
+ to { transform: translateX(-100%); opacity: 0; }
+}
+
+@keyframes slide-out-right {
+ from { transform: translateX(0); opacity: 1; }
+ to { transform: translateX(100%); opacity: 0; }
+}
+
+@keyframes slide-in-right {
+ from { transform: translateX(100%); opacity: 0; }
+ to { transform: translateX(0); opacity: 1; }
+}
+
+@keyframes slide-in-left {
+ from { transform: translateX(-100%); opacity: 0; }
+ to { transform: translateX(0); opacity: 1; }
+}
diff --git a/apps/client/src/widgets/react/SlidePages.spec.tsx b/apps/client/src/widgets/react/SlidePages.spec.tsx
new file mode 100644
index 0000000000..961b6ae668
--- /dev/null
+++ b/apps/client/src/widgets/react/SlidePages.spec.tsx
@@ -0,0 +1,108 @@
+import { render } from "preact";
+import { afterEach, describe, expect, it } from "vitest";
+
+import SlidePages from "./SlidePages";
+
+type Page = "first" | "second" | "third";
+const ORDER: Page[] = [ "first", "second", "third" ];
+
+let container: HTMLDivElement;
+
+function show(page: Page, props: { inFlow?: boolean } = {}) {
+ container ??= document.body.appendChild(document.createElement("div"));
+ render(
+ <SlidePages current={page} order={ORDER} {...props}>
+ {(shown) => <div class={`page-${shown}`}>{shown}</div>}
+ </SlidePages>,
+ container
+ );
+}
+
+/** The page on its way out, which only exists while a slide is running. */
+function leaving() {
+ return container.querySelector("[class*=slide-out-]");
+}
+
+function arriving() {
+ return container.querySelector("[class*=slide-in-], .slide-current");
+}
+
+/** Ends the animation the way the browser would, which is what tells the component to let go. */
+async function finishSlide() {
+ leaving()?.dispatchEvent(new Event("animationend", { bubbles: true }));
+ // Letting go is the one part that needs a render of its own, which Preact schedules.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ container = undefined as unknown as HTMLDivElement;
+});
+
+describe("sliding between pages", () => {
+ it("shows only the current page until there is somewhere to slide from", () => {
+ show("first");
+
+ expect(leaving()).toBeFalsy();
+ expect(arriving()?.className).toContain("slide-current");
+ expect(container.textContent).toBe("first");
+ });
+
+ it("slides forwards towards a page later in the order, keeping both on screen meanwhile", () => {
+ show("first");
+ show("second");
+
+ expect(leaving()?.className).toContain("slide-out-forward");
+ expect(leaving()?.textContent).toBe("first");
+ expect(arriving()?.className).toContain("slide-in-forward");
+ expect(arriving()?.textContent).toBe("second");
+ });
+
+ it("slides backwards towards an earlier one, without being told which way it went", async () => {
+ show("first");
+ show("third");
+ await finishSlide();
+
+ show("second");
+
+ expect(leaving()?.className).toContain("slide-out-backward");
+ expect(arriving()?.className).toContain("slide-in-backward");
+ });
+
+ it("lets the page it was leaving go once the animation ends", async () => {
+ show("first");
+ show("second");
+ expect(leaving()).toBeTruthy();
+
+ await finishSlide();
+
+ expect(leaving()).toBeFalsy();
+ expect(container.textContent).toBe("second");
+ expect(arriving()?.className).toContain("slide-current");
+ });
+
+ it("keeps sliding when something inside the page it is leaving finishes an animation of its own", async () => {
+ show("first");
+ show("second");
+
+ // Animation events bubble, and a spinner or a field's own animation ending is not the slide
+ // ending: acting on it would drop the page mid-flight and snap the other into place.
+ container.querySelector(".page-first")?.dispatchEvent(new Event("animationend", { bubbles: true }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(leaving()).toBeTruthy();
+ expect(arriving()?.className).toContain("slide-in-forward");
+ });
+
+ it("takes only the page leaving out of the flow when the pages keep their place", () => {
+ show("first", { inFlow: true });
+ show("second", { inFlow: true });
+
+ expect(container.querySelector(".slide-pages-in-flow")).toBeTruthy();
+ // Which of them is positioned is settled in CSS; what matters here is that they are told
+ // apart, so the height can follow the one arriving.
+ expect(leaving()?.className).toContain("slide-out-forward");
+ expect(arriving()?.className).not.toContain("slide-out-");
+ });
+});
diff --git a/apps/client/src/widgets/react/SlidePages.tsx b/apps/client/src/widgets/react/SlidePages.tsx
new file mode 100644
index 0000000000..0c879bf9ee
--- /dev/null
+++ b/apps/client/src/widgets/react/SlidePages.tsx
@@ -0,0 +1,81 @@
+import "./SlidePages.css";
+
+import clsx from "clsx";
+import { ComponentChildren } from "preact";
+import { useRef, useState } from "preact/hooks";
+
+interface SlidePagesProps<T extends string> {
+ /** The page to show. Changing it slides the one before it out and this one in. */
+ current: T;
+ /** Every page in the order they are visited: further along means the slide goes forwards. */
+ order: readonly T[];
+ /**
+ * Whether the pages keep their place in the flow.
+ *
+ * Off by default, which fills the container and suits pages that are each the size of the
+ * screen. On, only the page leaving is taken out of the flow, so the container follows the
+ * height of whatever is arriving — for steps within a screen, which are rarely the same size.
+ */
+ inFlow?: boolean;
+ className?: string;
+ /** Renders a page. Called for the one leaving as well, for as long as it is still on screen. */
+ children: (page: T) => ComponentChildren;
+}
+
+/**
+ * Slides from one page to the next, forwards or backwards depending on which way through `order` the
+ * change went.
+ *
+ * The direction is worked out rather than asked for, so a caller only ever says which page it is on
+ * and going back looks like going back without anything having to remember that it did.
+ */
+export default function SlidePages<T extends string>({ current, order, inFlow, className, children }: SlidePagesProps<T>) {
+ const shown = useRef(current);
+ const leavingRef = useRef<{ page: T; direction: Direction } | null>(null);
+ const [ , redraw ] = useState(0);
+
+ // Worked out while rendering the page being arrived at rather than in an effect afterwards: a
+ // pass that drew the new page before the slide had started would put it in its final place and
+ // then jump it back to slide in from there.
+ if (shown.current !== current) {
+ leavingRef.current = { page: shown.current, direction: directionBetween(order, shown.current, current) };
+ shown.current = current;
+ }
+
+ const leaving = leavingRef.current;
+
+ return (
+ <div className={clsx("slide-pages", className, { "slide-pages-in-flow": inFlow })}>
+ {leaving && (
+ <div
+ class={`slide-page slide-out-${leaving.direction}`}
+ onAnimationEnd={(e) => {
+ // Animation events bubble, so anything inside the page that animates would
+ // otherwise end the slide early: the page leaving is dropped and the one
+ // arriving loses its class mid-flight, snapping into place.
+ if (e.target !== e.currentTarget) {
+ return;
+ }
+
+ leavingRef.current = null;
+ redraw((pass) => pass + 1);
+ }}
+ >
+ {children(leaving.page)}
+ </div>
+ )}
+
+ {/* Keyed, so arriving at a page mounts it rather than reusing what was there before it. */}
+ <div class={`slide-page ${leaving ? `slide-in-${leaving.direction}` : "slide-current"}`} key={current}>
+ {children(current)}
+ </div>
+ </div>
+ );
+}
+
+type Direction = "forward" | "backward";
+
+/** Which way through `order` the move went. A page that is not in the order counts as forwards. */
+function directionBetween<T extends string>(order: readonly T[], from: T, to: T): Direction {
+ return order.indexOf(to) > order.indexOf(from) ? "forward" : "backward";
+}
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index 4d161c4210..14802bfd02 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -3,6 +3,7 @@ import "./backup.css";
import { BackupDatabaseNowResponse, BackupPassphraseStatus, DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { describeDatabaseFormat } from "../../../services/database_files";
import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
import options from "../../../services/options";
@@ -307,14 +308,10 @@ export function BackupList({ backups, backupFolderPath, refreshCallback }: { bac
if (customDir && backupFolderPath && !isInsideDirectory(backupFolderPath, file.filePath)) {
badges.push(t("backup.default_location"));
}
- if (file.compressed) {
- badges.push(t("backup.compressed"));
- }
- if (file.encrypted) {
- badges.push(t("backup.encrypted"));
- }
- return badges;
+ // What the file is comes from the shared description, so it reads the same here as it does
+ // on the setup screen that offers to restore from it.
+ return [ ...badges, ...describeDatabaseFormat(file) ];
}, [customDir, backupFolderPath]);
return (
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css
index b7578d15d5..a61b6975ea 100644
--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css
@@ -4,7 +4,3 @@
gap: 8px;
}
-.database-file-badge {
- --color: var(--muted-text-color);
- flex-shrink: 0;
-}
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
index 1675e14f7d..e1e2116a3a 100644
--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx
@@ -6,7 +6,7 @@ import { useMemo } from "preact/hooks";
import { type DatabaseFile, describeDatabaseFile } from "../../../../services/database_files";
import open from "../../../../services/open";
import ActionButton from "../../../react/ActionButton";
-import { Badge } from "../../../react/Badge";
+import DatabaseFileBadges from "../../../react/DatabaseFileBadges";
import NoItems from "../../../react/NoItems";
import OptionsRow from "./OptionsRow";
import OptionsSection from "./OptionsSection";
@@ -53,9 +53,7 @@ export default function DatabaseFileList<T extends DatabaseFile>({ title, locati
label={
<span className="database-file-label">
<span className="selectable-text">{file.fileName}</span>
- {fileBadges?.(file).map((badge) => (
- <Badge key={badge} className="database-file-badge" text={badge} outline />
- ))}
+ <DatabaseFileBadges badges={fileBadges?.(file) ?? []} />
</span>
}
description={describeDatabaseFile(file)}