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
client/start again: improve UI
Adorian Doran8b1a2a283531
diff --git a/apps/client/src/login.tsx b/apps/client/src/login.tsxindex 1250e54c3a..4340918d37 100644--- a/apps/client/src/login.tsx+++ b/apps/client/src/login.tsx@@ -10,6 +10,7 @@ import { initLocale, t } from "./services/i18n";import Button from "./widgets/react/Button";import { Card, CardSection } from "./widgets/react/Card";import FormTextBox from "./widgets/react/FormTextBox";+import PasswordField from "./widgets/react/PasswordField";import SetupPage from "./widgets/react/SetupPage";import OptionsRow, { OptionsRowWithToggle } from "./widgets/type_widgets/options/components/OptionsRow";@@ -157,13 +158,7 @@ export function PasswordLogin({ illustration, totpEnabled, error, errorId, onErr><Card><CardSection>- <OptionsRow name="password" label={t("login.password")} stacked>- <FormTextBox- inputRef={passwordRef} autoFocus- type="password" name="password"- autocomplete="current-password" required- />- </OptionsRow>+ <PasswordField inputRef={passwordRef} />{totpEnabled && (<OptionsRow name="totpToken" label={t("login.totp-token")} stacked>diff --git a/apps/client/src/setup.css b/apps/client/src/setup.cssindex 767e19f73e..cf93525d19 100644--- a/apps/client/src/setup.css+++ b/apps/client/src/setup.css@@ -80,6 +80,13 @@ body.setup {.tn-icon {font-size: 2.5em;color: var(--muted-text-color);+ /* A box of its own rather than whatever width the glyph happens to have, so+ every title and description in the list starts on the same line however+ large the icon beside it is drawn. One em at this size is 2.5em of the card,+ which is the measure the quieter card below matches itself to. */+ width: 1em;+ flex-shrink: 0;+ text-align: center;}h3 {@@ -99,14 +106,18 @@ body.setup {}}- /* Apart from the four above, which all replace the knowledge base, and quieter than+ /* Apart from the four below, which all replace the knowledge base, and quieter thanthem: this is the one that changes nothing. */.setup-keep-card {- margin-top: 1.5rem;+ margin-bottom: 0.5rem;background-color: transparent;.tn-icon {font-size: 1.75em;+ /* Drawn smaller, but taking the same room: 2.5em of the card, written in this+ icon's own units. Without it the smaller glyph pulls its title left and the+ item stops lining up with the four below. */+ width: calc(2.5em / 1.75);}h3 {diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsxindex bdcb711bee..9c6ad4f47e 100644--- a/apps/client/src/setup.spec.tsx+++ b/apps/client/src/setup.spec.tsx@@ -22,7 +22,7 @@ const serverMock = vi.hoisted(() => ({}));vi.mock("./services/server", () => ({ default: serverMock }));-import { initialState, openedAtRestore, renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";+import { afterLanguage, initialState, openedAtRestore, renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";type Stats = { outstandingPullCount: number; totalPullCount: number | null; initialized: boolean; lastSyncError?: string | null };@@ -64,6 +64,22 @@ afterEach(() => {vi.clearAllMocks();});+describe("the unlock screen, as the wizard renders it", () => {+ it("puts a real page inside the slide, not an empty one", async () => {+ // Worth asserting rather than assuming: the wizard's pages are absolutely positioned against+ // a container with a fixed height, so a page that renders nothing and a container that has+ // collapsed to nothing look exactly alike — a blank screen with no error to go on.+ const c = renderInto(renderState("unlock", vi.fn()));+ await flushEffects();++ expect(c.querySelector(".page.setup-unlock")).not.toBeNull();+ expect(c.querySelector("input[type=password]")).not.toBeNull();+ // Transparent to layout, so the page it wraps fills the frame rather than sitting in a box+ // of the width setup.css gives every other form.+ expect(c.querySelector("form.setup-unlock-form")).not.toBeNull();+ });+});+describe("SyncInProgress", () => {it("switches to the failure screen when the server reports a failed sync", async () => {const setState = vi.fn();@@ -202,14 +218,11 @@ describe("where the wizard opens", () => {expect(initialState({})).toBe("selectLanguage");});- it("goes where a setup marker asked, which is how the app sends a user here", () => {- expect(initialState({ setupTargetScreen: "restore-backup" })).toBe("restoreFromBackup");- });-- it("offers a copy of the existing knowledge base before anything else, wherever it was headed", () => {- expect(initialState({ hasExistingData: true })).toBe("existingData");+ it("starts there whatever a marker asked for, so the rest is read in the chosen language", () => {+ expect(initialState({ setupTargetScreen: "restore-backup" })).toBe("selectLanguage");+ expect(initialState({ hasExistingData: true })).toBe("selectLanguage");expect(initialState({ hasExistingData: true, setupTargetScreen: "restore-backup" }))- .toBe("existingData");+ .toBe("selectLanguage");});it("goes straight to the backup screen, which is the one that replaces nothing", () => {@@ -243,6 +256,27 @@ describe("where the wizard opens", () => {it("ignores a screen it does not know rather than guessing at one", () => {expect(initialState({ setupTargetScreen: "createNewDocumentEmpty" as never })).toBe("selectLanguage");+ expect(afterLanguage({ setupTargetScreen: "createNewDocumentEmpty" as never }))+ .toBe("firstOptions");+ });+});++describe("where the language step leads", () => {+ it("offers a copy of the existing knowledge base, before the menu that replaces it", () => {+ // After the language rather than before, so a question about the user's own knowledge base+ // is put in the language they have just chosen.+ expect(afterLanguage({ hasExistingData: true })).toBe("existingData");+ expect(afterLanguage({ hasExistingData: true, setupTargetScreen: "restore-backup" }))+ .toBe("existingData");+ });++ it("goes straight to the menu on a first run, which has nothing to copy", () => {+ expect(afterLanguage({})).toBe("firstOptions");+ });++ it("goes where a marker asked once there is nothing left to lose", () => {+ // A restore reached this way skips the menu: it is the errand the app was sent here for.+ expect(afterLanguage({ setupTargetScreen: "restore-backup" })).toBe("restoreFromBackup");});it("knows when the restore is the whole of what the wizard was opened for", () => {diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 7d79610ac5..a2ee1f8e98 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -45,7 +45,7 @@ async function main() {type State = "unlock" | "backupDatabase" | "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";-const STATE_ORDER: State[] = ["unlock", "backupDatabase", "existingData", "selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];+const STATE_ORDER: State[] = ["unlock", "backupDatabase", "selectLanguage", "existingData", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];export function renderState(state: State, setState: (state: State) => void) {switch (state) {@@ -124,10 +124,10 @@ interface SetupGlob {/*** Where the wizard opens.*- * A first run starts at the language step and works forward. Everything else comes in already- * knowing better: a wizard with a knowledge base behind it that has to be unlocked before it will- * do anything, a sync interrupted after it created the schema, an instance offered a copy of what is- * behind the wizard, and an instance sent to a particular screen through a `setup.json` marker.+ * Every run starts at the language step and works forward from there. Three things come in already+ * knowing better: a wizard with a knowledge base behind it that has to be unlocked before it will do+ * anything, a sync interrupted after it created the schema, and an instance sent to a particular+ * screen through a `setup.json` marker.*/export function initialState(glob: SetupGlob): State {// First of all, because everything below it acts on a knowledge base that is still there.@@ -145,14 +145,25 @@ export function initialState(glob: SetupGlob): State {/** The rest of the wizard, once there is nothing left standing in front of it. */function afterUnlock(glob: SetupGlob): State {// Asked for by a running instance that wants its database held still long enough to be copied.- // It skips the screen below because that screen is the same offer, made where the user is on- // their way somewhere else; here the copy is the whole errand.+ // Straight there, past the language: the instance already runs in one, and the copy is the whole+ // errand rather than a step on the way to a menu the user never asked for.if (glob.setupTargetScreen === "backup-database" && glob.hasExistingData) {return "backupDatabase";}- // Before the language, before the menu: this is the one moment the database is open and nothing- // is running against it, which is what taking a copy of it needs.+ return "selectLanguage";+}++/**+ * Where the language step leads.+ *+ * The offer of a copy comes after it rather than before, so that a question about the user's own+ * knowledge base is put in the language they have just chosen rather than in whichever one the+ * instance happened to be running in.+ */+export function afterLanguage(glob: SetupGlob): State {+ // The one moment the database is open with nothing running against it, which is what taking a+ // copy of it needs.if (glob.hasExistingData) {return "existingData";}@@ -180,7 +191,7 @@ function afterExistingData(glob: SetupGlob): State {case "restore-backup": return "restoreFromBackup";// Deliberately not a lookup table: two of the states below create a document the moment they// are shown, and nothing outside this file should be able to name one.- default: return "selectLanguage";+ default: return "firstOptions";}}@@ -194,7 +205,7 @@ function SelectLanguage({ setState }: { setState: (state: State) => void }) {title={t("setup.language")}className="select-language"illustration={<Icon icon="bx bx-globe" className="illustration-icon" />}- footer={<Button text={t("setup.continue")} kind="primary" onClick={() => setState("firstOptions")} />}+ footer={<Button text={t("setup.continue")} kind="primary" onClick={() => setState(afterLanguage(window.glob))} />}><Card><CardSection>@@ -257,9 +268,25 @@ function SetupOptions({ setState, onKeep }: { setState: (state: State) => void;illustration={<img src={logo} alt="Setup illustration" className="illustration-logo" />}error={error}errorId={errorId}- onBack={() => setState("selectLanguage")}+ // Back to whichever step actually came before this one: the offer of a copy where there+ // is still something to copy, and the language where that offer was never made.+ onBack={() => setState(hasExistingData() ? "existingData" : "selectLanguage")}><div class="setup-options">+ {/* First, and offered only while there is something to go back to. Set apart from+ the four below rather than made one of them: those replace the knowledge base+ and this one is how the user leaves it exactly as they found it. */}+ {hasExistingData() && (+ <CardFrame className="setup-option-card setup-keep-card" onClick={onKeep}>+ <Icon icon="bx bx-log-in-circle" />++ <div>+ <h3>{t("setup.keep-existing")}</h3>+ <p>{t("setup.keep-existing-description")}</p>+ </div>+ </CardFrame>+ )}+<SetupOptionCardicon="bx bx-file-blank"title={t("setup.new-document")}@@ -267,13 +294,6 @@ function SetupOptions({ setState, onKeep }: { setState: (state: State) => void;onClick={() => setState("createNewDocumentOptions")}/>- <SetupOptionCard- icon="bx bx-archive-in"- title={t("setup.restore-from-backup")}- description={t("setup.restore-from-backup-description")}- onClick={() => setState("restoreFromBackup")}- />-<SetupOptionCardicon="bx bx-server"title={t("setup.sync-from-server")}@@ -288,21 +308,14 @@ function SetupOptions({ setState, onKeep }: { setState: (state: State) => void;disabled={glob.isStandalone}onClick={() => void syncFromDesktop()}/>- </div>-- {/* The way out, offered only while there is something to go back to. Set apart from the- four above rather than made a fifth of them: those replace the knowledge base and- this one is how the user leaves it exactly as they found it. */}- {hasExistingData() && (- <CardFrame className="setup-option-card setup-keep-card" onClick={onKeep}>- <Icon icon="bx bx-log-in-circle" />- <div>- <h3>{t("setup.keep-existing")}</h3>- <p>{t("setup.keep-existing-description")}</p>- </div>- </CardFrame>- )}+ <SetupOptionCard+ icon="bx bx-archive-in"+ title={t("setup.restore-from-backup")}+ description={t("setup.restore-from-backup-description")}+ onClick={() => setState("restoreFromBackup")}+ />+ </div></SetupPage>);}diff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.cssindex 5cb6817774..7b9d14a569 100644--- a/apps/client/src/setup_existing.css+++ b/apps/client/src/setup_existing.css@@ -15,8 +15,8 @@padding-block: 12px;}-/* The answer that erases the knowledge base, in the colour the rest of the app gives an action- that cannot be taken back. */+/* The answer that leaves nothing to go back to, in the colour the rest of the app gives an action+ that cannot be taken back. Nothing is erased by choosing it — what it costs is the copy. */.page.existing-data .existing-data-destructive .tn-radio {color: var(--dropdown-item-icon-destructive-color);}diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsxindex 16a5ee6e87..614c774ba9 100644--- a/apps/client/src/setup_existing.tsx+++ b/apps/client/src/setup_existing.tsx@@ -214,10 +214,9 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onSkip, onCancelreturn (<SetupPageclassName="existing-data"- // A question and nothing else: a paragraph above it is the part someone in a hurry- // reads past, and this is the one offer of a copy they will get.+ // A question and nothing else: this is the one offer of a copy the user will get, and a+ // paragraph above it is the part someone in a hurry reads past.title={t("setup.existing-data")}- description={t("setup.existing-data-description")}illustration={<Icon icon="bx bx-data" className="illustration-icon" />}error={error}errorId={errorId}@@ -240,7 +239,10 @@ export function ExistingDataChoice({ error, errorId, onBackUp, onSkip, onCancelscreen is for. Which is checked is held here rather than by the browser's owngrouping, so the two stay exclusive. */}{CHOICES.map(({ value, label }) => (- <CardSection key={value}>+ // Going on without a copy is coloured as the app colours what cannot be taken+ // back: nothing is erased by choosing it, but it is the answer that leaves the+ // user with nothing to go back to once they pick a path from the menu after it.+ <CardSection key={value} className={value === "skip" ? "existing-data-destructive" : undefined}><FormRadioGroupname="existing-data-choice"currentValue={choice ?? ""}diff --git a/apps/client/src/setup_unlock.css b/apps/client/src/setup_unlock.cssnew file mode 100644index 0000000000..7726b35c96--- /dev/null+++ b/apps/client/src/setup_unlock.css@@ -0,0 +1,36 @@+/*+ * Selectors carry the whole chain down from `body.setup` on purpose. setup.css writes its own rules+ * as one nested block, so a plain `.setup-container form` reads as+ * `body.setup > .setup-outer-wrapper .setup-container form` and outweighs anything shorter. Both+ * rules below override one of those, so both have to be at least as specific to be applied at all.+ */++/*+ * The unlock page wraps the whole of itself in a form, so that the footer's button submits it the+ * way the login screen's does. setup.css lays out every form in the wizard as a column of its own,+ * which for a form that IS the page leaves `.page` sizing itself against a parent of no particular+ * height: `height: 100%` resolves to auto, the page shrinks to its contents, and the footer comes to+ * rest wherever they end. Made transparent to layout instead, so the page sizes against the frame.+ *+ * Note this cannot be borrowed from login.css by putting `login-container` on the wizard's own+ * container: that class sets `height: auto`, and the wizard's pages are absolutely positioned, so+ * the container would have nothing left in the flow to take its height from and would collapse.+ */+body.setup .setup-outer-wrapper .setup-container form.setup-unlock-form {+ display: contents;+}++/*+ * The one short field, narrowed to the login screen's proportions.+ *+ * Only across, never down: setup.css grows `main` with `flex: 1`, and that is what holds the footer+ * against the bottom of the frame. login.css centres its own `main` with `margin: auto`, which works+ * there because that container is only as tall as its contents — borrowed here it absorbs the free+ * space `flex` was going to use, and the footer comes to rest halfway up the page.+ */+@media (min-width: 700px) {+ body.setup .setup-outer-wrapper .setup-container .page.setup-unlock > main {+ width: 65%;+ margin-inline: auto;+ }+}diff --git a/apps/client/src/setup_unlock.spec.tsx b/apps/client/src/setup_unlock.spec.tsxnew file mode 100644index 0000000000..d104522155--- /dev/null+++ b/apps/client/src/setup_unlock.spec.tsx@@ -0,0 +1,113 @@+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 }));++const serverMock = vi.hoisted(() => ({+ // `get` is here for the eager module-load fetches the import graph makes (options, keyboard+ // actions), not for anything this screen asks for itself.+ get: vi.fn(async (url: string): Promise<unknown> => (url === "keyboard-actions" ? [] : {})),+ post: vi.fn(async (_url: string, _body?: unknown): Promise<unknown> => ({}))+}));+vi.mock("./services/server", () => ({ default: serverMock }));++const setSetupAuthToken = vi.hoisted(() => vi.fn());+vi.mock("./services/setup_auth", () => ({ setSetupAuthToken }));++import SetupUnlock from "./setup_unlock";++let container: HTMLDivElement;+const onUnlocked = vi.fn();++/** Preact flushes effects and state through the microtask queue plus a frame. */+const settle = () => vi.advanceTimersByTimeAsync(50);++function renderScreen() {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(<SetupUnlock onUnlocked={onUnlocked} />, container);++ return container;+}++function password(): HTMLInputElement | null {+ return container.querySelector<HTMLInputElement>("input[type=password]");+}++function submit() {+ container.querySelector("form")?.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+}++beforeEach(() => {+ vi.useFakeTimers();+ onUnlocked.mockReset();+ setSetupAuthToken.mockReset();+ serverMock.post.mockReset().mockResolvedValue({ authenticated: true, token: "a-token" });+});++afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+});++describe("unlocking a wizard that is standing over a knowledge base", () => {+ it("asks the one question the login screen asks, and says nothing else about it", async () => {+ renderScreen();+ await settle();++ expect(container.textContent).toContain("login.heading");+ expect(container.textContent).toContain("login.password");+ // Explaining why would only invite the user to read it as a different question.+ expect(container.textContent).not.toContain("setup.unlock-description");+ // Autofilled by a password manager the same way the login screen's field is.+ expect(password()?.getAttribute("autocomplete")).toBe("current-password");+ });++ it("takes the token the password bought and carries on", async () => {+ renderScreen();+ await settle();++ const input = password();+ if (input) {+ input.value = "hunter2";+ }+ submit();+ await settle();++ expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "hunter2" });+ expect(setSetupAuthToken).toHaveBeenCalledWith("a-token");+ expect(onUnlocked).toHaveBeenCalled();+ });++ it("says so and stays put on a wrong password, so the next attempt is a keystroke away", async () => {+ serverMock.post.mockResolvedValue({ authenticated: false });+ renderScreen();+ await settle();++ submit();+ await settle();++ expect(container.querySelector(".page-error")?.textContent).toContain("login.incorrect-password");+ expect(setSetupAuthToken).not.toHaveBeenCalled();+ expect(onUnlocked).not.toHaveBeenCalled();+ expect(password()).not.toBeNull();+ });++ it("reads the password off the field at submit time, not from state", async () => {+ // A controlled value of "" overwrites what the browser autofilled, so the first press would+ // submit an empty password — the "incorrect password, press again" bug the login screen hit.+ renderScreen();+ await settle();++ const input = password();+ if (input) {+ input.value = "filled-in-by-the-browser";+ }+ submit();+ await settle();++ expect(serverMock.post).toHaveBeenCalledWith("setup/auth", { password: "filled-in-by-the-browser" });+ });+});diff --git a/apps/client/src/setup_unlock.tsx b/apps/client/src/setup_unlock.tsxindex bfc307a82e..a228290e4a 100644--- a/apps/client/src/setup_unlock.tsx+++ b/apps/client/src/setup_unlock.tsx@@ -1,13 +1,14 @@-import { useState } from "preact/hooks";+import "./setup_unlock.css";+import { useRef, useState } from "preact/hooks";++import logo from "./assets/icon-color.svg?url";import { t } from "./services/i18n";import server from "./services/server";import { setSetupAuthToken } from "./services/setup_auth";import Button from "./widgets/react/Button";import { Card, CardSection } from "./widgets/react/Card";-import FormGroup from "./widgets/react/FormGroup";-import FormTextBox from "./widgets/react/FormTextBox";-import Icon from "./widgets/react/Icon";+import PasswordField from "./widgets/react/PasswordField";import SetupPage from "./widgets/react/SetupPage";/**@@ -18,6 +19,10 @@ import SetupPage from "./widgets/react/SetupPage";* case, and on a server it is served to whoever can reach the port, with a whole knowledge base one* button away from being replaced. So this comes first, before the wizard will say or do anything.*+ * Deliberately the login screen over again, down to the wording: the same logo, the same field, the+ * same button. The user is being asked the one question they already know the answer to, and saying+ * anything more about why would only invite them to read it as a different question.+ ** Asked for only where it can be answered and where it is worth asking: a first run has no password* to check against, and the desktop's own window is not reachable by anyone the desktop is not.*@@ -26,69 +31,59 @@ import SetupPage from "./widgets/react/SetupPage";* @module*/export default function SetupUnlock({ onUnlocked }: { onUnlocked: () => void }) {- const [ password, setPassword ] = useState("");- const [ wrong, setWrong ] = useState(false);- const [ busy, setBusy ] = useState(false);+ const passwordRef = useRef<HTMLInputElement>(null);+ const [ error, setError ] = useState<string | null>(null);+ const [ errorId, setErrorId ] = useState(0);+ const [ submitting, setSubmitting ] = useState(false);++ function raiseError(message: string) {+ setError(message);+ setErrorId((id) => id + 1);+ }- async function unlock() {- setBusy(true);+ async function handleSubmit(e: Event) {+ e.preventDefault();+ if (submitting) {+ return;+ }++ setSubmitting(true);try {const { authenticated, token } = await server.post<{ authenticated: boolean; token?: string }>(- "setup/auth", { password });+ "setup/auth", { password: passwordRef.current?.value ?? "" });if (!authenticated || !token) {- setWrong(true);+ raiseError(t("login.incorrect-password"));return;}setSetupAuthToken(token);onUnlocked();+ } catch {+ // A wrong password is answered, not thrown, so anything landing here is the connection+ // or the rate limiter the attempts are counted by.+ raiseError(t("login.connection-error"));} finally {- setBusy(false);+ setSubmitting(false);}}return (- <SetupPage- className="setup-unlock"- title={t("setup.unlock-title")}- description={t("setup.unlock-description")}- illustration={<Icon icon="bx bx-lock-alt" className="illustration-icon" />}- footer={- <Button- text={t("setup.continue")}- kind="primary"- disabled={!password || busy}- onClick={() => void unlock()}- />- }- >- <form onSubmit={(e) => {- e.preventDefault();- if (password && !busy) {- void unlock();- }- }}>+ <form className="setup-unlock-form" onSubmit={(e) => void handleSubmit(e)}>+ <SetupPage+ className="setup-unlock"+ title={t("login.heading")}+ illustration={<img src={logo} alt="" className="illustration-logo" />}+ error={error}+ errorId={errorId}+ footer={<Button text={t("login.button")} kind="primary" disabled={submitting} />}+ ><Card><CardSection>- <FormGroup- label={t("setup.unlock-password")} name="setupPassword"- error={wrong ? t("setup.wrong-password") : undefined}- >- <FormTextBox- type="password"- currentValue={password}- onChange={(value) => {- setPassword(value);- setWrong(false);- }}- autocomplete="current-password"- required- />- </FormGroup>+ <PasswordField inputRef={passwordRef} /></CardSection></Card>- </form>- </SetupPage>+ </SetupPage>+ </form>);}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9b686622f3..acae9f4f53 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1745,7 +1745,6 @@},"database": {"title": "Database",- "start_over_title": "Start over","start_over_description": "Switch to a new blank database, start again syncing with a new server or restore a backup. You will be prompted to backup your data before discarding the existing data.","start_over": "Start over","start_over_confirm": "Trilium will go back to the setup screen, where you can start a new knowledge base, restore a backup or sync from another device. You will be offered a backup of your current data first, and nothing is deleted until you choose one of those. Continue?",@@ -3703,7 +3702,6 @@"continue": "Continue","your-ip-addresses": "Addresses for this device","existing-data": "Save your existing data?",- "existing-data-description": "Your current knowledge base is still here and stays untouched until you choose what to do next. This is a good moment to take a copy of it.","existing-data-back-up": "Yes, create a backup","existing-data-skip": "No, continue without a backup","existing-data-skip-warning": "Nothing is deleted yet. Your knowledge base is only replaced once you choose to create a new one, restore a backup or sync from another device.",@@ -3740,14 +3738,11 @@"backup-download-failed": "The download did not finish.","backup-finish": "Finish","existing-data-erase-confirm": "Your existing knowledge base will now be permanently deleted, so that this device can receive one from your desktop app. Make sure you have a backup somewhere safe. Continue?",- "unlock-title": "Unlock your knowledge base",- "unlock-description": "This device already holds a knowledge base. Enter the password you use to log in, so that only you can decide what happens to it.",- "unlock-password": "Password",- "keep-existing": "Continue to the app",- "keep-existing-description": "Leave everything as it is and go back to your knowledge base.",+ "keep-existing": "Return to the app",+ "keep-existing-description": "Keep using your existing knowledge base and go back to the app.","existing-data-keep-failed": "The existing knowledge base could not be reopened.","restore-from-backup": "Restore from backup",- "restore-from-backup-description": "Continue using an existing knowledge base, restored from a backup file.",+ "restore-from-backup-description": "Start using a 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...",diff --git a/apps/client/src/widgets/react/PasswordField.tsx b/apps/client/src/widgets/react/PasswordField.tsxnew file mode 100644index 0000000000..ea55e0e7cc--- /dev/null+++ b/apps/client/src/widgets/react/PasswordField.tsx@@ -0,0 +1,28 @@+import type { RefObject } from "preact";++import { t } from "../../services/i18n";+import FormTextBox from "./FormTextBox";+import OptionsRow from "../type_widgets/options/components/OptionsRow";++/**+ * The instance's own password, asked for the way the login screen asks for it.+ *+ * Shared so the two screens that ask cannot drift apart: the login screen, and the setup wizard+ * standing over a knowledge base it has to prove ownership of before it will touch it. To a user+ * they are the same question, so they are the same field.+ *+ * Uncontrolled on purpose, and read from the ref at submit time. A controlled value of `""`+ * overwrites what the browser autofilled, so the first press would submit an empty password — the+ * "incorrect password, press again" bug. Neither screen needs live validation.+ */+export default function PasswordField({ inputRef }: { inputRef: RefObject<HTMLInputElement> }) {+ return (+ <OptionsRow name="password" label={t("login.password")} stacked>+ <FormTextBox+ inputRef={inputRef} autoFocus+ type="password" name="password"+ autocomplete="current-password" required+ />+ </OptionsRow>+ );+}diff --git a/apps/client/src/widgets/type_widgets/options/database.css b/apps/client/src/widgets/type_widgets/options/database.cssindex 8f2ddd53ff..ef4ead2fd8 100644--- a/apps/client/src/widgets/type_widgets/options/database.css+++ b/apps/client/src/widgets/type_widgets/options/database.css@@ -1,17 +1,8 @@-.options-section.start-over {- .start-over-actions {- display: flex;- justify-content: flex-end;- margin-top: 12px;- }-- /* Coloured like every other action that cannot be taken back, so it is recognised before it is- read rather than after. */- .start-over-button {- color: var(--dropdown-item-icon-destructive-color);- }+/* The notice sits above the card it is about, so the gap belongs under it. */+.admonition.start-over-pending {+ margin-bottom: 16px;- .start-over-pending {- margin-top: 12px;+ p:last-of-type {+ margin-bottom: 12px;}}diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsxindex 5bfd12ed8c..a87d82d805 100644--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx@@ -80,10 +80,15 @@ describe("starting over from Options", () => {button("start-over-button")?.click();await settle();- expect(container.querySelector(".start-over-pending")?.textContent)- .toContain("database.start_over_pending");- // The button that made it is gone, so it cannot be pressed twice over.- expect(button("start-over-button")).toBeNull();+ // Above the card, since a request left standing is the state of the whole page from here on.+ const notice = container.querySelector(".start-over-pending");+ expect(notice?.textContent).toContain("database.start_over_pending");+ expect(notice?.compareDocumentPosition(container.querySelector(".start-over") as Node))+ .toBe(Node.DOCUMENT_POSITION_FOLLOWING);++ // The button that made it stays where it was, so the row still reads as a whole — but it is+ // out of reach, since the request it would make has already been made.+ expect(button("start-over-button")?.disabled).toBe(true);});it("takes it back, which is all a server owner can do until they restart", async () => {@@ -111,6 +116,6 @@ describe("starting over from Options", () => {// What is lost is a notice; the button below it is what the page is for.expect(container.querySelector(".start-over-pending")).toBeNull();- expect(button("start-over-button")).not.toBeNull();+ expect(button("start-over-button")?.disabled).toBe(false);});});diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsxindex b07a3ad186..7b5543f9fc 100644--- a/apps/client/src/widgets/type_widgets/options/database.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.tsx@@ -11,8 +11,8 @@ import {} from "../../../services/setup_mode";import Admonition from "../../react/Admonition";import Button from "../../react/Button";+import { Card, CardOption } from "../../react/Card";import OptionsPageHeader from "./components/OptionsPageHeader";-import OptionsSection from "./components/OptionsSection";/*** What can be done to the knowledge base as a whole, rather than to anything inside it.@@ -21,10 +21,48 @@ import OptionsSection from "./components/OptionsSection";* nor a setting, and it is the only thing in Options that leaves the application entirely.*/export default function DatabaseSettings() {+ const startOverState = useStartOver();+return (<><OptionsPageHeader />- <StartOverSection />++ {/* Above the card rather than under the button that caused it: a request left standing+ is the state of the whole page from here on, and the first thing its owner needs to+ know when they open this page again. */}+ {startOverState.pending && (+ <Admonition type="warning" className="start-over-pending">+ <p>{t("database.start_over_pending")}</p>++ <Button+ name="cancel-start-over-button"+ text={t("database.start_over_cancel")}+ size="micro"+ disabled={startOverState.busy}+ onClick={() => void startOverState.cancel()}+ />+ </Admonition>+ )}++ {/* Headingless: the row names the feature itself, and this card is to be folded into+ another one later. */}+ <div className="options-section start-over">+ <Card>+ <CardOption+ label={t("database.start_over")}+ description={t("database.start_over_description")}+ >+ <Button+ name="start-over-button"+ text={t("database.start_over")}+ icon="bx-reset"+ size="micro"+ disabled={startOverState.busy || startOverState.pending}+ onClick={() => void startOverState.begin()}+ />+ </CardOption>+ </Card>+ </div></>);}@@ -33,11 +71,11 @@ export default function DatabaseSettings() {* Going back to the setup screen, from where the knowledge base can be replaced.** Two shapes, decided by whether the instance can restart itself. The desktop and the browser-only- * build go there and then, so the button is the whole of it. A server is restarted by whoever runs- * it, so the request outlives the page that made it, and the section has to say that a start-over is- * waiting and offer to call it off.+ * build go there and then, so pressing the button is the whole of it. A server is restarted by+ * whoever runs it, so the request outlives the page that made it, and the page has to say that a+ * start-over is waiting and offer to call it off.*/-function StartOverSection() {+function useStartOver() {const [ pending, setPending ] = useState(false);const [ busy, setBusy ] = useState(false);@@ -49,7 +87,7 @@ function StartOverSection() {}void isStartOverPending().then(setPending).catch(() => {- // The section still works without knowing; the button is what matters here.+ // The page still works without knowing; the button is what it is for.});}, []);@@ -72,37 +110,5 @@ function StartOverSection() {}}- return (- <OptionsSection title={t("database.start_over_title")} className="start-over">- <p className="options-section-description">{t("database.start_over_description")}</p>-- {pending ? (- <>- <Admonition type="warning" className="start-over-pending">- {t("database.start_over_pending")}- </Admonition>-- <div className="start-over-actions">- <Button- name="cancel-start-over-button"- text={t("database.start_over_cancel")}- disabled={busy}- onClick={() => void cancel()}- />- </div>- </>- ) : (- <div className="start-over-actions">- <Button- name="start-over-button"- className="start-over-button"- icon="bx bx-reset"- text={t("database.start_over")}- disabled={busy}- onClick={() => void begin()}- />- </div>- )}- </OptionsSection>- );+ return { pending, busy, begin, cancel };}diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.tsindex 4d570c5fd7..84f40fbd3a 100644--- a/apps/desktop/src/services/window.spec.ts+++ b/apps/desktop/src/services/window.spec.ts@@ -10,6 +10,8 @@ const state = vi.hoisted(() => ({isWindows: false,isLinux: false,supportsBackgroundMaterial: false,+ /** Whether a `setup.json` marker sent this start to the wizard, rather than a first run. */+ isSetupRequested: false,appVersion: "1.0.0",options: {} as Record<string, string>,optionBools: {} as Record<string, boolean>,@@ -232,6 +234,7 @@ vi.mock("@triliumnext/core", async (importOriginal) => {getOptionBool: (name: string) => state.optionBools[name] ?? false},sql_init: { ...actual.sql_init, dbReady: Promise.resolve() },+ isSetupRequested: () => state.isSetupRequested,keyboard_actions: { ...actual.keyboard_actions, getKeyboardActions: () => state.keyboardActions },cls: { ...actual.cls, wrap: (fn: Handler) => fn },events: {@@ -285,6 +288,7 @@ beforeEach(() => {state.isWindows = false;state.isLinux = false;state.supportsBackgroundMaterial = false;+ state.isSetupRequested = false;state.appVersion = "1.0.0";state.options = { spellCheckLanguageCode: "en-US, de , " };state.optionBools = {};@@ -442,6 +446,28 @@ describe("window service", () => {const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;expect(opts.vibrancy).toBe("under-window");});++ it("names the window for what it is: getting started, or starting over", async () => {+ // Asserted as the resolved English rather than as the key, which also proves both+ // entries are really in the catalog the Electron main process reads.+ await windowService.createSetupWindow();+ expect((state.windows[state.windows.length - 1].opts as Record<string, unknown>).title)+ .toBe("Getting Started - Trilium Notes");++ state.isSetupRequested = true;+ await windowService.createSetupWindow();+ expect((state.windows[state.windows.length - 1].opts as Record<string, unknown>).title)+ .toBe("Start Over - Trilium Notes");+ });++ it("keeps that title, which the page it loads would otherwise replace with the app name", async () => {+ await windowService.createSetupWindow();+ const preventDefault = vi.fn();++ state.windows[state.windows.length - 1].fire("page-title-updated", { preventDefault });++ expect(preventDefault).toHaveBeenCalled();+ });});describe("getIcon (via createSetupWindow)", () => {diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.tsindex e5a42636f8..9e52a6a393 100644--- a/apps/desktop/src/services/window.ts+++ b/apps/desktop/src/services/window.ts@@ -1,7 +1,8 @@-import { app_info, cls, events, getLog, keyboard_actions as keyboardActionsService, options as optionService, sql_init, utils as coreUtils } from "@triliumnext/core";+import { app_info, cls, events, getLog, isSetupRequested, keyboard_actions as keyboardActionsService, options as optionService, sql_init, utils as coreUtils } from "@triliumnext/core";import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";import { supportsBackgroundMaterial } from "@triliumnext/server/src/services/utils.js";import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";+import { t } from "i18next";import path from "path";import { markStartupMetric } from "./startup_metrics.js";@@ -367,7 +368,11 @@ async function createSetupWindow() {useContentSize: true,resizable: false,autoHideMenuBar: true,- title: "Trilium Notes Setup",+ // What the window is for, which differs by how it was reached: a first run is getting the+ // user started, while an instance sent here by a marker is starting over on a knowledge base+ // it already has. Translated in the language the marker carried, which `initializeCore` has+ // already loaded by this point.+ title: isSetupRequested() ? t("setup-window.start-over") : t("setup-window.getting-started"),icon: getIcon(),// Background effects (Mica on Windows 11 22H2+, vibrancy on macOS)...(coreUtils.isWindows() && supportsBackgroundMaterial && { backgroundMaterial: "mica" as const }),@@ -379,6 +384,9 @@ async function createSetupWindow() {}});setupWindow.removeMenu();+ // The wizard is served by the application's own page, whose `<title>` Electron would otherwise+ // apply to the window the moment it loads, replacing the one set above with the plain app name.+ setupWindow.on("page-title-updated", (e) => e.preventDefault());setupWindow.loadURL(TRILIUM_APP_BASE_URL);setupWindow.on("closed", () => (setupWindow = null));}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 97abdede75..9b06f17ded 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -513,11 +513,15 @@"lan-access": "network access","lan-access-warning": "The app and your shared notes will be served over the network — reachable from a browser on this computer and from other devices on your local network."},+ "setup-window": {+ "getting-started": "Getting Started - Trilium Notes",+ "start-over": "Start Over - Trilium Notes"+ },"start-over-dialog": {"title": "Start over","message": "Restart Trilium and go back to the setup screen?","detail": "You will be offered a backup of your current knowledge base first. Nothing is deleted until you choose to create a new knowledge base, restore a backup or sync from another device.\n\nDo not continue if a script or an unfamiliar note prompted you to.","cancel": "Cancel",- "confirm": "Restart & start over"+ "confirm": "Restart and start over"}}