Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(modal): add a wizard modal and move the provider dialog onto it
Elian Doran84cde01f3514
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e019eb8847..761a2bf664 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2773,6 +2773,11 @@"cancel": "Cancel","help_title": "Display more information about this screen"},+ "wizard": {+ "back": "Back",+ "next": "Next",+ "step_progress": "Step {{current}} of {{total}}"+ },"call_to_action": {"next_theme_title": "Try the new Trilium theme","next_theme_message": "You are currently using the legacy theme, would you like to try the new theme?",@@ -3140,8 +3145,6 @@"add_provider_title": "Add AI Provider","edit_provider_title": "Edit {{name}}","edit_provider": "Edit",- "next": "Next",- "back": "Back","save": "Save","select_models": "Select models","models_loading": "Loading models…",@@ -3191,7 +3194,6 @@"troubleshoot_server_running": "Is the server running on the machine you expect?","troubleshoot_port": "Does the port in the URL match the one the server reports?","troubleshoot_remote": "If the server is on another machine, is it configured to accept connections from the network rather than localhost only?",- "cancel": "Cancel","mcp_title": "MCP (Model Context Protocol)","mcp_enabled": "MCP server","mcp_enabled_description": "Expose a Model Context Protocol (MCP) endpoint so that AI coding assistants (e.g. Claude Code, GitHub Copilot) can read and modify your notes. The endpoint is only accessible from localhost.",diff --git a/apps/client/src/widgets/react/WizardModal.css b/apps/client/src/widgets/react/WizardModal.cssnew file mode 100644index 0000000000..b03fb16592--- /dev/null+++ b/apps/client/src/widgets/react/WizardModal.css@@ -0,0 +1,50 @@+.modal.wizard-modal {+ /**+ * The frame the wizard keeps across its steps: set `--wizard-body-height` on the+ * dialog to fit its content — enough that the shortest step doesn't look hollow,+ * and that the longest needs only a little scrolling.+ *+ * The default lives in the `var()` fallback rather than in a declaration here.+ * A declaration would be `(0,2,0)`, the same as the `.modal.<dialog>` rule a+ * consumer writes, so source order would decide — and this file is imported by+ * the component, i.e. after the dialog's own stylesheet, which would leave the+ * default quietly overriding every value anyone sets.+ *+ * A height rather than a min-height, so a step with a long list scrolls inside the+ * frame instead of stretching it, and a step with one field leaves the footer+ * exactly where the previous step had it. `.modal-body` still shrinks (it is a+ * flex item that scrolls), so a short viewport caps this via Bootstrap's+ * scrollable chain rather than pushing the footer off-screen.+ */+ .modal-body {+ height: var(--wizard-body-height, 30rem);+ }++ /* How far along, next to the close button — the title already says what the step+ is, so this only has to answer "how much is left". */+ .wizard-progress {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-inline-start: auto;+ margin-inline-end: 12px;+ }++ .wizard-progress-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background-color: var(--muted-text-color);+ opacity: 0.35;+ }++ /* Steps already walked through stay legible but recede; the current one is solid. */+ .wizard-progress-dot.visited {+ opacity: 0.6;+ }++ .wizard-progress-dot.current {+ background-color: var(--main-text-color);+ opacity: 1;+ }+}diff --git a/apps/client/src/widgets/react/WizardModal.spec.ts b/apps/client/src/widgets/react/WizardModal.spec.tsnew file mode 100644index 0000000000..450e7218da--- /dev/null+++ b/apps/client/src/widgets/react/WizardModal.spec.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";++import { wizardNavigation } from "./WizardModal";++const STEPS = ["provider", "connection", "models"];++describe("wizardNavigation", () => {+ it("walks the steps, turning Back into Cancel at the start and Next into Finish at the end", () => {+ expect(wizardNavigation(STEPS, "provider")).toMatchObject({+ index: 0, previousStep: undefined, nextStep: "connection", position: 1, total: 3+ });+ expect(wizardNavigation(STEPS, "connection")).toMatchObject({+ index: 1, previousStep: "provider", nextStep: "models", position: 2, total: 3+ });+ expect(wizardNavigation(STEPS, "models")).toMatchObject({+ index: 2, previousStep: "connection", nextStep: undefined, position: 3, total: 3+ });+ });++ it("hides the steps before the entry step, which the user could never have walked to", () => {+ // Reopening a wizard over its own result: the earlier choices are fixed, so+ // Back must not offer them and the progress must not count them.+ expect(wizardNavigation(STEPS, "connection", "connection")).toMatchObject({+ previousStep: undefined, nextStep: "models", position: 1, total: 2+ });+ expect(wizardNavigation(STEPS, "models", "connection")).toMatchObject({+ previousStep: "connection", position: 2, total: 2+ });+ // A single reachable step: no Back, no progress to show (the component hides+ // the dots at a total of one), and the primary action finishes straight away.+ expect(wizardNavigation(STEPS, "models", "models")).toMatchObject({+ previousStep: undefined, nextStep: undefined, position: 1, total: 1+ });+ });++ it("clamps a step it cannot place instead of leaving the dialog with nothing to render", () => {+ // Unknown id, and an id before the entry step — both would otherwise index+ // past the ends of the list.+ expect(wizardNavigation(STEPS, "nonexistent")).toMatchObject({ index: 0, position: 1 });+ expect(wizardNavigation(STEPS, "nonexistent", "connection")).toMatchObject({ index: 1, position: 1 });+ expect(wizardNavigation(STEPS, "provider", "connection")).toMatchObject({+ index: 1, previousStep: undefined, position: 1+ });+ // An entry step that isn't in the list falls back to the first one.+ expect(wizardNavigation(STEPS, "connection", "nonexistent")).toMatchObject({ index: 1, previousStep: "provider", total: 3 });+ });++ it("survives a single step and an empty list", () => {+ expect(wizardNavigation(["only"], "only")).toMatchObject({+ index: 0, previousStep: undefined, nextStep: undefined, position: 1, total: 1+ });+ // Nothing to render; the component bails on the missing step rather than throwing.+ expect(wizardNavigation([], "whatever").index).toBe(0);+ });+});diff --git a/apps/client/src/widgets/react/WizardModal.tsx b/apps/client/src/widgets/react/WizardModal.tsxnew file mode 100644index 0000000000..7df3c048c4--- /dev/null+++ b/apps/client/src/widgets/react/WizardModal.tsx@@ -0,0 +1,162 @@+import "./WizardModal.css";++import clsx from "clsx";+import type { ComponentChildren } from "preact";++import { t } from "../../services/i18n";+import Button from "./Button";+import Modal, { type ModalProps } from "./Modal";++export interface WizardStep<Id extends string = string> {+ id: Id;+ /** The modal's title while this step is shown. */+ title: string;+ content: ComponentChildren;+ /**+ * Whether the wizard may leave this step, blocking both the primary button and+ * Enter. Defaults to `true`.+ */+ canContinue?: boolean;+ /**+ * Hides the primary button because the step commits itself — picking one of a set+ * of cards, say, where "Next" would only be a second way to do what the click has+ * already done. Enter still advances, subject to {@link canContinue}, so the+ * keyboard path doesn't dead-end.+ */+ autoAdvance?: boolean;+ /** Primary button label, where neither "Next" nor the wizard's finish label fits. */+ nextLabel?: string;+}++export interface WizardModalProps<Id extends string>+ extends Pick<ModalProps, "size" | "maxWidth" | "minWidth" | "show" | "stackable" | "helpPageId" | "zIndex" | "onHidden" | "onShown"> {+ className?: string;+ /** In the order they are visited. Must not be empty. */+ steps: WizardStep<Id>[];+ /** The step being shown. The wizard is controlled: the caller owns this. */+ step: Id;+ onStepChange: (step: Id) => void;+ /**+ * The step the wizard opened on. Everything before it is unreachable and Back+ * turns into Cancel there, which is how a wizard reopened over its own result+ * skips the choices that are already fixed. Defaults to the first step.+ */+ entryStep?: Id;+ /** Primary button label on the last step, e.g. "Add provider". */+ finishLabel: string;+ /** The last step's primary action. */+ onFinish: () => void;+}++/**+ * A modal that walks through a fixed sequence of steps, keeping one frame while it+ * does: the body holds a constant height and scrolls, so Back and Next stay put+ * instead of jumping as a step with a long list gives way to one with a single+ * field. Set `--wizard-body-height` on the modal to size that frame for the content+ * (see the stylesheet).+ *+ * The wizard owns only the navigation — which step is next, whether Back exists,+ * what the buttons say. Everything else stays with the caller, including the step+ * state itself, so that a step can advance on its own (see {@link WizardStep.autoAdvance}).+ */+export default function WizardModal<Id extends string>({+ steps, step, onStepChange, entryStep, finishLabel, onFinish, className, onHidden, ...modalProps+}: WizardModalProps<Id>) {+ const { index, previousStep, nextStep, position, total } = wizardNavigation(steps.map(s => s.id), step, entryStep);+ const current = steps[index];+ if (!current) {+ return null;+ }+ const canContinue = current.canContinue ?? true;++ function submit() {+ if (!canContinue) {+ return;+ }+ if (nextStep) {+ onStepChange(nextStep);+ } else {+ onFinish();+ }+ }++ return (+ <Modal+ {...modalProps}+ className={clsx("wizard-modal", className)}+ title={current.title}+ onHidden={onHidden}+ onSubmit={submit}+ // The constant body height is what keeps the frame still; scrolling is how+ // a step taller than that frame stays reachable.+ scrollable+ header={total > 1 && <WizardProgress position={position} total={total} />}+ footer={<>+ <Button+ text={previousStep ? t("wizard.back") : t("modal.cancel")}+ onClick={previousStep ? () => onStepChange(previousStep) : onHidden}+ />+ {!current.autoAdvance && (+ <Button+ kind="primary"+ disabled={!canContinue}+ text={current.nextLabel ?? (nextStep ? t("wizard.next") : finishLabel)}+ />+ )}+ </>}+ >+ {current.content}+ </Modal>+ );+}++/**+ * Where the wizard stands: the steps either side of the current one, and its place+ * among those that can actually be reached. Split out from the component because it+ * is the whole of the navigation logic and is worth testing without a DOM.+ *+ * Both ids are clamped rather than trusted: an id outside the list — or one before+ * the entry step, which the user could never have walked to — would otherwise leave+ * the dialog with no content to render.+ */+export function wizardNavigation<Id extends string>(stepIds: Id[], step: Id, entryStep?: Id) {+ const lastIndex = stepIds.length - 1;+ // `clamp` guards the empty-list case too, where lastIndex is -1.+ const clamp = (value: number) => Math.min(Math.max(value, 0), Math.max(lastIndex, 0));+ const entryIndex = clamp(entryStep ? stepIds.indexOf(entryStep) : 0);+ const index = clamp(Math.max(stepIds.indexOf(step), entryIndex));++ return {+ index,+ /** The step Back returns to, or undefined where Back becomes Cancel. */+ previousStep: index > entryIndex ? stepIds[index - 1] : undefined,+ /** The step the primary button advances to, or undefined on the last one (where it finishes). */+ nextStep: index < lastIndex ? stepIds[index + 1] : undefined,+ /** 1-based position among the reachable steps. */+ position: index - entryIndex + 1,+ /** How many steps are reachable from where the wizard opened. */+ total: stepIds.length - entryIndex+ };+}++/**+ * How far along the wizard is, shown beside the title. Dots rather than "2 of 3" so+ * it stays a glance rather than something to read, with the count left to the label+ * screen readers get.+ */+function WizardProgress({ position, total }: { position: number; total: number }) {+ return (+ <div+ className="wizard-progress"+ role="progressbar"+ aria-valuemin={1}+ aria-valuemax={total}+ aria-valuenow={position}+ aria-label={t("wizard.step_progress", { current: position, total })}+ >+ {Array.from({ length: total }, (_, i) => (+ <span key={i} className={clsx("wizard-progress-dot", { current: i + 1 === position, visited: i + 1 < position })} />+ ))}+ </div>+ );+}diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.cssindex 8cd6eb53ab..57a6896598 100644--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css@@ -1,4 +1,12 @@.modal.add-provider-modal {+ /* Sized against the three steps, which trade off one for one: every pixel of frame+ is a pixel less scrolling in the provider list (far the tallest — four group+ cards, seven rows) and a pixel more empty space under the connection step (the+ shortest — a logo and one or two fields). This sits nearer the tall end because+ the model list, whose length isn't known until it loads, is the step that most+ wants the room. */+ --wizard-body-height: 40rem;+.tn-card {margin-bottom: 1rem;}diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsxindex d7d54f017a..dd813f044f 100644--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx@@ -2,7 +2,7 @@ import "./AddProviderModal.css";import type { LlmModelInfo } from "@triliumnext/commons";import { createPortal } from "preact/compat";-import { useMemo, useRef, useState } from "preact/hooks";+import { useMemo, useState } from "preact/hooks";import { Trans } from "react-i18next";import { t } from "../../../../services/i18n";@@ -10,8 +10,8 @@ import { Badge } from "../../../react/Badge";import { Card, CardSection } from "../../../react/Card";import FormTextBox from "../../../react/FormTextBox";import MaskedIcon from "../../../react/MaskedIcon";-import Modal from "../../../react/Modal";import SelectableCard, { SelectableCardGrid } from "../../../react/SelectableCard";+import WizardModal, { type WizardStep } from "../../../react/WizardModal";import OptionsRow from "../components/OptionsRow";import anthropicIcon from "./icons/anthropic.svg?url";import claudeAgentIcon from "./icons/claude-ai.svg?url";@@ -155,7 +155,6 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProviconst [apiKey, setApiKey] = useState(existingProvider?.apiKey ?? "");const [baseUrl, setBaseUrl] = useState(existingProvider?.baseURL ?? prefilledBaseUrl(existingProvider?.provider ?? PROVIDER_TYPES[0].id));const [selectedModels, setSelectedModels] = useState<LlmModelInfo[]>(existingProvider?.selectedModels ?? []);- const formRef = useRef<HTMLFormElement>(null);const providerType = useMemo(() => PROVIDER_TYPES.find(p => p.id === selectedProvider),@@ -236,22 +235,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvionHidden();}- function handleSubmit() {- if (step === "provider") {- // Enter with nothing picked yet must not silently advance with whichever- // provider happens to be first in the list.- if (providerChosen) {- setStep("connection");- }- return;- }- if (step === "connection") {- if (connectionValid) {- setStep("models");- }- return;- }-+ function handleFinish() {const saved: LlmProviderConfig = {id: existingProvider?.id ?? `${selectedProvider}_${Date.now()}`,name: providerType?.name || selectedProvider,@@ -268,57 +252,20 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi// Past the picker the cards are gone, so the title carries which provider is// being set up.- const title = isEdit+ const namedTitle = isEdit? t("llm.edit_provider_title", { name: existingProvider?.name ?? providerType?.name ?? selectedProvider })- : step === "provider"- ? t("llm.add_provider_title")- : t("llm.add_provider_title_named", { name: providerType?.name ?? selectedProvider });- const primaryLabel = step === "models"- ? (isEdit ? t("llm.save") : t("llm.add_provider"))- : t("llm.next");- // The models step never disables Save: an empty selection is valid (hides all- // of the provider's models, same as a pre-selection migration), and it avoids- // a dead-end when the live model fetch fails.- const primaryDisabled = step === "connection" && !connectionValid;- // Back retraces the steps this modal actually opened with: editing starts at- // the connection details (the provider type of a saved config is fixed), so- // there is nothing behind it to go back to.- const previousStep = step === "models" ? "connection" : step === "connection" ? "provider" : undefined;- const canGoBack = previousStep !== undefined && !(previousStep === "provider" && firstStep !== "provider");+ : t("llm.add_provider_title_named", { name: providerType?.name ?? selectedProvider });- return createPortal(- <Modal- show={show}- onHidden={handleCancel}- onSubmit={handleSubmit}- formRef={formRef}- title={title}- className="add-provider-modal"- size="md"- maxWidth={600}- stackable- // The provider list is the tallest step and grows with every provider- // added, so scroll the body rather than pushing the footer off-screen.- scrollable- footer={- <>- <button- type="button"- className="btn btn-secondary"- onClick={canGoBack && previousStep ? () => setStep(previousStep) : handleCancel}- >- {canGoBack ? t("llm.back") : t("llm.cancel")}- </button>- {/* Choosing a card advances on its own, so the provider step needs no primary action. */}- {step !== "provider" && (- <button type="submit" className="btn btn-primary" disabled={primaryDisabled}>- {primaryLabel}- </button>- )}- </>- }- >- {step === "provider" ? (+ const steps: WizardStep<ProviderStep>[] = [+ {+ id: "provider",+ title: t("llm.add_provider_title"),+ // Choosing a card advances on its own, so the step needs no primary action —+ // but Enter must still not advance with whichever provider happens to be+ // first in the list, hence the guard.+ autoAdvance: true,+ canContinue: providerChosen,+ content: (// One card per group rather than one "Provider" card holding them all:// the groups are the step's structure, so each gets the heading and the// enclosure, and the choices below it are only the ones it describes.@@ -332,7 +279,13 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvionSelect={selectProviderType}/>))- ) : step === "connection" ? (+ )+ },+ {+ id: "connection",+ title: namedTitle,+ canContinue: connectionValid,+ content: (<>{providerType && <ProviderIllustration providerType={providerType} />}@@ -367,7 +320,15 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi</CardSection></Card></>- ) : (+ )+ },+ {+ id: "models",+ title: namedTitle,+ // Never blocked: an empty selection is valid (it hides all of the provider's+ // models, same as a pre-selection migration), and allowing it avoids a+ // dead-end when the live model fetch fails.+ content: (<Card heading={t("llm.select_models")}><CardSection><ModelSelection@@ -382,8 +343,27 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi/></CardSection></Card>- )}- </Modal>,+ )+ }+ ];++ return createPortal(+ <WizardModal+ show={show}+ onHidden={handleCancel}+ steps={steps}+ step={step}+ onStepChange={setStep}+ // Editing starts at the connection details — the provider type of a saved+ // config is fixed — so the picker behind it is not somewhere Back can go.+ entryStep={firstStep}+ finishLabel={isEdit ? t("llm.save") : t("llm.add_provider")}+ onFinish={handleFinish}+ className="add-provider-modal"+ size="md"+ maxWidth={600}+ stackable+ />,document.body);}