feat(documents): choose how the vault is laid out, and confirm every delete

The wrench beside Upload opens Settings, Appearance, Documents, the way
the illness journal offers its display options: preview cards or a
compact list, and months stacked as blocks or flowing across the full
width with the month name inline above the document that opens it. The
choice is stored per account in `users.documents_layout_json` behind
GET/PUT /api/documents/inbound/layout (preserve-when-absent, module
gated, the read delegable like the rest of the vault), carried in the
account-settings backup and cleared by the data wipe.

Deleting from the vault now always asks first. The bulk bar's Delete and
a focused card's Delete key both go through one confirmation on the page,
and the detail sheet's Delete opens its own; before, all three deleted on
the spot with only an undo toast behind them.

The selection bar is two tight lines: the count with an X at its right
edge, then one action row with Delete alone at the right in the
destructive style. Below 1024 px the verbs are icon-only at the 44 px tap
floor, so the row stays one line at 360 px. The bar carries the
selection-bar slot the Coach launcher already steps aside for.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 16:45:06 +02:00
1 parent ce6d2fe72a
commit 4273af231e
39 files changed
+1661 -209

No files matched your search

+1
View File
@@ -454,6 +454,7 @@ export const USER_RESET = {
dashboardWidgetsJson: Prisma.DbNull,
medicationListLayoutJson: Prisma.DbNull,
moodTagLayoutJson: Prisma.DbNull,
documentsLayoutJson: Prisma.DbNull,
reportSelectionJson: Prisma.DbNull,
modulePreferencesJson: Prisma.DbNull,
healthScoreConfigJson: Prisma.DbNull,
+70
View File
@@ -0,0 +1,70 @@
/**
* Document vault presentation — persisted in `User.documentsLayoutJson`.
*
* Two independent choices, both display-only:
*
* - `view`: `cards` is the monthly grid of preview tiles; `list` is one
* compact row per document.
* - `arrangement`: `stacked` gives every month its own block, one under the
* other; `flow` lets the documents run left to right across the full width
* and wrap, with each month's name riding inline as a small marker that does
* not break the run.
*
* Null / missing column = the defaults below (cards, stacked — the vault as it
* has always looked). The GET endpoint never lazy-writes, so the column only
* carries data once the user has changed one of the two. Mirrors
* `medication-list-layout.ts`: tolerant resolver on read, normaliser on write,
* preserve-when-absent PUT (see the route).
*/
export const DOCUMENTS_LAYOUT_VIEWS = ["cards", "list"] as const;
export type DocumentsLayoutView = (typeof DOCUMENTS_LAYOUT_VIEWS)[number];
export const DOCUMENTS_LAYOUT_ARRANGEMENTS = ["stacked", "flow"] as const;
export type DocumentsLayoutArrangement =
(typeof DOCUMENTS_LAYOUT_ARRANGEMENTS)[number];
export interface DocumentsLayout {
version: 1;
view: DocumentsLayoutView;
arrangement: DocumentsLayoutArrangement;
}
export const DEFAULT_DOCUMENTS_LAYOUT: DocumentsLayout = {
version: 1,
view: "cards",
arrangement: "stacked",
};
function isView(value: unknown): value is DocumentsLayoutView {
return (
typeof value === "string" &&
(DOCUMENTS_LAYOUT_VIEWS as readonly string[]).includes(value)
);
}
function isArrangement(value: unknown): value is DocumentsLayoutArrangement {
return (
typeof value === "string" &&
(DOCUMENTS_LAYOUT_ARRANGEMENTS as readonly string[]).includes(value)
);
}
/**
* Any malformed, partial or legacy blob collapses onto the defaults field by
* field, so a GET never fails on a stored row and a field added later
* defaults cleanly for blobs written before it existed.
*/
export function resolveDocumentsLayout(raw: unknown): DocumentsLayout {
if (raw === null || raw === undefined || typeof raw !== "object") {
return { ...DEFAULT_DOCUMENTS_LAYOUT };
}
const blob = raw as { view?: unknown; arrangement?: unknown };
return {
version: 1,
view: isView(blob.view) ? blob.view : DEFAULT_DOCUMENTS_LAYOUT.view,
arrangement: isArrangement(blob.arrangement)
? blob.arrangement
: DEFAULT_DOCUMENTS_LAYOUT.arrangement,
};
}
@@ -524,6 +524,7 @@ const ACCOUNT_SETTING_CODECS: Readonly<
insightsLayoutJson: json("insightsLayoutJson"),
medicationListLayoutJson: json("medicationListLayoutJson"),
moodTagLayoutJson: json("moodTagLayoutJson"),
documentsLayoutJson: json("documentsLayoutJson"),
reportSelectionJson: json("reportSelectionJson"),
globalExcludedInjectionSites: excludedSites,
healthKitConfigJson: json("healthKitConfigJson"),
+1
View File
@@ -950,6 +950,7 @@ export const USER_COLUMN_BACKUP_CLASS = {
insightsLayoutJson: "SETTING",
medicationListLayoutJson: "SETTING",
moodTagLayoutJson: "SETTING",
documentsLayoutJson: "SETTING",
reportSelectionJson: "SETTING",
globalExcludedInjectionSites: "SETTING",
healthKitConfigJson: "SETTING",
+1
View File
@@ -200,6 +200,7 @@ const STATIC_SURFACE_MODULE = {
"settings-layout:mood": "mood",
"settings-layout:labs": "labs",
"settings-layout:illness": "illness",
"settings-layout:documents": "inboundDocuments",
// ── Correlation channels ──
// Rated mood factors (`FACTOR:<key>`) are mood's too; see
+86
View File
@@ -30,6 +30,10 @@ import {
INBOUND_DOCUMENT_KINDS,
INBOUND_DOCUMENT_STATUSES,
} from "@/lib/validations/inbound-documents";
import {
DOCUMENTS_LAYOUT_ARRANGEMENTS,
DOCUMENTS_LAYOUT_VIEWS,
} from "@/lib/documents/documents-layout";
import { aiExtractionRefusals } from "./ai-extraction-refusals";
import { aiRunAccepted, preferRespondAsyncParameter } from "./ai-run-accepted";
@@ -44,6 +48,41 @@ import {
} from "./shared";
const kindEnum = z.enum(INBOUND_DOCUMENT_KINDS);
// ─── Vault presentation (v1.42) ────────────────────────────────────────────
const documentsLayoutSchema = z
.object({
version: z.literal(1),
view: z
.enum(DOCUMENTS_LAYOUT_VIEWS)
.describe(
'`cards` renders the preview-tile grid, `list` one compact row per document. Default "cards".',
),
arrangement: z
.enum(DOCUMENTS_LAYOUT_ARRANGEMENTS)
.describe(
'`stacked` gives every month its own block; `flow` runs the documents across the full width and wraps, with month names inline. Default "stacked".',
),
})
.meta({
id: "DocumentsLayout",
description:
"Per-user document vault presentation. Display-only; a client that does not render a vault ignores it.",
});
const documentsLayoutPutBody = z
.object({
version: z.literal(1),
view: z.enum(DOCUMENTS_LAYOUT_VIEWS).optional(),
arrangement: z.enum(DOCUMENTS_LAYOUT_ARRANGEMENTS).optional(),
})
.strict()
.meta({
id: "DocumentsLayoutPutBody",
description:
"Either field may be omitted; the stored value is kept for the one left out.",
});
const statusEnum = z.enum(INBOUND_DOCUMENT_STATUSES);
// ─── Chat about a document (P4) — response shapes ──────────────────────────
@@ -719,6 +758,53 @@ export const inboundDocumentPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/documents/inbound/layout": {
get: {
tags: ["Documents"],
summary: "Get the vault presentation",
description:
"The resolved card/list view and month arrangement for the vault, with defaults filled in when nothing has been chosen. Inside a shared record this answers the owner's choice.",
responses: {
...recordRefusal(),
"200": {
description: "The resolved presentation.",
content: {
"application/json": {
schema: dataEnvelope(
documentsLayoutSchema,
"DocumentsLayoutEnvelope",
),
},
},
},
...stdResponses,
},
},
put: {
tags: ["Documents"],
summary: "Change the vault presentation",
description:
"Preserve-when-absent: a body carrying only `view` keeps the stored arrangement and vice versa. Returns the full resolved presentation. Refused while acting inside somebody else's record.",
requestBody: {
required: true,
content: { "application/json": { schema: documentsLayoutPutBody } },
},
responses: {
"200": {
description: "The presentation as stored.",
content: {
"application/json": {
schema: dataEnvelope(
documentsLayoutSchema,
"DocumentsLayoutSavedEnvelope",
),
},
},
},
...stdResponses,
},
},
},
"/api/documents/inbound/bulk": {
post: {
tags: ["Documents"],
@@ -0,0 +1,85 @@
/**
* The vault presentation switch: field-scoped PUT, optimistic cache flip,
* rollback and a toast when the save fails. Exercised through the
* dependency-injected `runSetDocumentsLayout`, without a React render.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient } from "@tanstack/react-query";
vi.mock("@/lib/api/api-fetch", () => ({
apiGet: vi.fn(),
apiPut: vi.fn(),
}));
vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
}));
import { apiPut } from "@/lib/api/api-fetch";
import { toast } from "sonner";
import { runSetDocumentsLayout } from "@/lib/queries/use-documents-layout";
import { queryKeys } from "@/lib/query-keys";
import type { DocumentsLayout } from "@/lib/documents/documents-layout";
const t = (key: string) => key;
const key = queryKeys.documentsLayout();
const STORED: DocumentsLayout = {
version: 1,
view: "cards",
arrangement: "stacked",
};
beforeEach(() => {
vi.resetAllMocks();
});
describe("runSetDocumentsLayout", () => {
it("sends only the field that changed and keeps the server's answer", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(key, STORED);
const saved: DocumentsLayout = { ...STORED, arrangement: "flow" };
vi.mocked(apiPut).mockResolvedValue(saved);
await runSetDocumentsLayout({
patch: { arrangement: "flow" },
queryClient,
t,
});
expect(apiPut).toHaveBeenCalledWith("/api/documents/inbound/layout", {
version: 1,
arrangement: "flow",
});
expect(queryClient.getQueryData(key)).toEqual(saved);
});
it("flips the cache before the save lands", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(key, STORED);
let settle: (value: DocumentsLayout) => void = () => {};
vi.mocked(apiPut).mockReturnValue(
new Promise<DocumentsLayout>((resolve) => {
settle = resolve;
}),
);
const run = runSetDocumentsLayout({
patch: { view: "list" },
queryClient,
t,
});
expect(queryClient.getQueryData<DocumentsLayout>(key)?.view).toBe("list");
settle({ ...STORED, view: "list" });
await run;
});
it("rolls back and says so when the save fails", async () => {
const queryClient = new QueryClient();
queryClient.setQueryData(key, STORED);
vi.mocked(apiPut).mockRejectedValue(new Error("offline"));
await runSetDocumentsLayout({ patch: { view: "list" }, queryClient, t });
expect(queryClient.getQueryData(key)).toEqual(STORED);
expect(toast.error).toHaveBeenCalledWith("documents.layout.saveFailed");
});
});
+85
View File
@@ -0,0 +1,85 @@
"use client";
import {
useQuery,
useQueryClient,
type QueryClient,
} from "@tanstack/react-query";
import { toast } from "sonner";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
import {
DEFAULT_DOCUMENTS_LAYOUT,
type DocumentsLayout,
type DocumentsLayoutArrangement,
type DocumentsLayoutView,
} from "@/lib/documents/documents-layout";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
type Translator = (
key: string,
params?: Record<string, string | number>,
) => string;
type LayoutPatch = {
view?: DocumentsLayoutView;
arrangement?: DocumentsLayoutArrangement;
};
/**
* Apply one field optimistically (the switch has to feel instant), then
* persist it. The PUT is field-scoped, so a view change never resets the
* arrangement and vice versa. On failure the cache rolls back and a calm
* toast says so.
*/
export async function runSetDocumentsLayout(deps: {
patch: LayoutPatch;
queryClient: QueryClient;
t: Translator;
}): Promise<void> {
const { patch, queryClient, t } = deps;
const key = queryKeys.documentsLayout();
const previous = queryClient.getQueryData<DocumentsLayout>(key);
queryClient.setQueryData<DocumentsLayout>(key, {
...(previous ?? DEFAULT_DOCUMENTS_LAYOUT),
...patch,
});
try {
const saved = await apiPut<DocumentsLayout>(
"/api/documents/inbound/layout",
{ version: 1, ...patch },
);
if (saved) queryClient.setQueryData(key, saved);
} catch {
queryClient.setQueryData(key, previous);
toast.error(t("documents.layout.saveFailed"));
}
}
/** The vault presentation, persisted per user. Defaults until the read lands. */
export function useDocumentsLayout(enabled: boolean = true): {
layout: DocumentsLayout;
isLayoutLoading: boolean;
setView: (view: DocumentsLayoutView) => Promise<void>;
setArrangement: (arrangement: DocumentsLayoutArrangement) => Promise<void>;
} {
const queryClient = useQueryClient();
const { t } = useTranslations();
const { data, isLoading } = useQuery({
queryKey: queryKeys.documentsLayout(),
queryFn: () => apiGet<DocumentsLayout>("/api/documents/inbound/layout"),
staleTime: 5 * 60 * 1000,
enabled,
});
return {
layout: data ?? DEFAULT_DOCUMENTS_LAYOUT,
isLayoutLoading: enabled && isLoading,
setView: (view) =>
runSetDocumentsLayout({ patch: { view }, queryClient, t }),
setArrangement: (arrangement) =>
runSetDocumentsLayout({ patch: { arrangement }, queryClient, t }),
};
}
+6
View File
@@ -30,6 +30,12 @@ export interface DocumentVaultFilters {
export const documentKeys = {
documents: () => ["documents"] as const,
/**
* The vault presentation (view + month arrangement). Deliberately outside
* the `["documents"]` prefix: a document write changes nothing about how
* the vault is laid out, so it must not refetch this.
*/
documentsLayout: () => ["documents-layout"] as const,
inboundDocuments: () => ["documents", "inbound"] as const,
/**
* The parameterised vault list (keyset-paginated via `useInfiniteQuery`).
+1
View File
@@ -2008,6 +2008,7 @@ const accountSettingsBackupSchema = z
insightsLayoutJson: z.unknown().optional(),
medicationListLayoutJson: z.unknown().optional(),
moodTagLayoutJson: z.unknown().optional(),
documentsLayoutJson: z.unknown().optional(),
reportSelectionJson: z.unknown().optional(),
globalExcludedInjectionSites: z.array(z.string()).optional(),
healthKitConfigJson: z.unknown().optional(),