From 69c8d07b827a21e1279802d527707368b1682dd8 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 09:58:45 +0100 Subject: [PATCH 01/41] feat(interface): add the Matrix block contract A grid of rows by columns edited in place, meant to cover the records grid of dms-database, the translation matrix of dms-lang and quantity grids by size and store. Contract only: options, data and save shapes, block registration. --- .../interface-dms/src/base/block-types.ts | 1 + packages/interface-dms/src/base/index.ts | 1 + packages/interface-dms/src/base/matrix.ts | 693 ++++++++++++++++++ 3 files changed, 695 insertions(+) create mode 100644 packages/interface-dms/src/base/matrix.ts diff --git a/packages/interface-dms/src/base/block-types.ts b/packages/interface-dms/src/base/block-types.ts index e3bcb34b3..8fd7b2705 100644 --- a/packages/interface-dms/src/base/block-types.ts +++ b/packages/interface-dms/src/base/block-types.ts @@ -23,6 +23,7 @@ import "./guard"; import "./key-value-list"; import "./kpi-card"; import "./live-toggle"; +import "./matrix"; import "./meter"; import "./nav-card-grid"; import "./page-toolbar"; diff --git a/packages/interface-dms/src/base/index.ts b/packages/interface-dms/src/base/index.ts index c66a7a13b..16944b399 100644 --- a/packages/interface-dms/src/base/index.ts +++ b/packages/interface-dms/src/base/index.ts @@ -27,6 +27,7 @@ export * from "./key-value-list"; export * from "./kpi-card"; export * from "./layouts"; export * from "./live-toggle"; +export * from "./matrix"; export * from "./meter"; export * from "./nav-card-grid"; export * from "./page-toolbar"; diff --git a/packages/interface-dms/src/base/matrix.ts b/packages/interface-dms/src/base/matrix.ts new file mode 100644 index 000000000..ef95e62d3 --- /dev/null +++ b/packages/interface-dms/src/base/matrix.ts @@ -0,0 +1,693 @@ +import { ComponentBuilder } from "../component"; +import { z } from "zod"; +import { + type BlockOptionsFor, + opaqueOption, + RegisterBlockType, + ui, +} from "./block-registry"; +import { blockRealtimeTopicOption } from "./display"; +import { attachRealtimeTopicsHook } from "./internal/realtime-topics"; +import type { ColumnDisplaySerialized } from "./table-view/column-display"; +import type { + ActionTarget, + ActionTargetSerialized, +} from "./types/action-target"; +import { serializeActionTarget } from "./types/internal/action-target"; +import type { BlockText } from "./types/composed-text"; +import { HttpMethod } from "./types/http"; +import type { Tone } from "./types/tone"; +import type { BaseComponentProps, EnumOption } from "./types"; + +/** + * What a cell holds, which picks the input that edits it and how it is drawn. + * Each kind is edited with the DMS form input of the matching data type + * (`text` → InputText, `json` → InputCode in JSON, `richText` → RichText...), + * so a cell edits exactly like the same field in a `Form`. + */ +export const MATRIX_CELL_KINDS = [ + "text", + "longText", + "number", + "boolean", + "date", + "select", + "tags", + "json", + "code", + "richText", + "keyValue", + "address", +] as const; + +export type MatrixCellKind = (typeof MATRIX_CELL_KINDS)[number]; + +/** + * The kinds edited in a drawer by default (`editIn: "auto"`), never in the + * cell: a value a one-line cell cannot show or take whole. A `longText` and a + * `text` cell go to the drawer too once their value holds a line break or + * passes {@link MATRIX_LONG_TEXT_LENGTH} characters. + */ +export const MATRIX_PANEL_KINDS: readonly MatrixCellKind[] = [ + "json", + "code", + "richText", + "keyValue", + "address", +]; + +/** Past this length, an `auto` text cell is edited in the drawer. */ +export const MATRIX_LONG_TEXT_LENGTH = 120; + +/** Where a cell is edited: in place, in a drawer holding that cell alone, or picked by its kind and value. */ +export type MatrixEditIn = "cell" | "panel" | "auto"; + +/** How a cell enters editing. */ +export type MatrixEditTrigger = "click" | "doubleClick"; + +/** + * When an edit reaches the server. `immediate` writes each cell as it is left + * (Saving → Saved, Retry on failure); `staged` keeps the edits, shows the old + * value struck through, and writes them together from a save bar. + */ +export type MatrixSaveMode = "immediate" | "staged"; + +/** Where Enter moves after saving a cell. */ +export type MatrixEnterMove = "down" | "right" | "stay"; + +/** + * `overwrite`: the last write wins. `detect`: each change carries the value + * the edit started from (`previous`); the route answers a conflict when the + * stored value moved, and the cell offers Overwrite or Discard. + */ +export type MatrixConflictMode = "overwrite" | "detect"; + +/** How many rows the grid reads at a time. */ +export type MatrixPagination = "none" | "pages" | "infinite"; + +/** The tones a cell, a row or a select option may take. */ +export type MatrixTone = Extract< + Tone, + "neutral" | "primary" | "success" | "warning" | "error" | "info" +>; + +/** A choice of a `select` or `tags` column. */ +export interface MatrixSelectOption { + value: string; + label: BlockText; + /** The pill the value is drawn as (a roster's "Off" in neutral, "Sick" in error). */ + tone?: MatrixTone; + icon?: string; +} + +/** + * One column. Columns come from the block's `columns` option, from the + * response's `columns`, or both: the response wins for an id both declare, + * and adds the ones it alone names (languages of a workspace, sizes of an + * article, fields of a collection). + */ +export interface MatrixColumn { + id: string; + label: BlockText; + /** Defaults to `text`. */ + kind?: MatrixCellKind; + icon?: string; + /** Dimmed line under the label, also its tooltip. */ + description?: BlockText; + /** Width in pixels. */ + width?: number; + /** `false` keeps the column read-only in an editable grid. */ + editable?: boolean; + /** Defaults to `auto`: see {@link MATRIX_PANEL_KINDS}. */ + editIn?: MatrixEditIn; + /** The choices of a `select` or `tags` column. */ + options?: MatrixSelectOption[]; + /** The language of a `code` column (`sql`, `html`...). */ + language?: string; + min?: number; + max?: number; + step?: number; + /** A `number` column taking whole numbers only (quantities). */ + integer?: boolean; + /** Offers "Set to null"; typing `null` empties the cell. */ + nullable?: boolean; + /** An empty value is refused before it is sent. */ + required?: boolean; + /** Left out of the row totals (an annex column, a price). Numbers count by default. */ + excludeFromTotals?: boolean; + align?: "start" | "center" | "end"; + /** + * A table view cell display drawing the value when it is not edited + * (`DefaultDisplays.StatusPillDisplay`, a module's own display), serialized + * as a column's `display`. + */ + display?: ColumnDisplaySerialized; + /** + * Escape hatch: a module's Vue component drawing the cell, registered under + * this name. It receives `value`, `row`, `column` and `cell`. + */ + component?: string; + /** A pill in the header ("Base", "12 missing"). */ + badge?: BlockText; + badgeTone?: MatrixTone; + /** A meter under the header, 0 to 1 (a language's coverage). */ + progress?: number; + progressTone?: MatrixTone; + /** Hidden until shown from the columns menu. */ + hidden?: boolean; + /** Stuck to the left, after the row header. */ + pinned?: boolean; +} + +/** What the server says about one cell, besides its value. */ +export interface MatrixCellState { + tone?: MatrixTone; + /** A small figure in the cell's corner (the stock already there). */ + hint?: BlockText; + /** Hatched and not editable: outside the range (a size the article lacks). */ + disabled?: boolean; + readOnly?: boolean; + /** Warnings shown on the cell and in its drawer (a placeholder missing). */ + issues?: BlockText[]; + /** Greyed text shown while the cell is empty (the inherited or base text). */ + placeholder?: BlockText; + /** A value shown struck through before the current one (before / after). */ + previous?: unknown; +} + +/** One row: a record, or one value of the vertical axis (a store, a person). */ +export interface MatrixRow { + id: string; + /** The row header. Defaults to the id. */ + label?: BlockText; + /** Dimmed line under the label. */ + description?: BlockText; + /** The id of the group the row is filed under. */ + group?: string; + /** The cells, by column id. */ + values: Record; + /** Per-cell state, by column id. */ + cells?: Record; + readOnly?: boolean; + /** Highlights the row (the current store). */ + tone?: MatrixTone; +} + +/** A group heading the rows that name it. */ +export interface MatrixGroup { + id: string; + label: BlockText; + description?: BlockText; + badge?: BlockText; + badgeTone?: MatrixTone; + /** Starts collapsed. */ + collapsed?: boolean; +} + +/** + * Expected totals, set on the block or answered by the route: a footer or a + * total cell that differs turns red, and with `blockSave` the save waits until + * every one matches (24 pairs received must be split into 24). + */ +export interface MatrixTargets { + rows?: Record; + columns?: Record; + total?: number; + blockSave?: boolean; + /** Said under the grid while a target is missed. */ + message?: BlockText; +} + +/** A choice of a facet filter. */ +export interface MatrixFacetItem { + value: string; + label: BlockText; + count?: number; +} + +/** + * The answer of `fetchUrl`. It is read with `offset` and `limit` (when + * paginated), `search`, `status`, `sort` and `direction`, and one + * `facet_=a,b` per facet in use. + */ +export interface MatrixData { + rows: MatrixRow[]; + columns?: MatrixColumn[]; + /** Every row the query matches, for the pager. Defaults to `rows.length`. */ + total?: number; + groups?: MatrixGroup[]; + /** The count of each status filter, by id. */ + counts?: Record; + /** The choices of each facet, by facet id, when the block does not list them. */ + facets?: Record; + targets?: MatrixTargets; + /** A line in the footer ("0 missing translations in French"). */ + footer?: BlockText; +} + +/** One edited cell, as `saveUrl` receives it. */ +export interface MatrixChange { + rowId: string; + columnId: string; + value: unknown; + /** The value the edit started from. */ + previous: unknown; +} + +/** The body posted to `saveUrl`. */ +export interface MatrixSaveRequest { + changes: MatrixChange[]; + /** Set when the user chose Overwrite on a conflict. */ + force?: boolean; +} + +/** A change the route refused. */ +export interface MatrixCellError { + rowId: string; + /** Absent: the error is about the whole row. */ + columnId?: string; + message: BlockText; +} + +/** A change made on a value that moved meanwhile (`conflicts: "detect"`). */ +export interface MatrixConflict { + rowId: string; + columnId: string; + current: unknown; +} + +/** + * The answer of `saveUrl`. Rows it returns replace theirs on screen; a change + * named in `errors` or `conflicts` stays in its cell with the message. A + * non-2xx answer fails every change of the request. + */ +export interface MatrixSaveResponse { + rows?: MatrixRow[]; + errors?: MatrixCellError[]; + conflicts?: MatrixConflict[]; + counts?: Record; + targets?: MatrixTargets; +} + +/** + * A server-computed fill (all to the warehouse, by minimum stock, clear): the + * grid posts its rows as shown (`{ rows }`) and applies the answered + * `{ changes }` as edits, through the save mode like typed ones. + */ +export interface MatrixFillAction { + id: string; + label: BlockText; + icon?: string; + url: string; + method?: EnumOption; +} + +/** A segment of the status filter ("Missing 12"), sent as `status=`. */ +export interface MatrixStatusFilter { + id: string; + label: BlockText; + tone?: MatrixTone; +} + +/** A select filter, sent as `facet_=a,b`. */ +export interface MatrixFacet { + id: string; + label: BlockText; + icon?: string; + multiple?: boolean; + /** Static choices; else the response's `facets[id]`. */ + items?: MatrixFacetItem[]; +} + +/** An entry of the legend under the grid. */ +export interface MatrixLegendItem { + label: BlockText; + tone?: MatrixTone; + /** Drawn as the hatching of a disabled cell. */ + hatched?: boolean; +} + +/** The row header, the sticky first column. */ +export interface MatrixRowHeader { + label?: BlockText; + width?: number; + /** Numbers the rows in a gutter (1, 2, 3... across pages). */ + numbers?: boolean; +} + +/** + * The drawer of a whole row, opened by the ⤢ button of its header or Space: + * one field per column, in a vertical form, J and K stepping through the rows. + */ +export interface MatrixRowPanel { + title?: BlockText; + /** Adds a read-only JSON tab of the row. */ + showJson?: boolean; +} + +/** Row totals (a Total column), column totals (a Total row), or both. */ +export interface MatrixTotals { + rows?: boolean; + columns?: boolean; + label?: BlockText; +} + +/** How groups behave. */ +export interface MatrixGrouping { + collapsible?: boolean; + /** Groups start collapsed past this many rows. */ + collapseAbove?: number; +} + +export interface MatrixProps extends BaseComponentProps { + title?: BlockText; + description?: BlockText; + + /** Where the rows are read from, answering {@link MatrixData}. Takes `{{params.X}}` and `{{query.X}}`. */ + fetchUrl?: string; + fetchUrlMethod?: EnumOption; + /** Reads `fetchUrl` again on each event of these topics. */ + realtimeTopic?: string | string[]; + /** Rows given in the options, for a grid without a route. */ + staticData?: MatrixData; + + /** Where edits are written, receiving {@link MatrixSaveRequest}. No `saveUrl`, no editing. */ + saveUrl?: string; + /** Defaults to POST. */ + saveUrlMethod?: EnumOption; + + columns?: MatrixColumn[]; + rowHeader?: MatrixRowHeader; + + /** Defaults to `true` when `saveUrl` is set. */ + editable?: boolean; + /** Defaults to `doubleClick`: a click selects the cell. */ + editTrigger?: MatrixEditTrigger; + /** Typing on a selected cell starts editing it with that character, as a spreadsheet does. */ + typeToEdit?: boolean; + /** Defaults to `immediate`. */ + saveMode?: MatrixSaveMode; + /** `staged`: lists the changes, before → after, before writing them. */ + review?: boolean; + /** Seconds an Undo stays offered after a save. 0 or absent: no undo. */ + undoSeconds?: number; + /** Defaults to `overwrite`. */ + conflicts?: MatrixConflictMode; + /** Defaults to `down`. */ + enterMove?: MatrixEnterMove; + /** The ⤢ button opening a row in a drawer. `true` for the defaults. */ + rowPanel?: boolean | MatrixRowPanel; + /** + * What a click on a read-only cell opens. `{{row.X}}` takes the row's + * values, plus `{{row.id}}`, `{{row.column}}` (the column id) and + * `{{row.value}}` (the cell's value). + */ + cellAction?: ActionTarget; + fillActions?: MatrixFillAction[]; + + /** Defaults to `none` (every row at once). */ + pagination?: MatrixPagination; + pageSize?: number; + /** The page sizes offered in the footer. */ + pageSizes?: number[]; + search?: boolean; + statusFilters?: MatrixStatusFilter[]; + facets?: MatrixFacet[]; + /** Header clicks sort, sent as `sort` and `direction`. */ + sortable?: boolean; + /** Keeps page, search, status and facets in the page URL. Defaults to `true`. */ + urlState?: boolean; + + grouping?: MatrixGrouping; + totals?: MatrixTotals; + targets?: MatrixTargets; + /** Lights the hovered cell's row and column. */ + crossHighlight?: boolean; + /** Show, hide and reorder columns, remembered on the device. */ + columnsMenu?: boolean; + resizableColumns?: boolean; + /** N and Shift+N jump to the next and previous empty editable cell. */ + jumpToEmpty?: boolean; + /** Keeps a row the user edited on screen after it stops matching the filters. */ + keepEditedRows?: boolean; + /** A CSV export of the rows shown. */ + exportCsv?: boolean; + legend?: MatrixLegendItem[]; + emptyLabel?: BlockText; + maxHeight?: string; + density?: "compact" | "comfortable"; +} + +/** The options as the block receives them, its targets serialized. */ +export interface MatrixPropsSerialized extends Omit { + cellAction?: ActionTargetSerialized; +} + +const MATRIX_COMPONENT_NAME = "dms-matrix-block"; +const DEFAULT_ICON = "i-ph-grid-nine"; + +/** + * A grid of rows by columns whose cells are read and edited in place: the + * records of a collection, the languages of a translation key, the sizes of + * an article by store. `options` is optional so a page under construction may + * write the bare call `Matrix()`. + */ +export function Matrix( + options?: MatrixProps, +): ComponentBuilder { + const { cellAction, ...rest } = options ?? {}; + const serialized: MatrixPropsSerialized = { + ...rest, + ...(cellAction && { cellAction: serializeActionTarget(cellAction) }), + }; + return attachRealtimeTopicsHook( + new ComponentBuilder(MATRIX_COMPONENT_NAME) + .options(serialized) + .meta({ name: "Matrix", icon: DEFAULT_ICON }), + options?.realtimeTopic, + ); +} + +/** The options `Matrix` accepts. */ +export const MatrixSchema = z.object({ + title: ui(opaqueOption().optional(), { + label: "Title", + group: "content", + }), + description: ui(opaqueOption().optional(), { + label: "Description", + group: "content", + }), + fetchUrl: ui( + z.string().optional().describe("Where the rows are read from."), + { + label: "Data source", + group: "data", + widget: "dataSource", + }, + ), + fetchUrlMethod: ui(z.nativeEnum(HttpMethod).optional(), { + label: "HTTP method", + group: "advanced", + widget: "select", + }), + realtimeTopic: blockRealtimeTopicOption(), + staticData: ui(opaqueOption().optional(), { + label: "Static data", + group: "advanced", + widget: "json", + }), + saveUrl: ui(z.string().optional().describe("Where edits are written."), { + label: "Save route", + group: "data", + widget: "url", + }), + saveUrlMethod: ui(z.nativeEnum(HttpMethod).optional(), { + label: "Save method", + group: "advanced", + widget: "select", + }), + columns: ui(opaqueOption().optional(), { + label: "Columns", + group: "data", + widget: "json", + }), + rowHeader: ui(opaqueOption().optional(), { + label: "Row header", + group: "appearance", + widget: "json", + }), + editable: ui(z.boolean().optional(), { + label: "Editable", + group: "behavior", + widget: "switch", + }), + editTrigger: ui(z.enum(["click", "doubleClick"]).optional(), { + label: "Edit on", + group: "behavior", + widget: "segmented", + }), + typeToEdit: ui(z.boolean().optional(), { + label: "Type to edit", + group: "behavior", + widget: "switch", + }), + saveMode: ui(z.enum(["immediate", "staged"]).optional(), { + label: "Save mode", + group: "behavior", + widget: "segmented", + }), + review: ui(z.boolean().optional(), { + label: "Review before saving", + group: "behavior", + widget: "switch", + }), + undoSeconds: ui(z.number().int().min(0).optional(), { + label: "Undo window (s)", + group: "behavior", + widget: "number", + min: 0, + }), + conflicts: ui(z.enum(["overwrite", "detect"]).optional(), { + label: "Conflicts", + group: "behavior", + widget: "segmented", + }), + enterMove: ui(z.enum(["down", "right", "stay"]).optional(), { + label: "Enter moves", + group: "behavior", + widget: "segmented", + }), + rowPanel: ui(opaqueOption().optional(), { + label: "Row drawer", + group: "features", + widget: "json", + }), + cellAction: ui(opaqueOption().optional(), { + label: "Cell action", + group: "behavior", + widget: "json", + }), + fillActions: ui(opaqueOption().optional(), { + label: "Fill actions", + group: "features", + widget: "json", + }), + pagination: ui(z.enum(["none", "pages", "infinite"]).optional(), { + label: "Pagination", + group: "data", + widget: "segmented", + }), + pageSize: ui(z.number().int().min(1).optional(), { + label: "Page size", + group: "data", + widget: "number", + min: 1, + }), + pageSizes: ui(z.array(z.number().int().min(1)).optional(), { + label: "Page sizes", + group: "data", + widget: "json", + }), + search: ui(z.boolean().optional(), { + label: "Search", + group: "features", + widget: "switch", + }), + statusFilters: ui(opaqueOption().optional(), { + label: "Status filters", + group: "features", + widget: "json", + }), + facets: ui(opaqueOption().optional(), { + label: "Facets", + group: "features", + widget: "json", + }), + sortable: ui(z.boolean().optional(), { + label: "Sortable", + group: "features", + widget: "switch", + }), + urlState: ui(z.boolean().optional(), { + label: "Keep state in the URL", + group: "behavior", + widget: "switch", + }), + grouping: ui(opaqueOption().optional(), { + label: "Grouping", + group: "features", + widget: "json", + }), + totals: ui(opaqueOption().optional(), { + label: "Totals", + group: "features", + widget: "json", + }), + targets: ui(opaqueOption().optional(), { + label: "Targets", + group: "features", + widget: "json", + }), + crossHighlight: ui(z.boolean().optional(), { + label: "Cross highlight", + group: "appearance", + widget: "switch", + }), + columnsMenu: ui(z.boolean().optional(), { + label: "Columns menu", + group: "features", + widget: "switch", + }), + resizableColumns: ui(z.boolean().optional(), { + label: "Resizable columns", + group: "features", + widget: "switch", + }), + jumpToEmpty: ui(z.boolean().optional(), { + label: "Jump to empty cells", + group: "behavior", + widget: "switch", + }), + keepEditedRows: ui(z.boolean().optional(), { + label: "Keep edited rows", + group: "behavior", + widget: "switch", + }), + exportCsv: ui(z.boolean().optional(), { + label: "CSV export", + group: "features", + widget: "switch", + }), + legend: ui(opaqueOption().optional(), { + label: "Legend", + group: "appearance", + widget: "json", + }), + emptyLabel: ui(opaqueOption().optional(), { + label: "Empty message", + group: "content", + }), + maxHeight: ui(z.string().optional(), { + label: "Maximum height", + group: "appearance", + }), + density: ui(z.enum(["compact", "comfortable"]).optional(), { + label: "Density", + group: "appearance", + widget: "segmented", + }), +}) satisfies BlockOptionsFor; + +RegisterBlockType({ + type: "Matrix", + componentName: MATRIX_COMPONENT_NAME, + schema: MatrixSchema, + meta: { + name: "Matrix", + icon: DEFAULT_ICON, + description: + "A grid of rows by columns edited in place: records, translations, quantities by size and store.", + group: "data", + }, +}); From 705138cece15115e9e57862c27ab1cabd9a719d9 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:18:07 +0100 Subject: [PATCH 02/41] feat(interface): group a Matrix's rows on a column, folded and subtotalled Aligns grouping with the table view's grouped display: groupByField, by value, day or week, collapsible headers with a row count, plus subtotals. --- packages/interface-dms/src/base/matrix.ts | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/interface-dms/src/base/matrix.ts b/packages/interface-dms/src/base/matrix.ts index ef95e62d3..c7080a744 100644 --- a/packages/interface-dms/src/base/matrix.ts +++ b/packages/interface-dms/src/base/matrix.ts @@ -9,6 +9,7 @@ import { import { blockRealtimeTopicOption } from "./display"; import { attachRealtimeTopicsHook } from "./internal/realtime-topics"; import type { ColumnDisplaySerialized } from "./table-view/column-display"; +import type { TableViewGroupBy } from "./table-view/options"; import type { ActionTarget, ActionTargetSerialized, @@ -352,11 +353,32 @@ export interface MatrixTotals { label?: BlockText; } -/** How groups behave. */ +/** + * Rows cut into groups, each under a header row, as the table view's + * `grouped` display does. A row joins the group its `group` names (groups the + * server builds, described by the response's `groups`), else the group of its + * value in `groupByField`. + */ export interface MatrixGrouping { + /** + * Column the rows are grouped on, read from each row's values. The route + * lists the rows sorted on it, so a group's rows follow each other and a + * page starting inside a group repeats its header on top. + */ + groupByField?: string; + /** + * `value` (the default): one group per value; `day` or `week`: one group + * per calendar day or week of a date column. Same as the table view's. + */ + by?: TableViewGroupBy; + /** A click on a group header folds its rows; the fold is kept while the page stays open. */ collapsible?: boolean; /** Groups start collapsed past this many rows. */ collapseAbove?: number; + /** Group headers show how many rows the group holds. */ + count?: boolean; + /** With `totals.columns`, each group header carries its own column sums. */ + subtotals?: boolean; } export interface MatrixProps extends BaseComponentProps { From 388c28e239993dad4da19a5abff438d0612e0c13 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:19:09 +0100 Subject: [PATCH 03/41] refactor(interface): keep a Matrix's grouping to what a grid needs Drops the day and week buckets borrowed from the table view: a Matrix groups on server-built groups or on a column's value. --- packages/interface-dms/src/base/matrix.ts | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/packages/interface-dms/src/base/matrix.ts b/packages/interface-dms/src/base/matrix.ts index c7080a744..d79e0121f 100644 --- a/packages/interface-dms/src/base/matrix.ts +++ b/packages/interface-dms/src/base/matrix.ts @@ -9,7 +9,6 @@ import { import { blockRealtimeTopicOption } from "./display"; import { attachRealtimeTopicsHook } from "./internal/realtime-topics"; import type { ColumnDisplaySerialized } from "./table-view/column-display"; -import type { TableViewGroupBy } from "./table-view/options"; import type { ActionTarget, ActionTargetSerialized, @@ -354,24 +353,17 @@ export interface MatrixTotals { } /** - * Rows cut into groups, each under a header row, as the table view's - * `grouped` display does. A row joins the group its `group` names (groups the - * server builds, described by the response's `groups`), else the group of its - * value in `groupByField`. + * Rows cut into groups, each under a header row. A row joins the group its + * `group` names (groups the server builds, described by the response's + * `groups`), else the group of its value in `groupByField`. */ export interface MatrixGrouping { /** - * Column the rows are grouped on, read from each row's values. The route - * lists the rows sorted on it, so a group's rows follow each other and a - * page starting inside a group repeats its header on top. + * Column the rows are grouped on, for rows that name no `group`. The route + * lists the rows sorted on it, so a group's rows follow each other. */ groupByField?: string; - /** - * `value` (the default): one group per value; `day` or `week`: one group - * per calendar day or week of a date column. Same as the table view's. - */ - by?: TableViewGroupBy; - /** A click on a group header folds its rows; the fold is kept while the page stays open. */ + /** A click on a group header folds its rows. */ collapsible?: boolean; /** Groups start collapsed past this many rows. */ collapseAbove?: number; From 2836b56a77a28ae2239034e8ef52ac7918073eb3 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:25:48 +0100 Subject: [PATCH 04/41] docs(interface): order a Matrix's merged columns, send the list query with a save --- packages/interface-dms/src/base/matrix.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/interface-dms/src/base/matrix.ts b/packages/interface-dms/src/base/matrix.ts index d79e0121f..6b0ee17bd 100644 --- a/packages/interface-dms/src/base/matrix.ts +++ b/packages/interface-dms/src/base/matrix.ts @@ -104,7 +104,9 @@ export interface MatrixSelectOption { * One column. Columns come from the block's `columns` option, from the * response's `columns`, or both: the response wins for an id both declare, * and adds the ones it alone names (languages of a workspace, sizes of an - * article, fields of a collection). + * article, fields of a collection). They are drawn in the response's order, + * then the block's columns the response does not name, in the block's order; + * `pinned` ones first. */ export interface MatrixColumn { id: string; @@ -259,6 +261,12 @@ export interface MatrixSaveRequest { changes: MatrixChange[]; /** Set when the user chose Overwrite on a conflict. */ force?: boolean; + /** + * The query the grid reads its rows with (`search`, `status`, + * `facet_`...), without paging, so the route can answer the `counts` + * of the filtered view. + */ + query?: Record; } /** A change the route refused. */ From 4d2f9026e551178c308e4f6fec959b69cac7bd9b Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:25:49 +0100 Subject: [PATCH 05/41] feat(playground): demo the Matrix block on six pages Overview, records (database style), translations (dynamic columns, server groups, conflicts), stock by size and store (read-only, totals, grouping, cell action), reception allocation (targets, fills, before/after) and a roster (toned labels). In-memory routes; plus the Matrix contract test and its feature index. --- .../playground/src/feature-index/catalog.ts | 2 + .../playground/src/feature-index/matrix.ts | 164 +++++ .../dms/playground/src/feature-index/types.ts | 1 + packages/dms/playground/src/index.ts | 1 + .../playground/src/matrix/allocation/api.ts | 305 ++++++++ .../playground/src/matrix/allocation/data.ts | 62 ++ .../playground/src/matrix/allocation/page.ts | 151 ++++ .../dms/playground/src/matrix/category.ts | 19 + packages/dms/playground/src/matrix/index.ts | 19 + .../dms/playground/src/matrix/options/page.ts | 367 ++++++++++ packages/dms/playground/src/matrix/query.ts | 165 +++++ .../dms/playground/src/matrix/records/api.ts | 304 ++++++++ .../dms/playground/src/matrix/records/data.ts | 348 +++++++++ .../dms/playground/src/matrix/records/page.ts | 278 ++++++++ .../dms/playground/src/matrix/roster/api.ts | 161 +++++ .../dms/playground/src/matrix/roster/data.ts | 176 +++++ .../dms/playground/src/matrix/roster/page.ts | 99 +++ packages/dms/playground/src/matrix/save.ts | 80 +++ .../dms/playground/src/matrix/stock/api.ts | 307 ++++++++ .../dms/playground/src/matrix/stock/data.ts | 130 ++++ .../dms/playground/src/matrix/stock/page.ts | 173 +++++ .../playground/src/matrix/translations/api.ts | 325 +++++++++ .../src/matrix/translations/data.ts | 665 ++++++++++++++++++ .../src/matrix/translations/page.ts | 115 +++ .../unit/interfaces/dms-base/matrix.test.ts | 165 +++++ 25 files changed, 4582 insertions(+) create mode 100644 packages/dms/playground/src/feature-index/matrix.ts create mode 100644 packages/dms/playground/src/matrix/allocation/api.ts create mode 100644 packages/dms/playground/src/matrix/allocation/data.ts create mode 100644 packages/dms/playground/src/matrix/allocation/page.ts create mode 100644 packages/dms/playground/src/matrix/category.ts create mode 100644 packages/dms/playground/src/matrix/index.ts create mode 100644 packages/dms/playground/src/matrix/options/page.ts create mode 100644 packages/dms/playground/src/matrix/query.ts create mode 100644 packages/dms/playground/src/matrix/records/api.ts create mode 100644 packages/dms/playground/src/matrix/records/data.ts create mode 100644 packages/dms/playground/src/matrix/records/page.ts create mode 100644 packages/dms/playground/src/matrix/roster/api.ts create mode 100644 packages/dms/playground/src/matrix/roster/data.ts create mode 100644 packages/dms/playground/src/matrix/roster/page.ts create mode 100644 packages/dms/playground/src/matrix/save.ts create mode 100644 packages/dms/playground/src/matrix/stock/api.ts create mode 100644 packages/dms/playground/src/matrix/stock/data.ts create mode 100644 packages/dms/playground/src/matrix/stock/page.ts create mode 100644 packages/dms/playground/src/matrix/translations/api.ts create mode 100644 packages/dms/playground/src/matrix/translations/data.ts create mode 100644 packages/dms/playground/src/matrix/translations/page.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/matrix.test.ts diff --git a/packages/dms/playground/src/feature-index/catalog.ts b/packages/dms/playground/src/feature-index/catalog.ts index 390b10544..d7dc98efd 100644 --- a/packages/dms/playground/src/feature-index/catalog.ts +++ b/packages/dms/playground/src/feature-index/catalog.ts @@ -1,6 +1,7 @@ import { BLOCKS_FEATURES } from "./blocks"; import { FORM_FEATURES } from "./form"; import { FRONTEND_FEATURES } from "./frontend"; +import { MATRIX_FEATURES } from "./matrix"; import { PAGES_FEATURES } from "./pages"; import { TABLE_VIEW_FEATURES } from "./table-view"; import type { PlaygroundFeature } from "./types"; @@ -9,6 +10,7 @@ import type { PlaygroundFeature } from "./types"; export const PLAYGROUND_FEATURES: PlaygroundFeature[] = [ ...BLOCKS_FEATURES, ...TABLE_VIEW_FEATURES, + ...MATRIX_FEATURES, ...FORM_FEATURES, ...PAGES_FEATURES, ...FRONTEND_FEATURES, diff --git a/packages/dms/playground/src/feature-index/matrix.ts b/packages/dms/playground/src/feature-index/matrix.ts new file mode 100644 index 000000000..78c1caa99 --- /dev/null +++ b/packages/dms/playground/src/feature-index/matrix.ts @@ -0,0 +1,164 @@ +import { FEATURE_AREAS, type PlaygroundFeature } from "./types"; + +const AREA = FEATURE_AREAS.matrix; +const ROOT = "/matrix"; + +// The release the Matrix block ships in: the next minor after 0.11.0. +const MATRIX_RELEASE = "0.12.0"; + +const PAGES = { + overview: `${ROOT}/matrix-options`, + records: `${ROOT}/matrix-records`, + translations: `${ROOT}/matrix-translations`, + stock: `${ROOT}/matrix-stock`, + allocation: `${ROOT}/matrix-allocation`, + roster: `${ROOT}/matrix-roster`, +}; + +function feature(name: string, api: string, demo: string): PlaygroundFeature { + return { area: AREA, feature: name, api, demo, since: MATRIX_RELEASE }; +} + +/** The Matrix block's features, page by page. */ +export const MATRIX_FEATURES: PlaygroundFeature[] = [ + feature( + "A read-only grid from static data, totals both ways", + "Matrix({ staticData, totals: { rows, columns } })", + PAGES.overview, + ), + feature( + "Records of mixed types edited in place", + 'Matrix({ fetchUrl, saveUrl, columns: [{ kind: "json" | "keyValue" | "code" | … }] })', + PAGES.records, + ), + feature( + "Double click to edit, a click selects", + 'editTrigger: "doubleClick"', + PAGES.records, + ), + feature( + "Objects, code and long texts edited in a drawer", + 'columns[].editIn: "auto"', + PAGES.records, + ), + feature( + "Staged edits, reviewed, saved together, undo", + 'saveMode: "staged", review: true, undoSeconds', + PAGES.records, + ), + feature( + "Per-cell and per-row errors of the save route", + "MatrixSaveResponse.errors [{ rowId, columnId?, message }]", + PAGES.records, + ), + feature( + "A row in a drawer, with a JSON tab", + "rowPanel: { showJson: true }", + PAGES.records, + ), + feature( + "Server paging with row numbers", + 'pagination: "pages", pageSize, pageSizes, rowHeader: { numbers: true }', + PAGES.records, + ), + feature( + "Server sort, search and facets", + "sortable, search, facets (facet_=a,b)", + PAGES.records, + ), + feature( + "Rows grouped on a column", + "grouping: { groupByField, collapsible, count }", + PAGES.records, + ), + feature( + "Columns shown, hidden, reordered, resized; CSV export", + "columnsMenu, resizableColumns, exportCsv", + PAGES.records, + ), + feature( + "Columns answered by the route, with a badge and a meter", + "MatrixData.columns [{ badge, progress }]", + PAGES.translations, + ), + feature( + "Click to edit, saved cell by cell, Enter moves down", + 'editTrigger: "click", saveMode: "immediate", enterMove: "down"', + PAGES.translations, + ), + feature( + "Conflicts detected, Overwrite or Discard", + 'conflicts: "detect" (MatrixSaveResponse.conflicts, force)', + PAGES.translations, + ), + feature( + "Base text as placeholder, issues on a cell", + "MatrixRow.cells[id].placeholder / issues", + PAGES.translations, + ), + feature( + "Status segments with counts", + "statusFilters, MatrixData.counts", + PAGES.translations, + ), + feature( + "Server groups, collapsible and counted", + "MatrixRow.group, MatrixData.groups, grouping: { collapseAbove, count }", + PAGES.translations, + ), + feature( + "Infinite scrolling, jump to empty, edited rows kept", + 'pagination: "infinite", jumpToEmpty, keepEditedRows', + PAGES.translations, + ), + feature( + "Stock by size and store, cross highlight", + "totals, crossHighlight, legend", + PAGES.stock, + ), + feature( + "Hatched cells out of range, alert tones, annex columns", + "cells[id].disabled / tone, columns[].excludeFromTotals / display", + PAGES.stock, + ), + feature( + "Group subtotals", + "grouping: { groupByField, subtotals: true }", + PAGES.stock, + ), + feature( + "A cell opening a prefilled form", + 'cellAction: { type: "drawer", component: Form({ fetchUrl: "…?store={{row.id}}&size={{row.column}}" }) }', + PAGES.stock, + ), + feature( + "Targets that hold the save until totals match", + "targets: { columns, total, blockSave, message }", + PAGES.allocation, + ), + feature( + "Fills computed by the server", + "fillActions [{ id, label, url }] → { changes }", + PAGES.allocation, + ), + feature( + "Type to edit, the stock as a hint", + "typeToEdit, cells[id].hint", + PAGES.allocation, + ), + feature( + "Before / after, the old value struck through", + "cells[id].previous", + PAGES.allocation, + ), + feature( + "Toned labels picked from a select", + 'columns[]: { kind: "select", options: [{ value, label, tone }] }', + PAGES.roster, + ), + feature( + "Row descriptions and tones from the route", + "MatrixRow.description / tone", + PAGES.roster, + ), +]; diff --git a/packages/dms/playground/src/feature-index/types.ts b/packages/dms/playground/src/feature-index/types.ts index d9ed7a4dd..674596605 100644 --- a/packages/dms/playground/src/feature-index/types.ts +++ b/packages/dms/playground/src/feature-index/types.ts @@ -2,6 +2,7 @@ export const FEATURE_AREAS = { blocks: "Blocks & charts", tableView: "Table view", + matrix: "Matrix", form: "Forms", pages: "Pages & navigation", frontend: "Frontend modules", diff --git a/packages/dms/playground/src/index.ts b/packages/dms/playground/src/index.ts index 4662d81f4..ba2e3967c 100644 --- a/packages/dms/playground/src/index.ts +++ b/packages/dms/playground/src/index.ts @@ -9,6 +9,7 @@ import "./flow-canvas"; import "./drawer-modal"; import "./form"; import "./table-view"; +import "./matrix"; import "./tabs"; import "./grid"; import "./chart"; diff --git a/packages/dms/playground/src/matrix/allocation/api.ts b/packages/dms/playground/src/matrix/allocation/api.ts new file mode 100644 index 000000000..b43212b7e --- /dev/null +++ b/packages/dms/playground/src/matrix/allocation/api.ts @@ -0,0 +1,305 @@ +import { Controller, Get, JSONBody, Post } from "@antelopejs/interface-api"; +import type { User } from "@antelopejs/interface-dms/auth/db"; +import type { + MatrixCellError, + MatrixCellState, + MatrixChange, + MatrixData, + MatrixRow, + MatrixSaveRequest, + MatrixSaveResponse, +} from "@antelopejs/interface-dms/base/matrix"; +import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards"; +import { + cellError, + type MatrixFillRequest, + readSaveRequest, + sameCellValue, +} from "../save"; +import { + CURRENT_STORE, + findStore, + isInRange, + SIZES, + STOCK, + type Store, + type StoreQuantities, + STORES, + WAREHOUSE, +} from "../stock/data"; +import { allocation, counted, RECEIVED, resetAllocationDemo } from "./data"; +import { MATRIX_ALLOCATION_API, PageMatrixAllocation } from "./page"; + +const MAX_PAIRS = 999; + +/** The pairs a fill gives a store in a size; `null` empties the cell. */ +type FillRule = (store: Store, size: string) => number | null; + +/** The cells of the grid as the browser shows them, by row then column. */ +type ShownValues = Record; + +function storeRowBase( + store: Store, +): Pick { + const isCurrent = store.id === CURRENT_STORE; + return { + id: store.id, + label: store.id, + description: isCurrent ? `${store.name} · votre magasin` : store.name, + tone: isCurrent ? "primary" : undefined, + }; +} + +function quantityValues( + store: Store, + quantities: StoreQuantities, +): Record { + return Object.fromEntries( + SIZES.map((size) => [ + size, + isInRange(store, size) ? (quantities[store.id]?.[size] ?? null) : null, + ]), + ); +} + +function stockOf(store: Store, size: string): number { + return STOCK[store.id]?.[size] ?? 0; +} + +function allocationCell(store: Store, size: string): MatrixCellState { + if (!isInRange(store, size)) return { disabled: true }; + return { hint: String(stockOf(store, size)) }; +} + +function correctionCell(store: Store, size: string): MatrixCellState { + if (!isInRange(store, size)) return { disabled: true }; + const before = stockOf(store, size); + const after = counted[store.id]?.[size] ?? 0; + return after === before ? {} : { previous: before, tone: "warning" }; +} + +function cellsBy( + store: Store, + cellOf: (store: Store, size: string) => MatrixCellState, +): Record { + return Object.fromEntries(SIZES.map((size) => [size, cellOf(store, size)])); +} + +function allocationRow(store: Store): MatrixRow { + return { + ...storeRowBase(store), + values: quantityValues(store, allocation), + cells: cellsBy(store, allocationCell), + }; +} + +function correctionRow(store: Store): MatrixRow { + return { + ...storeRowBase(store), + values: quantityValues(store, counted), + cells: cellsBy(store, correctionCell), + }; +} + +/** Why a quantity cannot go in a cell, or `undefined` when it can. */ +function quantityProblem(change: MatrixChange): string | undefined { + const store = findStore(change.rowId); + if (!store) return "Magasin inconnu."; + if (!SIZES.includes(change.columnId)) return "Pointure inconnue."; + if (!isInRange(store, change.columnId)) { + return `${store.id} n'a pas commandé la pointure ${change.columnId}.`; + } + const { value } = change; + if (value === null) return undefined; + if ( + !Number.isInteger(value) || + Number(value) < 0 || + Number(value) > MAX_PAIRS + ) { + return `Un nombre entier de paires, de 0 à ${MAX_PAIRS}.`; + } + return undefined; +} + +function setQuantity(quantities: StoreQuantities, change: MatrixChange): void { + const row = { ...quantities[change.rowId] }; + if (change.value === null) delete row[change.columnId]; + else row[change.columnId] = Number(change.value); + quantities[change.rowId] = row; +} + +function sizeTotal(quantities: StoreQuantities, size: string): number { + return STORES.reduce( + (total, store) => total + (quantities[store.id]?.[size] ?? 0), + 0, + ); +} + +/** The changes of a size column whose pairs do not add up to the delivery. */ +function unbalancedErrors( + proposed: StoreQuantities, + changes: MatrixChange[], +): MatrixCellError[] { + return changes.flatMap((change) => { + const size = change.columnId; + const total = sizeTotal(proposed, size); + const received = RECEIVED[size] ?? 0; + if (total === received) return []; + return [ + cellError( + change, + `Pointure ${size} : ${total} paires réparties pour ${received} reçues.`, + ), + ]; + }); +} + +function copyOf(quantities: StoreQuantities): StoreQuantities { + return Object.fromEntries( + Object.entries(quantities).map(([store, sizes]) => [store, { ...sizes }]), + ); +} + +function shownValues(request: MatrixFillRequest | undefined): ShownValues { + const rows = Array.isArray(request?.rows) + ? request.rows + : STORES.map(allocationRow); + return Object.fromEntries(rows.map((row) => [row.id, row.values ?? {}])); +} + +/** The edits that turn the grid shown into the one a fill computes. */ +function fillChanges( + request: MatrixFillRequest | undefined, + rule: FillRule, +): MatrixChange[] { + const shown = shownValues(request); + return STORES.flatMap((store) => + SIZES.filter((size) => isInRange(store, size)).flatMap((size) => { + const value = rule(store, size); + const previous = shown[store.id]?.[size] ?? null; + if (sameCellValue(value, previous)) return []; + return [{ rowId: store.id, columnId: size, value, previous }]; + }), + ); +} + +const allToWarehouse: FillRule = (store, size) => + store.id === WAREHOUSE ? (RECEIVED[size] ?? 0) : null; + +const clearAll: FillRule = () => null; + +// The stores in the order they are served: the current store first, the +// e-shop last, the warehouse taking what is left. +const SERVED_STORES = [ + ...STORES.filter((store) => store.id === CURRENT_STORE), + ...STORES.filter( + (store) => store.id !== CURRENT_STORE && store.id !== WAREHOUSE, + ), +]; + +/** Tops each store up to its minimum, size by size; the rest goes to the warehouse. */ +function byMinimumStock(): StoreQuantities { + const split: StoreQuantities = Object.fromEntries( + STORES.map((store) => [store.id, {}]), + ); + for (const size of SIZES) { + let left = RECEIVED[size] ?? 0; + for (const store of SERVED_STORES.filter((candidate) => + isInRange(candidate, size), + )) { + const given = Math.min( + left, + Math.max(0, store.minimum - stockOf(store, size)), + ); + if (given) split[store.id]![size] = given; + left -= given; + } + if (left) split[WAREHOUSE]![size] = left; + } + return split; +} + +const toMinimumStock: FillRule = (store, size) => + byMinimumStock()[store.id]?.[size] ?? null; + +/** + * The routes of the "Reception allocation" demo: the split of a delivery + * between the stores (saved together, only when every size adds up), the + * three fills computed here, and the stock correction saved cell by cell. + */ +export class MatrixAllocationController extends Controller( + MATRIX_ALLOCATION_API, +) { + @AuthUserWithPermission(PageMatrixAllocation) + declare user: User; + + @Get("rows") + list(): MatrixData { + return { rows: STORES.map(allocationRow) }; + } + + // Atomic: a split is written whole or not at all, a delivery being split + // once. The grid already waits for the targets (blockSave); the route + // checks them again. + @Post("save") + save(@JSONBody() body: MatrixSaveRequest): MatrixSaveResponse { + const { changes } = readSaveRequest(body); + const refused = changes.flatMap((change) => { + const problem = quantityProblem(change); + return problem ? [cellError(change, problem)] : []; + }); + if (refused.length) return { errors: refused }; + const proposed = copyOf(allocation); + for (const change of changes) setQuantity(proposed, change); + const unbalanced = unbalancedErrors(proposed, changes); + if (unbalanced.length) return { errors: unbalanced }; + Object.assign(allocation, proposed); + return { rows: STORES.map(allocationRow) }; + } + + @Post("fill/warehouse") + fillWarehouse(@JSONBody() body: MatrixFillRequest) { + return { changes: fillChanges(body, allToWarehouse) }; + } + + @Post("fill/minimum") + fillMinimum(@JSONBody() body: MatrixFillRequest) { + return { changes: fillChanges(body, toMinimumStock) }; + } + + @Post("fill/clear") + fillClear(@JSONBody() body: MatrixFillRequest) { + return { changes: fillChanges(body, clearAll) }; + } + + @Get("correction/rows") + correction(): MatrixData { + return { rows: STORES.map(correctionRow) }; + } + + @Post("correction/save") + saveCorrection(@JSONBody() body: MatrixSaveRequest): MatrixSaveResponse { + const { changes } = readSaveRequest(body); + const errors: MatrixCellError[] = []; + for (const change of changes) { + const problem = + quantityProblem(change) ?? + (change.value === null + ? "Indiquez le nombre compté, 0 s'il n'y en a plus." + : undefined); + if (problem) errors.push(cellError(change, problem)); + else setQuantity(counted, change); + } + const rowIds = new Set(changes.map((change) => change.rowId)); + return { + rows: STORES.filter((store) => rowIds.has(store.id)).map(correctionRow), + errors, + }; + } + + @Post("reset") + reset() { + resetAllocationDemo(); + return { message: "Démo remise à zéro" }; + } +} diff --git a/packages/dms/playground/src/matrix/allocation/data.ts b/packages/dms/playground/src/matrix/allocation/data.ts new file mode 100644 index 000000000..16152b450 --- /dev/null +++ b/packages/dms/playground/src/matrix/allocation/data.ts @@ -0,0 +1,62 @@ +import { STOCK, STORES, type StoreQuantities } from "../stock/data"; + +/** The pairs of the delivery, by size: 24 in all. */ +export const RECEIVED: Record = { + 36: 2, + 37: 3, + 38: 6, + 39: 6, + 40: 4, + 41: 2, + 42: 1, +}; + +export const RECEIVED_TOTAL = Object.values(RECEIVED).reduce( + (total, pairs) => total + pairs, + 0, +); + +export const DELIVERY_NUMBER = "BL-26-04140"; + +interface CountDiscrepancy { + store: string; + size: string; + pairs: number; +} + +// What the stock count found unlike the system: a pair found in the back +// room, two pairs gone. +const DISCREPANCIES: CountDiscrepancy[] = [ + { store: "NE1", size: "38", pairs: 3 }, + { store: "LG4", size: "39", pairs: 2 }, + { store: "WEB", size: "40", pairs: 2 }, +]; + +function emptyAllocation(): StoreQuantities { + return Object.fromEntries(STORES.map((store) => [store.id, {}])); +} + +function countAtStart(): StoreQuantities { + const count: StoreQuantities = Object.fromEntries( + STORES.map((store) => [store.id, { ...STOCK[store.id] }]), + ); + for (const { store, size, pairs } of DISCREPANCIES) { + count[store] = { ...count[store], [size]: pairs }; + } + return count; +} + +/** The split of the delivery the stores saved, nothing at first. */ +export const allocation: StoreQuantities = emptyAllocation(); + +/** + * The pairs the stock count found, by store and size: the "after" of the + * correction grid, the stock in the system being the "before". + */ +export const counted: StoreQuantities = countAtStart(); + +/** Puts the demo back as it started. */ +export function resetAllocationDemo(): void { + Object.assign(allocation, emptyAllocation()); + Object.assign(counted, countAtStart()); +} diff --git a/packages/dms/playground/src/matrix/allocation/page.ts b/packages/dms/playground/src/matrix/allocation/page.ts new file mode 100644 index 000000000..c391f8252 --- /dev/null +++ b/packages/dms/playground/src/matrix/allocation/page.ts @@ -0,0 +1,151 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { + Matrix, + type MatrixColumn, + type MatrixLegendItem, +} from "@antelopejs/interface-dms/base/matrix"; +import { demoGuide } from "../../table-view/guide"; +import { MATRIX_API, matrixCategory } from "../category"; +import { ARTICLE, SIZES } from "../stock/data"; +import { DELIVERY_NUMBER, RECEIVED, RECEIVED_TOTAL } from "./data"; + +export const MATRIX_ALLOCATION_SLUG = "matrix-allocation"; +export const MATRIX_ALLOCATION_API = `${MATRIX_API}/allocation`; + +const MAX_PAIRS = 999; +const SIZE_WIDTH = 76; + +const LEGEND: MatrixLegendItem[] = [ + { label: "Hors plage commandée", hatched: true }, + { label: "Votre magasin", tone: "primary" }, +]; + +function sizeColumns(describe: (size: string) => string): MatrixColumn[] { + return SIZES.map((size) => ({ + id: size, + label: size, + description: describe(size), + kind: "number", + integer: true, + min: 0, + max: MAX_PAIRS, + align: "center", + width: SIZE_WIDTH, + })); +} + +@RegisterPage() +export class PageMatrixAllocation extends PageController( + MATRIX_ALLOCATION_SLUG, + { + displayName: "Reception allocation (targets and fills)", + icon: "i-ph-arrows-split", + category: matrixCategory, + order: 40, + description: + "A delivery of 24 pairs split between the warehouse and the stores: integer cells typed like a spreadsheet, the stock in each cell's corner, totals that must match the pairs received before saving, and fills the route computes. Under it, a stock correction showing the old quantity struck through.", + }, + DefaultLayout({ + fullWidth: true, + headerActions: [ + { + label: "Reset the demo", + icon: "i-ph-arrow-counter-clockwise", + target: { + type: "api", + url: `${MATRIX_ALLOCATION_API}/reset`, + method: "POST", + successMessage: "Both grids are back as they started", + }, + }, + ], + }), +) { + static guide = demoGuide([ + { + label: "Click a cell and type a number", + text: 'editTrigger: "click" and typeToEdit: typing on a selected cell starts editing with that digit; integers from 0 (integer, min). The small figure is the stock already there (hint).', + }, + { + label: "Watch the totals", + text: `targets: each size has the pairs received (38: ${RECEIVED["38"]}), ${RECEIVED_TOTAL} in all. A Total cell that differs turns red, the message says why, and the save waits until every one matches (blockSave).`, + }, + { + label: "Use a fill", + text: 'fillActions post the rows shown and apply the { changes } the route answers, staged like typed edits: "Tout à l\'entrepôt", "Selon les stocks minimum" (tops each store up to its minimum, current store first), "Effacer".', + }, + { + label: "Save the split", + text: 'saveMode: "staged" without review: one save writes it all. The route checks the totals again and refuses a size that does not add up.', + }, + { + label: "Correct a counted stock", + text: 'The second grid saves each cell as it is left (saveMode: "immediate"). A cell whose count differs from the system shows the system quantity struck through (cells[size].previous).', + }, + { + label: "Start over", + text: "The header's Reset the demo puts both grids back.", + }, + ]); + + static allocation = Matrix({ + title: `Réception de ${RECEIVED_TOTAL} paires — ${ARTICLE.label}`, + description: `Livraison ${DELIVERY_NUMBER} : répartissez les paires reçues entre l'entrepôt et les magasins. Le petit chiffre de chaque case est le stock actuel.`, + fetchUrl: `${MATRIX_ALLOCATION_API}/rows`, + saveUrl: `${MATRIX_ALLOCATION_API}/save`, + columns: sizeColumns((size) => `${RECEIVED[size] ?? 0} reçue(s)`), + rowHeader: { label: "Magasin", width: 220 }, + editTrigger: "click", + typeToEdit: true, + saveMode: "staged", + totals: { rows: true, columns: true, label: "Total réparti" }, + targets: { + columns: RECEIVED, + total: RECEIVED_TOTAL, + blockSave: true, + message: + "Chaque pointure doit être répartie en entier : le total réparti doit égaler les paires reçues.", + }, + fillActions: [ + { + id: "warehouse", + label: "Tout à l'entrepôt", + icon: "i-ph-warehouse", + url: `${MATRIX_ALLOCATION_API}/fill/warehouse`, + }, + { + id: "minimum", + label: "Selon les stocks minimum", + icon: "i-ph-scales", + url: `${MATRIX_ALLOCATION_API}/fill/minimum`, + }, + { + id: "clear", + label: "Effacer", + icon: "i-ph-eraser", + url: `${MATRIX_ALLOCATION_API}/fill/clear`, + }, + ], + crossHighlight: true, + legend: LEGEND, + }); + + static correction = Matrix({ + title: "Correction de stock (avant / après)", + description: + "Inventaire du 24 octobre : le chiffre barré est le stock du système, l'autre celui compté. Chaque case est enregistrée dès qu'on la quitte.", + fetchUrl: `${MATRIX_ALLOCATION_API}/correction/rows`, + saveUrl: `${MATRIX_ALLOCATION_API}/correction/save`, + columns: sizeColumns(() => "compté"), + rowHeader: { label: "Magasin", width: 220 }, + editTrigger: "click", + typeToEdit: true, + saveMode: "immediate", + totals: { rows: true, columns: true, label: "Total" }, + legend: [ + { label: "Hors plage commandée", hatched: true }, + { label: "Écart d'inventaire", tone: "warning" }, + ], + }); +} diff --git a/packages/dms/playground/src/matrix/category.ts b/packages/dms/playground/src/matrix/category.ts new file mode 100644 index 000000000..c5a8ed0d4 --- /dev/null +++ b/packages/dms/playground/src/matrix/category.ts @@ -0,0 +1,19 @@ +import { Category } from "@antelopejs/interface-dms/page"; +import { componentsSection } from "../sections"; + +// Right after the Table View (30), before the Form (40): the grid edited in +// place is read next to the table it complements. +export const matrixCategory = Category("matrix", { + displayName: "Matrix", + icon: "i-ph-grid-nine", + order: 35, + category: componentsSection, +}); + +/** The URL of a Matrix demo page, from the dashboard root. */ +export function matrixPagePath(slug: string): string { + return `/matrix/${slug}`; +} + +/** The root of the demos' API routes. */ +export const MATRIX_API = "/api/playground/matrix"; diff --git a/packages/dms/playground/src/matrix/index.ts b/packages/dms/playground/src/matrix/index.ts new file mode 100644 index 000000000..cff25dcf1 --- /dev/null +++ b/packages/dms/playground/src/matrix/index.ts @@ -0,0 +1,19 @@ +export * from "./allocation/api"; +export * from "./allocation/data"; +export * from "./allocation/page"; +export * from "./category"; +export * from "./options/page"; +export * from "./query"; +export * from "./records/api"; +export * from "./records/data"; +export * from "./records/page"; +export * from "./roster/api"; +export * from "./roster/data"; +export * from "./roster/page"; +export * from "./save"; +export * from "./stock/api"; +export * from "./stock/data"; +export * from "./stock/page"; +export * from "./translations/api"; +export * from "./translations/data"; +export * from "./translations/page"; diff --git a/packages/dms/playground/src/matrix/options/page.ts b/packages/dms/playground/src/matrix/options/page.ts new file mode 100644 index 000000000..adcad7b65 --- /dev/null +++ b/packages/dms/playground/src/matrix/options/page.ts @@ -0,0 +1,367 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { CodeBlock, KeyValueList } from "@antelopejs/interface-dms/base"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { Matrix, type MatrixData } from "@antelopejs/interface-dms/base/matrix"; +import { MATRIX_ALLOCATION_SLUG } from "../allocation/page"; +import { matrixCategory, matrixPagePath } from "../category"; +import { MATRIX_RECORDS_SLUG } from "../records/page"; +import { MATRIX_ROSTER_SLUG } from "../roster/page"; +import { MATRIX_STOCK_SLUG } from "../stock/page"; +import { MATRIX_TRANSLATIONS_SLUG } from "../translations/page"; + +export const MATRIX_OPTIONS_SLUG = "matrix-options"; + +/** A Matrix option and the demo page that shows it. */ +interface OptionEntry { + option: string; + text: string; + /** The demo page's slug; none for an option no page sets. */ + page?: string; +} + +const PAGE_NAMES: Record = { + [MATRIX_OPTIONS_SLUG]: "This page", + [MATRIX_RECORDS_SLUG]: "Records", + [MATRIX_TRANSLATIONS_SLUG]: "Translations", + [MATRIX_STOCK_SLUG]: "Stock", + [MATRIX_ALLOCATION_SLUG]: "Allocation", + [MATRIX_ROSTER_SLUG]: "Roster", +}; + +function optionList(title: string, entries: OptionEntry[]) { + return KeyValueList({ + title, + dense: true, + items: entries.map(({ option, text, page }) => ({ + label: option, + value: text, + detail: page ? PAGE_NAMES[page] : "Not shown in a demo", + to: page ? matrixPagePath(page) : undefined, + })), + }); +} + +const QUARTERS: MatrixData = { + columns: [ + { id: "q1", label: "Q1", kind: "number", align: "end" }, + { id: "q2", label: "Q2", kind: "number", align: "end" }, + { id: "q3", label: "Q3", kind: "number", align: "end" }, + { + id: "q4", + label: "Q4", + kind: "number", + align: "end", + badge: "Forecast", + badgeTone: "info", + }, + ], + rows: [ + { + id: "LG4", + label: "LG4", + description: "Liège Médiacité", + values: { q1: 182, q2: 205, q3: 171, q4: 240 }, + tone: "primary", + }, + { + id: "NE1", + label: "NE1", + description: "Namur Esplanade", + values: { q1: 131, q2: 144, q3: 120, q4: 166 }, + }, + { + id: "LUX29", + label: "LUX29", + description: "Luxembourg Cloche d'Or", + values: { q1: 96, q2: 88, q3: 74, q4: 110 }, + cells: { q3: { tone: "error", issues: ["Below the 80 k€ floor"] } }, + }, + { + id: "WEB", + label: "WEB", + description: "E-shop", + values: { q1: 210, q2: 236, q3: 251, q4: 320 }, + cells: { q4: { hint: "+27 %" } }, + }, + ], + footer: "Revenue in thousands of euros, 2026.", +}; + +const DECLARATION = `static revenue = Matrix({ + title: "Revenue by quarter (k€)", + staticData: QUARTERS, // or fetchUrl: "/api/…" answering MatrixData + rowHeader: { label: "Store" }, + totals: { rows: true, columns: true }, + crossHighlight: true, + legend: [{ label: "Below the floor", tone: "error" }], +}); + +// Editable: add a route receiving { changes: [{ rowId, columnId, value, previous }] } +// and answering { rows?, errors?, conflicts? }. +static stock = Matrix({ fetchUrl, saveUrl, editTrigger: "click", saveMode: "staged" });`; + +@RegisterPage() +export class PageMatrixOptions extends PageController( + MATRIX_OPTIONS_SLUG, + { + displayName: "Matrix — overview", + icon: "i-ph-grid-nine", + category: matrixCategory, + order: 0, + description: + "The Matrix block: a grid of rows by columns read and edited in place. A small read-only one from static data, its declaration, and every option with the page that demonstrates it.", + }, + DefaultLayout(), +) { + static revenue = Matrix({ + title: "Revenue by quarter (k€)", + description: + "staticData: no route. Totals both ways, a cross highlight, server-side cell states.", + staticData: QUARTERS, + rowHeader: { label: "Store", width: 200 }, + totals: { rows: true, columns: true }, + crossHighlight: true, + legend: [ + { label: "Your store", tone: "primary" }, + { label: "Below the floor", tone: "error" }, + ], + }); + + static declaration = CodeBlock({ + title: "Declaring it", + language: "typescript", + code: DECLARATION, + }); + + static data = optionList("Data", [ + { + option: "fetchUrl / staticData", + text: "Where the rows come from: a route answering MatrixData, or the options themselves.", + page: MATRIX_OPTIONS_SLUG, + }, + { + option: "columns", + text: "Declared on the block (kind, width, min / max, integer, nullable, required, options of a select).", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "columns from the response", + text: "The route adds the columns it alone knows (languages, sizes) and wins for an id both declare.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "column badge / progress", + text: "A pill and a meter under a header (Base, 12 missing, coverage).", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "column display", + text: "A table view cell display drawing a read-only value (status_pill).", + page: MATRIX_STOCK_SLUG, + }, + { + option: "column hidden / pinned", + text: "Hidden until shown from the columns menu; stuck after the row header.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "rowHeader", + text: "The sticky first column: its label, width, and row numbers across pages (numbers).", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "row description / tone / group", + text: "A dimmed line under the label, a highlighted row, the group it is filed under.", + page: MATRIX_ROSTER_SLUG, + }, + { + option: "cell tone / hint / disabled", + text: "Server-side cell states: an alert tone, a small figure in the corner, a hatched cell.", + page: MATRIX_STOCK_SLUG, + }, + { + option: "cell placeholder / issues", + text: "The base text greyed in an empty cell; warnings on a cell.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "cell previous", + text: "The old value struck through before the new one.", + page: MATRIX_ALLOCATION_SLUG, + }, + { + option: "realtimeTopic", + text: "Reads the route again on each event of the topics, as every block does.", + }, + ]); + + static editing = optionList("Editing", [ + { + option: "saveUrl / editable", + text: "Where edits are written ({ changes } → { rows, errors, conflicts }); no saveUrl, no editing.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "editTrigger: doubleClick", + text: "A click selects, a double click or Enter edits.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "editTrigger: click", + text: "A click edits.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "typeToEdit", + text: "Typing on a selected cell starts editing with that character.", + page: MATRIX_ALLOCATION_SLUG, + }, + { + option: "editIn (auto)", + text: "json, code, keyValue and long texts are edited in a drawer.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "saveMode: staged", + text: "Edits kept, the old value struck through, written together from a save bar.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "review / undoSeconds", + text: "Lists before → after before writing; an Undo after the save.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "saveMode: immediate", + text: "Each cell written as it is left (Saving → Saved, Retry).", + page: MATRIX_ROSTER_SLUG, + }, + { + option: "conflicts: detect", + text: "The route answers a conflict when the value moved; Overwrite or Discard.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "enterMove", + text: "Where Enter goes after saving: down, right, or stay.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "errors", + text: "Per-cell and per-row refusals of the route, kept in the cell with the message.", + page: MATRIX_ROSTER_SLUG, + }, + { + option: "rowPanel", + text: "A row in a drawer, one field per column, with a JSON tab (showJson).", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "cellAction", + text: "What a click on a read-only cell opens, {{row.id}} and {{row.column}} filled.", + page: MATRIX_STOCK_SLUG, + }, + { + option: "fillActions", + text: "Server-computed fills: the rows posted, the { changes } applied as edits.", + page: MATRIX_ALLOCATION_SLUG, + }, + { + option: "targets (blockSave)", + text: "Expected totals; a missed one turns red and holds the save.", + page: MATRIX_ALLOCATION_SLUG, + }, + ]); + + static navigation = optionList("Reading and filtering", [ + { + option: "pagination: pages", + text: "Server paging with pageSize and the pageSizes offered.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "pagination: infinite", + text: "The next rows read while scrolling.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "sortable", + text: "Header clicks send sort and direction.", + page: MATRIX_RECORDS_SLUG, + }, + { option: "search", text: "Sent as search.", page: MATRIX_RECORDS_SLUG }, + { + option: "facets", + text: "Select filters sent as facet_=a,b, choices static or answered.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "statusFilters", + text: "Segments sent as status=, with the response's counts.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "grouping (server groups)", + text: "Each row names its group, the response's groups describe them; collapsible, counted, collapsed past a row count.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "grouping.groupByField", + text: "Rows grouped on a column's value, the route listing them sorted on it.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "grouping.subtotals", + text: "With totals.columns, each group header carries its own column sums.", + page: MATRIX_STOCK_SLUG, + }, + { + option: "jumpToEmpty / keepEditedRows", + text: "N / Shift+N to the next empty cell; edited rows kept on screen after they stop matching.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "urlState", + text: "Page, search, status and facets kept in the page URL (on by default).", + page: MATRIX_TRANSLATIONS_SLUG, + }, + ]); + + static display = optionList("Display", [ + { + option: "totals", + text: "A Total column, a Total row, or both; excludeFromTotals leaves a column out.", + page: MATRIX_STOCK_SLUG, + }, + { + option: "crossHighlight", + text: "Lights the hovered cell's row and column.", + page: MATRIX_STOCK_SLUG, + }, + { + option: "legend", + text: "Entries under the grid, a tone or the hatching.", + page: MATRIX_ROSTER_SLUG, + }, + { + option: "columnsMenu / resizableColumns", + text: "Show, hide, reorder and resize the columns, remembered on the device.", + page: MATRIX_RECORDS_SLUG, + }, + { + option: "exportCsv", + text: "The rows shown as a CSV file.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "footer", + text: "A line the route answers under the grid.", + page: MATRIX_TRANSLATIONS_SLUG, + }, + { + option: "density / maxHeight / emptyLabel", + text: "Row height, a scrolling height, the words of an empty grid.", + page: MATRIX_RECORDS_SLUG, + }, + ]); +} diff --git a/packages/dms/playground/src/matrix/query.ts b/packages/dms/playground/src/matrix/query.ts new file mode 100644 index 000000000..7082f9626 --- /dev/null +++ b/packages/dms/playground/src/matrix/query.ts @@ -0,0 +1,165 @@ +import type { MatrixFacetItem } from "@antelopejs/interface-dms/base/matrix"; + +const FACET_PREFIX = "facet_"; +const LIST_SEPARATOR = ","; +const DESCENDING = "desc"; +// Park-Miller's minimal standard generator, and the FNV-1a 32-bit hash. +const PARK_MILLER_MULTIPLIER = 48271; +const PARK_MILLER_MODULUS = 2147483647; +const FNV_OFFSET_BASIS = 2166136261; +const FNV_PRIME = 16777619; +const PERCENT = 100; + +export type SortDirection = "asc" | "desc"; + +/** + * What a Matrix sends its `fetchUrl`: `offset` and `limit` when paginated, + * `search`, `status`, `sort` and `direction`, and one `facet_=a,b` per + * facet in use. + */ +export interface MatrixQuery { + offset: number; + /** Absent: every row from `offset`. */ + limit?: number; + /** Lower-cased and trimmed; empty when there is no search. */ + search: string; + status?: string; + sort?: string; + direction: SortDirection; + /** The values picked in each facet, by facet id. */ + facets: Record; +} + +/** Reads a value of an item by a column id, for sorting. */ +export type CellReader = (item: T, columnId: string) => unknown; + +function readFacets(params: URLSearchParams): Record { + const facets: Record = {}; + params.forEach((value, key) => { + if (!key.startsWith(FACET_PREFIX)) return; + const picked = value.split(LIST_SEPARATOR).filter(Boolean); + if (picked.length) facets[key.slice(FACET_PREFIX.length)] = picked; + }); + return facets; +} + +function readPositive(params: URLSearchParams, key: string): number { + const value = Number(params.get(key)); + return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0; +} + +/** Parses the query string a Matrix sends its route. */ +export function readMatrixQuery(params: URLSearchParams): MatrixQuery { + const limit = readPositive(params, "limit"); + return { + offset: readPositive(params, "offset"), + limit: limit || undefined, + search: (params.get("search") ?? "").trim().toLowerCase(), + status: params.get("status") || undefined, + sort: params.get("sort") || undefined, + direction: params.get("direction") === DESCENDING ? "desc" : "asc", + facets: readFacets(params), + }; +} + +/** The slice of the matching items the grid asked for. */ +export function pageOf(items: T[], query: MatrixQuery): T[] { + const end = + query.limit === undefined ? undefined : query.offset + query.limit; + return items.slice(query.offset, end); +} + +/** Whether a facet lets a value through: an unused facet lets everything. */ +export function facetAllows( + query: MatrixQuery, + facetId: string, + value: string, +): boolean { + const picked = query.facets[facetId]; + return !picked || picked.includes(value); +} + +/** Whether any of the texts holds the search (already lower-cased). */ +export function matchesSearch(search: string, texts: unknown[]): boolean { + if (!search) return true; + return texts.some( + (text) => + text !== null && + text !== undefined && + searchableText(text).toLowerCase().includes(search), + ); +} + +function searchableText(value: unknown): string { + if (typeof value === "string") return value; + return JSON.stringify(value) ?? ""; +} + +function isEmpty(value: unknown): boolean { + return value === null || value === undefined || value === ""; +} + +/** + * Orders two cell values: empty ones last, numbers and booleans by value, the + * rest (dates as ISO strings, texts, objects) as text. + */ +export function compareCells(left: unknown, right: unknown): number { + if (isEmpty(left) || isEmpty(right)) { + return Number(isEmpty(left)) - Number(isEmpty(right)); + } + if (typeof left === "number" || typeof left === "boolean") { + return Number(left) - Number(right); + } + return searchableText(left).localeCompare(searchableText(right)); +} + +/** The items ordered by the column the grid sorts on, when it sorts. */ +export function sortItems( + items: T[], + query: MatrixQuery, + read: CellReader, +): T[] { + const { sort } = query; + if (!sort) return items; + const sign = query.direction === DESCENDING ? -1 : 1; + return [...items].sort( + (left, right) => compareCells(read(left, sort), read(right, sort)) * sign, + ); +} + +/** The facet choices of a list, each with how many items hold it. */ +export function facetItems( + items: T[], + valueOf: (item: T) => string, + labels: Record, +): MatrixFacetItem[] { + const counts = new Map(); + for (const item of items) { + const value = valueOf(item); + counts.set(value, (counts.get(value) ?? 0) + 1); + } + return Object.entries(labels).map(([value, label]) => ({ + value, + label, + count: counts.get(value) ?? 0, + })); +} + +/** A small deterministic generator, so every restart seeds the same data. */ +export function seededRandom(seed: number): () => number { + let state = seed; + return () => { + state = (state * PARK_MILLER_MULTIPLIER) % PARK_MILLER_MODULUS; + return state / PARK_MILLER_MODULUS; + }; +} + +/** A stable number from 0 to 99 for a text: which cell is missing, which is wrong. */ +export function percentileOf(text: string): number { + let hash = FNV_OFFSET_BASIS; + for (let index = 0; index < text.length; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, FNV_PRIME); + } + return Math.abs(hash) % PERCENT; +} diff --git a/packages/dms/playground/src/matrix/records/api.ts b/packages/dms/playground/src/matrix/records/api.ts new file mode 100644 index 000000000..9aeec3d6e --- /dev/null +++ b/packages/dms/playground/src/matrix/records/api.ts @@ -0,0 +1,304 @@ +import { + Context, + Controller, + Get, + JSONBody, + Post, + type RequestContext, +} from "@antelopejs/interface-api"; +import type { User } from "@antelopejs/interface-dms/auth/db"; +import type { + MatrixCellError, + MatrixCellState, + MatrixChange, + MatrixData, + MatrixRow, + MatrixSaveRequest, + MatrixSaveResponse, +} from "@antelopejs/interface-dms/base/matrix"; +import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards"; +import { + facetAllows, + facetItems, + type MatrixQuery, + matchesSearch, + pageOf, + readMatrixQuery, + sortItems, +} from "../query"; +import { cellError, readSaveRequest, rowError, touchedRowIds } from "../save"; +import { + HTTP_METHODS, + PURGED_REF, + REQUEST_DOCUMENTS, + REQUEST_LABELS, + type RequestDocument, + type RequestField, +} from "./data"; +import { MATRIX_RECORDS_API, PageMatrixRecords } from "./page"; + +const STATUS_CLASS_SIZE = 100; +const LOWEST_STATUS = 100; +const HIGHEST_STATUS = 599; +const CLIENT_ERROR = 400; +const SERVER_ERROR = 500; +const SLOW_MS = 900; +const MAX_PATH_LENGTH = 2048; +const MAX_NOTE_LENGTH = 4000; +const GROUP_BY_KEY = "groupBy"; + +const STATUS_CLASSES: Record = { + "2xx": "2xx Success", + "3xx": "3xx Redirect", + "4xx": "4xx Client error", + "5xx": "5xx Server error", +}; + +const DOCUMENT_KEYS: (keyof RequestDocument)[] = [ + "_id", + "ref", + "method", + "path", + "status", + "durationMs", + "cached", + "receivedAt", + "client", + "headers", + "body", + "sql", + "labels", + "notes", +]; + +type CellValue = MatrixChange["value"]; + +/** Why a value does not fit its field, or `undefined` when it does. */ +type FieldCheck = (value: CellValue) => string | undefined; + +const isNullOr = + (check: FieldCheck): FieldCheck => + (value) => + value === null ? undefined : check(value); + +function isHeaderMap(value: CellValue): boolean { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return false; + } + return Object.values(value).every((header) => typeof header === "string"); +} + +const FIELD_CHECKS: Record = { + method: (value) => + HTTP_METHODS.some((method) => method === value) + ? undefined + : `Expected one of ${HTTP_METHODS.join(", ")}.`, + path: (value) => + typeof value === "string" && + value.startsWith("/") && + value.length <= MAX_PATH_LENGTH + ? undefined + : "A path starts with /.", + status: (value) => + Number.isInteger(value) && + Number(value) >= LOWEST_STATUS && + Number(value) <= HIGHEST_STATUS + ? undefined + : `An HTTP status is a whole number from ${LOWEST_STATUS} to ${HIGHEST_STATUS}.`, + durationMs: isNullOr((value) => + typeof value === "number" && Number.isFinite(value) && value >= 0 + ? undefined + : "A duration is a positive number of milliseconds, or null.", + ), + cached: (value) => + typeof value === "boolean" ? undefined : "Expected true or false.", + receivedAt: (value) => + typeof value === "string" && !Number.isNaN(Date.parse(value)) + ? undefined + : "Expected a date.", + client: isNullOr((value) => + typeof value === "string" && value.trim() + ? undefined + : "A client is a name, or null for an anonymous call.", + ), + headers: (value) => + isHeaderMap(value) ? undefined : "Headers are names with text values.", + body: (value) => + value === null || typeof value === "object" + ? undefined + : "A request body is an object, an array or null.", + sql: (value) => + typeof value === "string" && value.trim() + ? undefined + : "The statement cannot be empty.", + labels: (value) => + Array.isArray(value) && + value.every((label) => REQUEST_LABELS.some((known) => known === label)) + ? undefined + : `Labels are among ${REQUEST_LABELS.join(", ")}.`, + notes: isNullOr((value) => + typeof value === "string" && value.length <= MAX_NOTE_LENGTH + ? undefined + : `A note holds ${MAX_NOTE_LENGTH} characters at most.`, + ), +}; + +function isDocumentKey(columnId: string): columnId is keyof RequestDocument { + return DOCUMENT_KEYS.some((key) => key === columnId); +} + +function isWritableField(columnId: string): columnId is RequestField { + return columnId in FIELD_CHECKS; +} + +function statusClass(status: number): string { + return `${Math.floor(status / STATUS_CLASS_SIZE)}xx`; +} + +function statusTone(status: number): MatrixCellState["tone"] { + if (status >= SERVER_ERROR) return "error"; + if (status >= CLIENT_ERROR) return "warning"; + return undefined; +} + +function cellStates( + document: RequestDocument, +): Record { + const cells: Record = {}; + const tone = statusTone(document.status); + if (tone) cells.status = { tone }; + if (document.durationMs === null) { + cells.durationMs = { tone: "error", placeholder: "timed out" }; + } else if (document.durationMs > SLOW_MS) { + cells.durationMs = { tone: "warning" }; + } + return cells; +} + +function toRow(document: RequestDocument): MatrixRow { + return { + id: document._id, + label: document.ref, + values: { ...document }, + cells: cellStates(document), + }; +} + +function readField(document: RequestDocument, columnId: string): CellValue { + return isDocumentKey(columnId) ? document[columnId] : undefined; +} + +function searchDocuments(query: MatrixQuery): RequestDocument[] { + return REQUEST_DOCUMENTS.filter((document) => + matchesSearch(query.search, [ + document.ref, + document._id, + document.path, + document.client, + document.notes, + ]), + ); +} + +/** + * The rows ordered on the field a grouped grid groups on (`?groupBy=method`), + * the requested sort kept inside each group: a group's rows follow each other, + * as `grouping.groupByField` expects. + */ +function groupedFirst( + documents: RequestDocument[], + field: string | null, +): RequestDocument[] { + if (!field || !isDocumentKey(field)) return documents; + return sortItems( + documents, + { offset: 0, search: "", direction: "asc", facets: {}, sort: field }, + readField, + ); +} + +function findDocument(id: string): RequestDocument | undefined { + return REQUEST_DOCUMENTS.find((document) => document._id === id); +} + +function applyChange( + document: RequestDocument, + change: MatrixChange, +): MatrixCellError | undefined { + const { columnId } = change; + if (!isWritableField(columnId)) { + return cellError(change, `${columnId} is read-only.`); + } + const problem = FIELD_CHECKS[columnId](change.value); + if (problem) return cellError(change, problem); + Object.assign(document, { [columnId]: change.value }); + return undefined; +} + +function saveRow(rowId: string, changes: MatrixChange[]): MatrixCellError[] { + const document = findDocument(rowId); + if (!document) return [rowError(rowId, "This document no longer exists.")]; + if (document.ref === PURGED_REF) { + return [ + rowError( + rowId, + "The retention job purged this document after you opened the page: reload to drop it.", + ), + ]; + } + return changes + .filter((change) => change.rowId === rowId) + .map((change) => applyChange(document, change)) + .filter((error): error is MatrixCellError => !!error); +} + +/** + * The routes of the "Records" demo: a collection browser over the + * in-memory `api_requests` documents. The list searches, filters, sorts and + * pages on the server; the save checks each cell against its field and + * answers the rows it wrote, and a row error for the purged document. + */ +export class MatrixRecordsController extends Controller(MATRIX_RECORDS_API) { + @AuthUserWithPermission(PageMatrixRecords) + declare user: User; + + @Get("rows") + list(@Context() ctx: RequestContext): MatrixData { + const query = readMatrixQuery(ctx.url.searchParams); + const searched = searchDocuments(query); + const byMethod = searched.filter((document) => + facetAllows(query, "method", document.method), + ); + const matching = byMethod.filter((document) => + facetAllows(query, "status", statusClass(document.status)), + ); + const sorted = groupedFirst( + sortItems(matching, query, readField), + ctx.url.searchParams.get(GROUP_BY_KEY), + ); + return { + rows: pageOf(sorted, query).map(toRow), + total: matching.length, + facets: { + status: facetItems( + byMethod, + (document) => statusClass(document.status), + STATUS_CLASSES, + ), + }, + }; + } + + @Post("save") + save(@JSONBody() body: MatrixSaveRequest): MatrixSaveResponse { + const { changes } = readSaveRequest(body); + const rowIds = touchedRowIds(changes); + const errors = rowIds.flatMap((rowId) => saveRow(rowId, changes)); + const rows = rowIds + .map(findDocument) + .filter((document): document is RequestDocument => !!document) + .filter((document) => document.ref !== PURGED_REF) + .map(toRow); + return { rows, errors }; + } +} diff --git a/packages/dms/playground/src/matrix/records/data.ts b/packages/dms/playground/src/matrix/records/data.ts new file mode 100644 index 000000000..0e8daa3a8 --- /dev/null +++ b/packages/dms/playground/src/matrix/records/data.ts @@ -0,0 +1,348 @@ +import { seededRandom } from "../query"; + +/** A JSON value, as a document field holds it. */ +export type JsonValue = + | string + | number + | boolean + | null + | JsonValue[] + | JsonObject; + +/** A JSON object: a request body, a nested document. */ +export interface JsonObject { + [key: string]: JsonValue; +} + +export const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; +export type HttpVerb = (typeof HTTP_METHODS)[number]; + +export const REQUEST_LABELS = ["slow", "retried", "flagged", "internal"]; + +/** + * A document of the `api_requests` collection, as a database browser lists + * it: scalar fields, a nested body, headers, the SQL the request ran and + * free notes, some of them empty (`null`). + */ +export interface RequestDocument { + _id: string; + ref: string; + method: HttpVerb; + path: string; + status: number; + durationMs: number | null; + cached: boolean; + receivedAt: string; + client: string | null; + headers: Record; + body: JsonValue; + sql: string; + labels: string[]; + notes: string | null; +} + +/** The fields a save may write, all of them but the ids. */ +export type RequestField = Exclude; + +interface RouteTemplate { + method: HttpVerb; + path: (serial: number) => string; + body: (serial: number) => JsonValue; + sql: string; + statuses: number[]; +} + +const DOCUMENT_COUNT = 300; +const SEED = 20261025; +const STEP_MINUTES = 7; +const MINUTE_MS = 60_000; +const LOG_END = Date.parse("2026-10-25T09:00:00.000Z"); +const OBJECT_ID_MACHINE = "b7e21c4a90"; +const OBJECT_ID_COUNTER = 0x3f2a10; +const HEX = 16; +const SECONDS_MS = 1000; +const MAX_DURATION_MS = 1800; +const MIN_DURATION_MS = 12; +const SLOW_RATIO = 0.08; +const CACHED_RATIO = 0.3; +const NOTE_RATIO = 0.12; +const LABEL_RATIO = 0.2; +const TIMEOUT_STATUS = 504; +const SERVER_ERROR = 500; +const SLOW_MS = 900; +const TYPICAL_DURATION_SPREAD_MS = 300; +const REF_DIGITS = 4; +const ARTICLE = "A260191"; +const SIZES = [36, 37, 38, 39, 40, 41, 42]; +const STORES = ["ENT", "NE1", "LG4", "LUX29", "WEB"]; + +const CLIENTS: (string | null)[] = [ + "pos-lg4", + "pos-ne1", + "pos-lux29", + "eshop-front", + "backoffice", + "stripe-webhook", + null, +]; + +const USER_AGENTS: Record = { + "pos-lg4": "AltabPOS/4.2 (Windows 11; LG4-caisse-1)", + "pos-ne1": "AltabPOS/4.2 (Windows 11; NE1-caisse-2)", + "pos-lux29": "AltabPOS/4.1 (iPadOS 18; LUX29-tablette)", + "eshop-front": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6) Safari/605.1", + backoffice: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/141.0", + "stripe-webhook": "Stripe/1.0 (+https://stripe.com/docs/webhooks)", +}; + +function pick(items: readonly T[], serial: number): T { + return items[serial % items.length]!; +} + +function orderBody(serial: number): JsonValue { + const size = pick(SIZES, serial); + return { + customerId: `cus_${(serial * 7919).toString(HEX)}`, + lines: [ + { + sku: `${ARTICLE}-${size}`, + label: "Tamaris Bottine Alma", + qty: 1, + unitPrice: 89.95, + }, + ...(serial % 3 === 0 + ? [ + { + sku: "CARE-SPRAY-200", + label: "Spray imperméabilisant", + qty: 1, + unitPrice: 9.5, + }, + ] + : []), + ], + shipping: { + method: serial % 2 ? "pickup" : "home", + store: pick(STORES, serial), + }, + coupon: serial % 5 === 0 ? "AUTOMNE10" : null, + }; +} + +function transferBody(serial: number): JsonValue { + return [ + { + sku: `${ARTICLE}-${pick(SIZES, serial)}`, + from: "ENT", + to: pick(STORES, serial + 1), + qty: 2, + }, + { + sku: `${ARTICLE}-${pick(SIZES, serial + 2)}`, + from: "ENT", + to: pick(STORES, serial + 1), + qty: 1, + }, + ]; +} + +const ROUTES: RouteTemplate[] = [ + { + method: "GET", + path: (serial) => `/api/orders?status=paid&page=${(serial % 4) + 1}`, + body: () => null, + sql: "SELECT o.id, o.total, c.email\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nWHERE o.status = 'paid'\nORDER BY o.created_at DESC\nLIMIT 50 OFFSET 50;", + statuses: [200, 200, 200, 304, 401], + }, + { + method: "POST", + path: () => "/api/orders", + body: orderBody, + sql: "INSERT INTO orders (customer_id, store, total)\nVALUES ($1, $2, $3)\nRETURNING id;", + statuses: [201, 201, 201, 422, 409], + }, + { + method: "PATCH", + path: (serial) => `/api/orders/ord_${4100 + serial}`, + body: (serial) => ({ + status: pick(["shipped", "ready_for_pickup", "cancelled"], serial), + }), + sql: "UPDATE orders\nSET status = $2, updated_at = now()\nWHERE id = $1;", + statuses: [200, 200, 404, 409], + }, + { + method: "GET", + path: (serial) => + `/api/stock/levels?article=${ARTICLE}&store=${pick(STORES, serial)}`, + body: () => null, + sql: "SELECT size, quantity, min_quantity\nFROM stock_levels\nWHERE article = $1 AND store = $2\nORDER BY size;", + statuses: [200, 200, 200, 200, 500], + }, + { + method: "POST", + path: () => "/api/stock/transfers", + body: transferBody, + sql: "INSERT INTO stock_transfers (sku, from_store, to_store, qty)\nSELECT * FROM jsonb_to_recordset($1)\n AS t(sku text, from_store text, to_store text, qty int);", + statuses: [201, 201, 422, 503], + }, + { + method: "PUT", + path: (serial) => `/api/customers/cus_${(serial * 7919).toString(HEX)}`, + body: (serial) => ({ + firstName: pick( + ["Charlotte", "Julie", "Mehdi", "Sophie", "Inès"], + serial, + ), + lastName: pick( + ["Hubert", "Lambert", "Bensaïd", "Dubois", "Moreau"], + serial, + ), + newsletter: serial % 2 === 0, + tags: ["fidélité", pick(["vip", "eshop", "magasin"], serial)], + }), + sql: "UPDATE customers\nSET first_name = $2, last_name = $3, newsletter = $4\nWHERE id = $1;", + statuses: [200, 200, 400, 404], + }, + { + method: "DELETE", + path: (serial) => + `/api/customers/cus_${(serial * 7919).toString(HEX)}/addresses/${serial % 3}`, + body: () => null, + sql: "DELETE FROM customer_addresses\nWHERE customer_id = $1 AND position = $2;", + statuses: [204, 204, 404], + }, + { + method: "POST", + path: () => "/api/webhooks/stripe", + body: (serial) => ({ + id: `evt_${(serial * 104729).toString(HEX)}`, + type: pick( + [ + "payment_intent.succeeded", + "charge.refunded", + "charge.dispute.created", + ], + serial, + ), + data: { object: { amount: 8995 + (serial % 3) * 950, currency: "eur" } }, + }), + sql: "INSERT INTO payment_events (provider_id, type, payload)\nVALUES ($1, $2, $3)\nON CONFLICT (provider_id) DO NOTHING;", + statuses: [200, 200, 200, 400], + }, + { + method: "GET", + path: () => "/api/health", + body: () => null, + sql: "SELECT 1;", + statuses: [200, 200, 200, 200, 503], + }, + { + method: "GET", + path: (serial) => + `/api/reports/sales?from=2026-10-${String((serial % 20) + 1).padStart(2, "0")}&store=${pick(STORES, serial)}`, + body: () => null, + sql: "SELECT date_trunc('day', created_at) AS day, sum(total) AS revenue\nFROM orders\nWHERE store = $1 AND created_at >= $2\nGROUP BY 1\nORDER BY 1;", + statuses: [200, 200, TIMEOUT_STATUS, SERVER_ERROR], + }, +]; + +const LONG_NOTES = [ + "Incident INC-2291 (24/10): la base de reporting a saturé pendant la clôture du mois.\nLa requête a été relancée à la main par Antony après l'ajout de l'index sur orders(created_at).\nÀ surveiller lors de la prochaine clôture : si le temps dépasse encore 30 s, passer le rapport en tâche de fond.", + "Le terminal de caisse a renvoyé trois fois la même commande après une coupure Wi-Fi.\nLes doublons ont été annulés côté back-office ; le client n'a été débité qu'une fois (vérifié dans Stripe).", + "Webhook Stripe reçu avant la création de la commande (course entre l'e-shop et le paiement).\nRejoué automatiquement 2 minutes plus tard, sans perte.", +]; + +const SHORT_NOTES = [ + "Relancé par le client", + "Vérifié avec le magasin", + "Doublon ignoré", + "Ticket support #8812", +]; + +function noteFor(status: number, random: () => number): string | null { + if (status >= SERVER_ERROR) + return pick(LONG_NOTES, Math.floor(random() * HEX)); + if (random() < NOTE_RATIO) + return pick(SHORT_NOTES, Math.floor(random() * HEX)); + return null; +} + +function durationFor(status: number, random: () => number): number | null { + if (status === TIMEOUT_STATUS) return null; + const spread = + random() < SLOW_RATIO ? MAX_DURATION_MS : TYPICAL_DURATION_SPREAD_MS; + return Math.round(MIN_DURATION_MS + random() * spread); +} + +function headersFor( + route: RouteTemplate, + client: string | null, + serial: number, +): Record { + const headers: Record = { + accept: "application/json", + "x-request-id": `rq-${(serial * 2654435761).toString(HEX).slice(-8)}`, + }; + if (client) headers["user-agent"] = USER_AGENTS[client] ?? "curl/8.9.1"; + if (route.method !== "GET" && route.method !== "DELETE") + headers["content-type"] = "application/json"; + if (client?.startsWith("pos-")) + headers["x-store"] = client.slice("pos-".length).toUpperCase(); + return headers; +} + +function labelsFor(durationMs: number | null, random: () => number): string[] { + const labels: string[] = []; + if (durationMs === null || durationMs > SLOW_MS) labels.push("slow"); + if (random() < LABEL_RATIO) + labels.push(pick(REQUEST_LABELS.slice(1), Math.floor(random() * HEX))); + return labels; +} + +function objectId(serial: number, at: number): string { + const seconds = Math.floor(at / SECONDS_MS).toString(HEX); + return `${seconds}${OBJECT_ID_MACHINE}${(OBJECT_ID_COUNTER + serial).toString(HEX)}`; +} + +function buildDocument(serial: number, random: () => number): RequestDocument { + const route = pick(ROUTES, Math.floor(random() * ROUTES.length)); + const status = pick( + route.statuses, + Math.floor(random() * route.statuses.length), + ); + const at = LOG_END - (DOCUMENT_COUNT - serial) * STEP_MINUTES * MINUTE_MS; + const client = pick(CLIENTS, Math.floor(random() * CLIENTS.length)); + const durationMs = durationFor(status, random); + return { + _id: objectId(serial, at), + ref: `req-${String(serial).padStart(REF_DIGITS, "0")}`, + method: route.method, + path: route.path(serial), + status, + durationMs, + cached: route.method === "GET" && random() < CACHED_RATIO, + receivedAt: new Date(at).toISOString(), + client, + headers: headersFor(route, client, serial), + body: route.body(serial), + sql: route.sql, + labels: labelsFor(durationMs, random), + notes: noteFor(status, random), + }; +} + +function seedDocuments(): RequestDocument[] { + const random = seededRandom(SEED); + return Array.from({ length: DOCUMENT_COUNT }, (_, index) => + buildDocument(DOCUMENT_COUNT - index, random), + ); +} + +/** The collection, newest first, kept in memory: a restart seeds it again. */ +export const REQUEST_DOCUMENTS: RequestDocument[] = seedDocuments(); + +/** + * The document the retention job "purged" after the grid read it: still + * listed, but any save on it answers that the row is gone. + */ +export const PURGED_REF = "req-0297"; diff --git a/packages/dms/playground/src/matrix/records/page.ts b/packages/dms/playground/src/matrix/records/page.ts new file mode 100644 index 000000000..2a9698fd2 --- /dev/null +++ b/packages/dms/playground/src/matrix/records/page.ts @@ -0,0 +1,278 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { + Matrix, + type MatrixColumn, + type MatrixSelectOption, +} from "@antelopejs/interface-dms/base/matrix"; +import { demoGuide } from "../../table-view/guide"; +import { MATRIX_API, matrixCategory } from "../category"; +import { HTTP_METHODS, PURGED_REF, REQUEST_LABELS } from "./data"; + +export const MATRIX_RECORDS_SLUG = "matrix-records"; +export const MATRIX_RECORDS_API = `${MATRIX_API}/records`; + +const PAGE_SIZE = 50; +const PAGE_SIZES = [25, 50, 100, 200]; +const UNDO_SECONDS = 10; +const LOWEST_STATUS = 100; +const HIGHEST_STATUS = 599; + +const METHOD_TONES: Record = { + GET: "info", + POST: "success", + PUT: "warning", + PATCH: "warning", + DELETE: "error", +}; + +const METHOD_OPTIONS: MatrixSelectOption[] = HTTP_METHODS.map((method) => ({ + value: method, + label: method, + tone: METHOD_TONES[method], +})); + +const LABEL_OPTIONS: MatrixSelectOption[] = REQUEST_LABELS.map((label) => ({ + value: label, + label, +})); + +// Database style: the headers are the field names, the description their +// stored type, as a collection browser shows them. +const COLUMNS: MatrixColumn[] = [ + { + id: "_id", + label: "_id", + description: "ObjectId", + icon: "i-ph-key", + editable: false, + pinned: true, + width: 230, + }, + { + id: "method", + label: "method", + description: "string", + kind: "select", + options: METHOD_OPTIONS, + width: 110, + }, + { + id: "path", + label: "path", + description: "string", + required: true, + width: 300, + }, + { + id: "status", + label: "status", + description: "int32", + kind: "number", + integer: true, + min: LOWEST_STATUS, + max: HIGHEST_STATUS, + align: "end", + width: 90, + }, + { + id: "durationMs", + label: "durationMs", + description: "double, null: timed out", + kind: "number", + min: 0, + nullable: true, + align: "end", + width: 130, + }, + { + id: "cached", + label: "cached", + description: "bool", + kind: "boolean", + width: 90, + }, + { + id: "receivedAt", + label: "receivedAt", + description: "date", + kind: "date", + width: 190, + }, + { + id: "client", + label: "client", + description: "string, nullable", + nullable: true, + width: 140, + }, + { + id: "headers", + label: "headers", + description: "object (string values)", + kind: "keyValue", + width: 220, + }, + { + id: "body", + label: "body", + description: "object, array or null", + kind: "json", + nullable: true, + width: 260, + }, + { + id: "sql", + label: "sql", + description: "string (SQL)", + kind: "code", + language: "sql", + hidden: true, + width: 260, + }, + { + id: "labels", + label: "labels", + description: "array of strings", + kind: "tags", + options: LABEL_OPTIONS, + width: 170, + }, + { + id: "notes", + label: "notes", + description: "string, nullable", + kind: "longText", + nullable: true, + width: 280, + }, +]; + +// The grouped grid keeps the scalar fields: the grouping is the point. +const GROUPED_COLUMNS = [ + "_id", + "method", + "path", + "status", + "durationMs", + "receivedAt", + "client", +]; + +@RegisterPage() +export class PageMatrixRecords extends PageController( + MATRIX_RECORDS_SLUG, + { + displayName: "Records (database style)", + icon: "i-ph-database", + category: matrixCategory, + order: 10, + description: + "A Matrix as a collection browser: 300 documents of mixed field types, paged, sorted, searched and filtered on the server, edited with a double click, staged, reviewed and saved together, with an undo.", + }, + DefaultLayout({ fullWidth: true }), +) { + static guide = demoGuide([ + { + label: "Double-click a cell", + text: 'editTrigger: "doubleClick": a click selects, the arrows move, Enter or a double click edits. Each kind takes its own input; typing "null" empties a nullable field (durationMs, client, body, notes).', + }, + { + label: "Open body, headers or a long note", + text: 'editIn "auto": json, keyValue and code cells, and texts holding a line break or over 120 characters, are edited in a drawer. sql is hidden: show it from the columns menu.', + }, + { + label: "Edit a few cells, then save", + text: 'saveMode: "staged": each edited cell shows its old value struck through; the save bar\'s review (review: true) lists before → after; an Undo stays 10 s after the save (undoSeconds).', + }, + { + label: `Edit ${PURGED_REF}, then save`, + text: `Search ${PURGED_REF} (4th row). The route answers a row error (the document was purged after the grid read it): the change stays in its row with the message, the others are written.`, + }, + { + label: "Set a status to 700, or a path without /", + text: "The route checks each cell and answers per-cell errors; a body must be an object, an array or null.", + }, + { + label: "Open a whole row", + text: "rowPanel: the ⤢ button of the row header, or Space, opens the document as a form, with a JSON tab (showJson). J / K step through the rows.", + }, + { + label: "Sort, search, filter", + text: "sortable sends sort / direction, search searches ref, _id, path, client and notes, the facets send facet_method=GET,POST and facet_status=4xx,5xx (the status choices and their counts come from the response).", + }, + { + label: "Page through 300 documents", + text: 'pagination: "pages", pageSize 50, pageSizes 25 to 200; rowHeader.numbers numbers the rows across pages.', + }, + { + label: "Resize, hide, export", + text: "resizableColumns, columnsMenu (show, hide, reorder; remembered on the device), exportCsv.", + }, + { + label: "Fold a method group (second grid)", + text: 'grouping: { groupByField: "method", collapsible, count }: a header per method with its row count; the route sorts on the method first (?groupBy=method), the sort you pick applies inside each group.', + }, + ]); + + static records = Matrix({ + title: "api_requests", + description: + "The shop's API log: 300 documents, newest first, kept in memory (a restart reseeds them).", + fetchUrl: `${MATRIX_RECORDS_API}/rows`, + saveUrl: `${MATRIX_RECORDS_API}/save`, + columns: COLUMNS, + rowHeader: { label: "ref", numbers: true, width: 130 }, + editTrigger: "doubleClick", + saveMode: "staged", + review: true, + undoSeconds: UNDO_SECONDS, + rowPanel: { title: "Document", showJson: true }, + pagination: "pages", + pageSize: PAGE_SIZE, + pageSizes: PAGE_SIZES, + sortable: true, + search: true, + facets: [ + { + id: "method", + label: "Method", + icon: "i-ph-arrows-left-right", + multiple: true, + items: METHOD_OPTIONS.map(({ value, label }) => ({ value, label })), + }, + { + id: "status", + label: "Status", + icon: "i-ph-traffic-signal", + multiple: true, + }, + ], + resizableColumns: true, + columnsMenu: true, + exportCsv: true, + emptyLabel: "No document matches the search and the filters.", + density: "compact", + maxHeight: "70vh", + }); + + static byMethod = Matrix({ + title: "api_requests, grouped by method", + description: + "The same documents grouped on a column (grouping.groupByField): the route lists them sorted on the method, each group folds and counts its rows.", + fetchUrl: `${MATRIX_RECORDS_API}/rows?groupBy=method`, + saveUrl: `${MATRIX_RECORDS_API}/save`, + columns: COLUMNS.filter((column) => GROUPED_COLUMNS.includes(column.id)), + rowHeader: { label: "ref", width: 130 }, + grouping: { groupByField: "method", collapsible: true, count: true }, + pagination: "pages", + pageSize: PAGE_SIZE, + sortable: true, + search: true, + // The first grid keeps its state in the URL; two would share the keys. + urlState: false, + saveMode: "staged", + density: "compact", + maxHeight: "60vh", + }); +} diff --git a/packages/dms/playground/src/matrix/roster/api.ts b/packages/dms/playground/src/matrix/roster/api.ts new file mode 100644 index 000000000..ce652d8dd --- /dev/null +++ b/packages/dms/playground/src/matrix/roster/api.ts @@ -0,0 +1,161 @@ +import { Controller, Get, JSONBody, Post } from "@antelopejs/interface-api"; +import type { User } from "@antelopejs/interface-dms/auth/db"; +import type { + MatrixCellError, + MatrixCellState, + MatrixChange, + MatrixData, + MatrixGroup, + MatrixRow, + MatrixSaveRequest, + MatrixSaveResponse, +} from "@antelopejs/interface-dms/base/matrix"; +import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards"; +import { cellError, readSaveRequest, rowError } from "../save"; +import { + MAX_WORKING_DAYS, + PEOPLE, + type Person, + resetRoster, + type Shift, + SHIFT_HOURS, + SHIFT_OPTIONS, + type StoreTeam, + TEAMS, + WEEK, +} from "./data"; +import { MATRIX_ROSTER_API, PageMatrixRoster } from "./page"; + +const HOURS_DECIMALS = 1; + +function isShift(value: MatrixChange["value"]): value is Shift { + return SHIFT_OPTIONS.some((option) => option.value === value); +} + +function hours(value: number): string { + return `${value.toFixed(HOURS_DECIMALS).replace(".", ",")} h`; +} + +function plannedHours(person: Person): number { + return WEEK.reduce((total, day) => { + const shift = person.week[day.id]; + return total + (shift ? (SHIFT_HOURS[shift] ?? 0) : 0); + }, 0); +} + +function workingDays(week: Person["week"]): number { + return WEEK.filter((day) => { + const shift = week[day.id]; + return !!shift && !!SHIFT_HOURS[shift]; + }).length; +} + +function closedCells(): Record { + return Object.fromEntries( + WEEK.filter((day) => day.isClosed).map((day) => [ + day.id, + { disabled: true }, + ]), + ); +} + +function personRow(person: Person): MatrixRow { + const planned = plannedHours(person); + return { + id: person.id, + label: person.name, + description: `${person.role} · ${hours(planned)} / ${person.contractHours} h`, + group: person.store, + values: Object.fromEntries( + WEEK.map((day) => [day.id, person.week[day.id] ?? null]), + ), + cells: closedCells(), + // Planned past the contract: overtime to pay, or a mistake. + tone: planned > person.contractHours ? "warning" : undefined, + }; +} + +function teamGroup(team: StoreTeam): MatrixGroup { + const members = PEOPLE.filter((person) => person.store === team.id); + return { + id: team.id, + label: team.label, + description: team.description, + badge: `${members.length} personnes`, + }; +} + +function teamHours(team: StoreTeam): string { + const total = PEOPLE.filter((person) => person.store === team.id).reduce( + (sum, person) => sum + plannedHours(person), + 0, + ); + return `${team.id} ${hours(total)}`; +} + +function shiftProblem( + person: Person, + change: MatrixChange, +): string | undefined { + const day = WEEK.find((candidate) => candidate.id === change.columnId); + if (!day) return "Jour inconnu."; + if (day.isClosed) return "Les magasins sont fermés ce jour-là."; + if (!isShift(change.value)) + return "Choisissez un horaire, Repos ou une absence."; + const days = workingDays({ ...person.week, [day.id]: change.value }); + if (days > MAX_WORKING_DAYS) { + return `${person.name} travaillerait ${days} jours cette semaine : ${MAX_WORKING_DAYS} au maximum. Posez d'abord un repos un autre jour.`; + } + return undefined; +} + +function applyShift(change: MatrixChange): MatrixCellError | undefined { + const person = PEOPLE.find((candidate) => candidate.id === change.rowId); + if (!person) + return rowError( + change.rowId, + "Cette personne ne fait plus partie de l'équipe.", + ); + const problem = shiftProblem(person, change); + if (problem) return cellError(change, problem); + if (isShift(change.value)) person.week[change.columnId] = change.value; + return undefined; +} + +/** + * The routes of the "Roster" demo: a team's week, one shift per person and + * day. The save refuses a sixth working day and the closed Sunday, per + * cell; each row's description sums the hours planned against the contract. + */ +export class MatrixRosterController extends Controller(MATRIX_ROSTER_API) { + @AuthUserWithPermission(PageMatrixRoster) + declare user: User; + + @Get("rows") + list(): MatrixData { + return { + rows: PEOPLE.map(personRow), + groups: TEAMS.map(teamGroup), + footer: `Heures planifiées cette semaine : ${TEAMS.map(teamHours).join(" · ")}.`, + }; + } + + @Post("save") + save(@JSONBody() body: MatrixSaveRequest): MatrixSaveResponse { + const { changes } = readSaveRequest(body); + const errors = changes + .map(applyShift) + .filter((error): error is MatrixCellError => !!error); + const rowIds = new Set(changes.map((change) => change.rowId)); + return { + rows: PEOPLE.filter((person) => rowIds.has(person.id)).map(personRow), + errors, + }; + } + + @Post("reset") + reset() { + resetRoster(); + return { message: "Planning remis à zéro" }; + } +} diff --git a/packages/dms/playground/src/matrix/roster/data.ts b/packages/dms/playground/src/matrix/roster/data.ts new file mode 100644 index 000000000..a72821812 --- /dev/null +++ b/packages/dms/playground/src/matrix/roster/data.ts @@ -0,0 +1,176 @@ +import type { MatrixSelectOption } from "@antelopejs/interface-dms/base/matrix"; + +/** What a person does on a day. */ +export type Shift = "morning" | "afternoon" | "day" | "off" | "leave" | "sick"; + +export const SHIFT_OPTIONS: MatrixSelectOption[] = [ + { value: "morning", label: "Matin", tone: "info", icon: "i-ph-sun-horizon" }, + { + value: "afternoon", + label: "Après-midi", + tone: "primary", + icon: "i-ph-sun", + }, + { value: "day", label: "Journée", tone: "success", icon: "i-ph-briefcase" }, + { value: "off", label: "Repos", tone: "neutral", icon: "i-ph-coffee" }, + { + value: "leave", + label: "Congé", + tone: "warning", + icon: "i-ph-airplane-tilt", + }, + { value: "sick", label: "Malade", tone: "error", icon: "i-ph-first-aid" }, +]; + +// A full-time week is 38 hours in Belgian retail: 7.6 hours a day, five days. +const FULL_DAY_HOURS = 7.6; +const HALF_DAY_HOURS = 3.8; + +/** The hours a shift counts; the others count none. */ +export const SHIFT_HOURS: Partial> = { + morning: HALF_DAY_HOURS, + afternoon: HALF_DAY_HOURS, + day: FULL_DAY_HOURS, +}; + +/** The most days a person works in a week. */ +export const MAX_WORKING_DAYS = 5; + +export interface Day { + id: string; + label: string; + date: string; + /** The stores are closed: nobody is planned. */ + isClosed?: boolean; +} + +export const WEEK: Day[] = [ + { id: "mon", label: "Lun 26/10", date: "2026-10-26" }, + { id: "tue", label: "Mar 27/10", date: "2026-10-27" }, + { id: "wed", label: "Mer 28/10", date: "2026-10-28" }, + { id: "thu", label: "Jeu 29/10", date: "2026-10-29" }, + { id: "fri", label: "Ven 30/10", date: "2026-10-30" }, + { id: "sat", label: "Sam 31/10", date: "2026-10-31" }, + { id: "sun", label: "Dim 01/11", date: "2026-11-01", isClosed: true }, +]; + +export interface Person { + id: string; + name: string; + role: string; + store: string; + contractHours: number; + week: Partial>; +} + +export interface StoreTeam { + id: string; + label: string; + description: string; +} + +export const TEAMS: StoreTeam[] = [ + { + id: "LG4", + label: "Liège Médiacité", + description: "Ouvert du lundi au samedi, 10 h – 19 h", + }, + { + id: "NE1", + label: "Namur Esplanade", + description: "Ouvert du lundi au samedi, 9 h 30 – 18 h 30", + }, +]; + +type WeekPlan = [Shift, Shift, Shift, Shift, Shift, Shift]; + +function plan(days: WeekPlan): Partial> { + return Object.fromEntries( + days.map((shift, index) => [WEEK[index]!.id, shift]), + ); +} + +function seedPeople(): Person[] { + return [ + { + id: "charlotte-hubert", + name: "Charlotte Hubert", + role: "Responsable magasin", + store: "LG4", + contractHours: 38, + week: plan(["day", "day", "off", "day", "day", "day"]), + }, + { + id: "julie-lambert", + name: "Julie Lambert", + role: "Vendeuse", + store: "LG4", + contractHours: 38, + week: plan(["off", "day", "day", "day", "day", "day"]), + }, + { + id: "mehdi-bensaid", + name: "Mehdi Bensaïd", + role: "Vendeur", + store: "LG4", + contractHours: 30, + week: plan(["morning", "afternoon", "day", "off", "leave", "day"]), + }, + { + id: "sophie-dubois", + name: "Sophie Dubois", + role: "Vendeuse", + store: "LG4", + contractHours: 24, + week: plan(["afternoon", "off", "morning", "afternoon", "off", "day"]), + }, + { + id: "lucas-martin", + name: "Lucas Martin", + role: "Étudiant", + store: "LG4", + contractHours: 12, + week: plan(["off", "off", "afternoon", "off", "off", "day"]), + }, + { + id: "camille-renard", + name: "Camille Renard", + role: "Responsable magasin", + store: "NE1", + contractHours: 38, + week: plan(["day", "day", "day", "off", "day", "day"]), + }, + { + id: "thomas-lejeune", + name: "Thomas Lejeune", + role: "Vendeur", + store: "NE1", + contractHours: 38, + week: plan(["day", "off", "day", "day", "day", "day"]), + }, + { + id: "ines-moreau", + name: "Inès Moreau", + role: "Vendeuse", + store: "NE1", + contractHours: 30, + week: plan(["sick", "sick", "morning", "day", "afternoon", "off"]), + }, + { + id: "nathalie-collard", + name: "Nathalie Collard", + role: "Vendeuse", + store: "NE1", + contractHours: 20, + week: plan(["off", "morning", "off", "morning", "afternoon", "day"]), + }, + ]; +} + +/** The team's week, kept in memory: a restart puts it back. */ +export const PEOPLE: Person[] = seedPeople(); + +/** Puts the week back as it started. */ +export function resetRoster(): void { + PEOPLE.splice(0, PEOPLE.length, ...seedPeople()); +} diff --git a/packages/dms/playground/src/matrix/roster/page.ts b/packages/dms/playground/src/matrix/roster/page.ts new file mode 100644 index 000000000..142cd2721 --- /dev/null +++ b/packages/dms/playground/src/matrix/roster/page.ts @@ -0,0 +1,99 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { + Matrix, + type MatrixColumn, + type MatrixLegendItem, +} from "@antelopejs/interface-dms/base/matrix"; +import { demoGuide } from "../../table-view/guide"; +import { MATRIX_API, matrixCategory } from "../category"; +import { MAX_WORKING_DAYS, SHIFT_OPTIONS, WEEK } from "./data"; + +export const MATRIX_ROSTER_SLUG = "matrix-roster"; +export const MATRIX_ROSTER_API = `${MATRIX_API}/roster`; + +const DAY_WIDTH = 128; + +const DAY_COLUMNS: MatrixColumn[] = WEEK.map((day) => ({ + id: day.id, + label: day.label, + description: day.isClosed ? "Magasins fermés" : undefined, + kind: "select", + options: SHIFT_OPTIONS, + required: true, + align: "center", + width: DAY_WIDTH, +})); + +// The legend reads the shifts' own labels and tones, so it cannot drift +// from the pills drawn in the cells. +const LEGEND: MatrixLegendItem[] = [ + ...SHIFT_OPTIONS.map(({ label, tone }) => ({ label, tone })), + { label: "Magasins fermés", hatched: true }, +]; + +@RegisterPage() +export class PageMatrixRoster extends PageController( + MATRIX_ROSTER_SLUG, + { + displayName: "Roster (labels and tones)", + icon: "i-ph-calendar-check", + category: matrixCategory, + order: 50, + description: + "A team's week: people by days, each cell a shift drawn as a toned pill and picked with a click, saved at once. The route refuses a sixth working day, per cell.", + }, + DefaultLayout({ + fullWidth: true, + headerActions: [ + { + label: "Reset the week", + icon: "i-ph-arrow-counter-clockwise", + target: { + type: "api", + url: `${MATRIX_ROSTER_API}/reset`, + method: "POST", + successMessage: "The week is back as it started", + }, + }, + ], + }), +) { + static guide = demoGuide([ + { + label: "Click a cell, pick a shift", + text: 'A select column whose options carry a tone and an icon: each value is drawn as its pill. editTrigger: "click", saveMode: "immediate": the pick is saved at once.', + }, + { + label: "Give Charlotte Hubert her Wednesday", + text: `She already works ${MAX_WORKING_DAYS} days: the route refuses a sixth one and the cell keeps the error message (errors with a columnId). Set another day to Repos first.`, + }, + { + label: "Read the rows", + text: "Each row's description is the role and the hours planned against the contract, recomputed by the route on each save; a row planned past its contract takes the warning tone.", + }, + { + label: "Hover, read the legend", + text: "crossHighlight lights the person and the day; the legend is built from the options' tones; Sunday is closed (disabled cells, hatched). No totals: the values are labels.", + }, + { + label: "Fold a store", + text: "The people are grouped by store (group, groups), each group collapsible; the footer line sums the hours per store.", + }, + ]); + + static roster = Matrix({ + title: "Planning — semaine du 26 octobre", + description: + "Deux magasins, neuf personnes. Une semaine compte au plus 5 jours travaillés.", + fetchUrl: `${MATRIX_ROSTER_API}/rows`, + saveUrl: `${MATRIX_ROSTER_API}/save`, + columns: DAY_COLUMNS, + rowHeader: { label: "Équipe", width: 250 }, + editTrigger: "click", + saveMode: "immediate", + grouping: { collapsible: true }, + crossHighlight: true, + legend: LEGEND, + }); +} diff --git a/packages/dms/playground/src/matrix/save.ts b/packages/dms/playground/src/matrix/save.ts new file mode 100644 index 000000000..ed8aad9ca --- /dev/null +++ b/packages/dms/playground/src/matrix/save.ts @@ -0,0 +1,80 @@ +import { HTTPResult } from "@antelopejs/interface-api"; +import type { + MatrixCellError, + MatrixChange, + MatrixRow, + MatrixSaveRequest, +} from "@antelopejs/interface-dms/base/matrix"; + +const HTTP_BAD_REQUEST = 400; +const JSON_TYPE = "application/json"; + +/** A 400 naming what the request got wrong, as the playground's routes answer. */ +export function badRequest(message: string): HTTPResult { + return new HTTPResult( + HTTP_BAD_REQUEST, + JSON.stringify({ message }), + JSON_TYPE, + ); +} + +function isChange(change: MatrixChange | null | undefined): boolean { + return ( + !!change && + typeof change.rowId === "string" && + typeof change.columnId === "string" + ); +} + +/** + * The changes a `saveUrl` received, checked for their shape: a body that is + * not a {@link MatrixSaveRequest} fails the whole request with a 400. + */ +export function readSaveRequest( + body: MatrixSaveRequest | undefined, +): MatrixSaveRequest { + const changes = body?.changes; + if (!Array.isArray(changes) || !changes.every(isChange)) { + throw badRequest("Expected { changes: [{ rowId, columnId, value }] }."); + } + return { changes, force: body?.force === true }; +} + +/** The rows a fill action received (`{ rows }`), as the grid shows them. */ +export interface MatrixFillRequest { + rows?: MatrixRow[]; +} + +/** A refusal of one cell, or of a whole row without `columnId`. */ +export function cellError( + change: Pick, + message: string, +): MatrixCellError { + return { rowId: change.rowId, columnId: change.columnId, message }; +} + +/** A refusal of a whole row: the row is gone, or locked. */ +export function rowError(rowId: string, message: string): MatrixCellError { + return { rowId, message }; +} + +function normalized(value: MatrixChange["value"]): string { + if (value === null || value === undefined || value === "") return ""; + return JSON.stringify(value); +} + +/** + * Whether two cell values are the same for a conflict check: an empty + * string, `null` and an absent value all mean an empty cell. + */ +export function sameCellValue( + left: MatrixChange["value"], + right: MatrixChange["value"], +): boolean { + return normalized(left) === normalized(right); +} + +/** The ids of the rows a request touched, once each, in their order. */ +export function touchedRowIds(changes: MatrixChange[]): string[] { + return [...new Set(changes.map((change) => change.rowId))]; +} diff --git a/packages/dms/playground/src/matrix/stock/api.ts b/packages/dms/playground/src/matrix/stock/api.ts new file mode 100644 index 000000000..b24153f2f --- /dev/null +++ b/packages/dms/playground/src/matrix/stock/api.ts @@ -0,0 +1,307 @@ +import { + Controller, + Get, + HTTPResult, + JSONBody, + Parameter, + Post, +} from "@antelopejs/interface-api"; +import type { User } from "@antelopejs/interface-dms/auth/db"; +import type { + MatrixCellState, + MatrixColumn, + MatrixData, + MatrixRow, + MatrixSelectOption, +} from "@antelopejs/interface-dms/base/matrix"; +import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards"; +import { + ARTICLE, + CURRENT_STORE, + findStore, + isInRange, + LAST_DELIVERIES, + SALES_30_DAYS, + SIZES, + STOCK, + type Store, + STORES, + storesByRegion, + WAREHOUSE, +} from "./data"; +import { MATRIX_STOCK_API, PageMatrixStock } from "./page"; + +const HTTP_BAD_REQUEST = 400; +const HTTP_CONFLICT = 409; +const JSON_TYPE = "application/json"; +const BEST_SELLER_PAIRS = 4; +const PERCENT = 100; +const SALES_VIEW = "sales"; + +/** The status of a store's stock of the article, drawn as a pill. */ +type StockStatus = "ok" | "low" | "out" | "transit"; + +const STATUS_OPTIONS: MatrixSelectOption[] = [ + { value: "ok", label: "En stock", tone: "success" }, + { value: "low", label: "Stock bas", tone: "warning" }, + { value: "out", label: "Rupture partielle", tone: "error" }, + { value: "transit", label: "Livraison en route", tone: "info" }, +]; + +const STATUS_PILL_TONES = Object.fromEntries( + STATUS_OPTIONS.map(({ value, tone }) => [value, tone]), +); + +/** What the order form opens with, and what it posts back. */ +interface OrderRequest { + article?: string; + size?: string; + donor?: string; + available?: number; + customer?: string; + phone?: string; + email?: string; + pickupStore?: string; + note?: string; +} + +const sizeColumns = (): MatrixColumn[] => + SIZES.map((size) => ({ + id: size, + label: size, + kind: "number", + integer: true, + align: "center", + width: 64, + })); + +const STOCK_ANNEX: MatrixColumn[] = [ + // What the grid groups on (grouping.groupByField); the group headers show it. + { id: "region", label: "Région", kind: "text", hidden: true, width: 140 }, + { + id: "minimum", + label: "Min.", + description: "Paires à garder par pointure", + kind: "number", + align: "center", + excludeFromTotals: true, + width: 70, + }, + { + id: "delivery", + label: "Dernière livraison", + kind: "text", + width: 140, + }, + { id: "deliveredAt", label: "Le", kind: "date", width: 110 }, + { + id: "status", + label: "Statut", + kind: "select", + options: STATUS_OPTIONS, + display: { type: "status_pill", options: { tones: STATUS_PILL_TONES } }, + width: 170, + }, +]; + +const SALES_ANNEX: MatrixColumn[] = [ + { + id: "sellThrough", + label: "Écoulement", + description: "Ventes ÷ (ventes + stock), en %", + kind: "number", + align: "center", + excludeFromTotals: true, + width: 110, + }, +]; + +function stockStatus(store: Store): StockStatus { + if (LAST_DELIVERIES[store.id]?.inTransit) return "transit"; + const inRange = store.sizes.map((size) => STOCK[store.id]?.[size] ?? 0); + if (inRange.some((pairs) => pairs === 0)) return "out"; + if (inRange.some((pairs) => pairs < store.minimum)) return "low"; + return "ok"; +} + +function rowBase(store: Store): Omit { + const isCurrent = store.id === CURRENT_STORE; + return { + id: store.id, + label: store.id, + description: isCurrent ? `${store.name} · votre magasin` : store.name, + tone: isCurrent ? "primary" : undefined, + }; +} + +type CellTone = (store: Store, pairs: number) => MatrixCellState["tone"]; + +function sizeCells( + store: Store, + quantities: Record, + toneOf: CellTone, +): Record { + const cells: Record = {}; + for (const size of SIZES) { + if (!isInRange(store, size)) { + cells[size] = { disabled: true }; + continue; + } + const tone = toneOf(store, quantities[size] ?? 0); + if (tone) cells[size] = { tone }; + } + return cells; +} + +function sizeValues( + store: Store, + quantities: Record, +): Record { + return Object.fromEntries( + SIZES.map((size) => [ + size, + isInRange(store, size) ? (quantities[size] ?? 0) : null, + ]), + ); +} + +const underMinimum: CellTone = (store, pairs) => + pairs < store.minimum ? "error" : undefined; + +const bestSeller: CellTone = (_store, pairs) => + pairs >= BEST_SELLER_PAIRS ? "success" : undefined; + +function stockRow(store: Store): MatrixRow { + const quantities = STOCK[store.id] ?? {}; + const delivery = LAST_DELIVERIES[store.id]; + return { + ...rowBase(store), + values: { + ...sizeValues(store, quantities), + region: store.region, + minimum: store.minimum, + delivery: delivery?.number ?? null, + deliveredAt: delivery?.date ?? null, + status: stockStatus(store), + }, + cells: sizeCells(store, quantities, underMinimum), + }; +} + +function sum(quantities: Record): number { + return Object.values(quantities).reduce((total, pairs) => total + pairs, 0); +} + +function salesRow(store: Store): MatrixRow { + const sold = SALES_30_DAYS[store.id] ?? {}; + if (store.id === WAREHOUSE) { + return { + ...rowBase(store), + description: `${store.name} · ne vend pas`, + values: { sellThrough: null }, + readOnly: true, + }; + } + const soldPairs = sum(sold); + const stockPairs = sum(STOCK[store.id] ?? {}); + return { + ...rowBase(store), + values: { + ...sizeValues(store, sold), + sellThrough: Math.round((soldPairs / (soldPairs + stockPairs)) * PERCENT), + }, + cells: sizeCells(store, sold, bestSeller), + }; +} + +function refuse(status: number, field: string, message: string): HTTPResult { + return new HTTPResult(status, JSON.stringify({ field, message }), JSON_TYPE); +} + +function availableAt(store: Store | undefined, size: string): number { + if (!store || !isInRange(store, size)) return 0; + return STOCK[store.id]?.[size] ?? 0; +} + +function donorLabel(store: Store | undefined, fallback: string): string { + return store ? `${store.id} — ${store.name}` : fallback; +} + +/** + * The routes of the "Stock by size and store" demo: the two read-only grids + * (`?view=stock`, `?view=sales`) and the order form a cell opens, prefilled + * with the cell's store and size. + */ +export class MatrixStockController extends Controller(MATRIX_STOCK_API) { + @AuthUserWithPermission(PageMatrixStock) + declare user: User; + + @Get("rows") + list(@Parameter("view", "query") view?: string): MatrixData { + if (view === SALES_VIEW) { + return { + columns: [...sizeColumns(), ...SALES_ANNEX], + rows: STORES.map(salesRow), + }; + } + return { + columns: [...sizeColumns(), ...STOCK_ANNEX], + rows: storesByRegion().map(stockRow), + }; + } + + @Get("order") + orderForm( + @Parameter("store", "query") storeId = "", + @Parameter("size", "query") size = "", + ): OrderRequest { + const store = findStore(storeId); + return { + article: `${ARTICLE.label} — ${ARTICLE.code} (${ARTICLE.colour})`, + size: SIZES.includes(size) ? size : "", + donor: donorLabel(store, storeId), + available: availableAt(store, size), + customer: "", + phone: "", + email: "", + pickupStore: CURRENT_STORE, + note: "", + }; + } + + @Post("order") + order( + @JSONBody() body: OrderRequest, + @Parameter("store", "query") storeId = "", + @Parameter("size", "query") sizeQuery = "", + ) { + const store = findStore(storeId); + const size = sizeQuery || body.size || ""; + if (!body.customer?.trim()) { + throw refuse( + HTTP_BAD_REQUEST, + "customer", + "Indiquez le nom de la cliente.", + ); + } + if (!body.phone?.trim() && !body.email?.trim()) { + throw refuse( + HTTP_BAD_REQUEST, + "phone", + "Un téléphone ou un e-mail pour la prévenir.", + ); + } + if (availableAt(store, size) < 1) { + throw refuse( + HTTP_CONFLICT, + "size", + `Plus de paire en ${size || "cette pointure"} chez ${donorLabel(store, storeId || "ce magasin")}.`, + ); + } + const pickup = + findStore(body.pickupStore ?? CURRENT_STORE)?.name ?? CURRENT_STORE; + return { + message: `Demande envoyée à ${store?.id}: 1 paire en ${size} pour ${body.customer.trim()}, retrait à ${pickup}.`, + }; + } +} diff --git a/packages/dms/playground/src/matrix/stock/data.ts b/packages/dms/playground/src/matrix/stock/data.ts new file mode 100644 index 000000000..2780092c9 --- /dev/null +++ b/packages/dms/playground/src/matrix/stock/data.ts @@ -0,0 +1,130 @@ +/** + * The friend's shoe shops: one article, Tamaris Bottine Alma A260191, in + * sizes 36 to 42, across the warehouse, three stores and the e-shop. The + * Stock, Allocation and Correction demos share these axes. + */ + +export const ARTICLE = { + code: "A260191", + label: "Tamaris Bottine Alma", + colour: "Cognac", +} as const; + +export const SIZES = ["36", "37", "38", "39", "40", "41", "42"]; + +/** The store the signed-in seller works in, highlighted on every grid. */ +export const CURRENT_STORE = "LG4"; +/** The warehouse: every size, the reserve the stores order from. */ +export const WAREHOUSE = "ENT"; + +export interface Store { + id: string; + name: string; + /** The sizes the store ordered of this article; the others are out of range. */ + sizes: string[]; + /** Pairs to keep of each ordered size; under it, the cell turns red. */ + minimum: number; + /** Where the store is, the group the stock grid files it under. */ + region: string; +} + +export const REGIONS = { + belgium: "Belgique", + luxembourg: "Luxembourg", + logistics: "Entrepôt & web", +} as const; + +export const STORES: Store[] = [ + { + id: WAREHOUSE, + name: "Entrepôt — Herstal", + sizes: SIZES, + minimum: 2, + region: REGIONS.logistics, + }, + { + id: "NE1", + name: "Namur Esplanade", + sizes: ["37", "38", "39", "40", "41"], + minimum: 2, + region: REGIONS.belgium, + }, + { + id: CURRENT_STORE, + name: "Liège Médiacité", + sizes: ["36", "37", "38", "39", "40", "41"], + minimum: 2, + region: REGIONS.belgium, + }, + { + id: "LUX29", + name: "Luxembourg Cloche d'Or", + sizes: ["36", "37", "38", "39", "40"], + minimum: 2, + region: REGIONS.luxembourg, + }, + { + id: "WEB", + name: "E-shop (stock dédié)", + sizes: SIZES, + minimum: 1, + region: REGIONS.logistics, + }, +]; + +/** Quantities by store, then by size. */ +export type StoreQuantities = Record>; + +/** Pairs in stock today. */ +export const STOCK: StoreQuantities = { + ENT: { 36: 4, 37: 9, 38: 14, 39: 12, 40: 8, 41: 5, 42: 2 }, + NE1: { 37: 1, 38: 2, 39: 0, 40: 1, 41: 1 }, + LG4: { 36: 1, 37: 2, 38: 0, 39: 3, 40: 2, 41: 1 }, + LUX29: { 36: 0, 37: 1, 38: 2, 39: 2, 40: 1 }, + WEB: { 36: 2, 37: 3, 38: 5, 39: 4, 40: 3, 41: 2, 42: 1 }, +}; + +/** Pairs sold over the last 30 days. */ +export const SALES_30_DAYS: StoreQuantities = { + ENT: {}, + NE1: { 37: 2, 38: 3, 39: 4, 40: 2, 41: 0 }, + LG4: { 36: 1, 37: 3, 38: 5, 39: 4, 40: 2, 41: 1 }, + LUX29: { 36: 1, 37: 2, 38: 2, 39: 1, 40: 0 }, + WEB: { 36: 2, 37: 4, 38: 6, 39: 5, 40: 3, 41: 1, 42: 1 }, +}; + +/** The last delivery each store received of the article. */ +export interface Delivery { + number: string; + date: string; + /** A delivery on its way, not received yet. */ + inTransit?: boolean; +} + +export const LAST_DELIVERIES: Record = { + ENT: { number: "BL-26-04117", date: "2026-10-21" }, + NE1: { number: "BL-26-04122", date: "2026-10-14" }, + LG4: { number: "BL-26-04131", date: "2026-10-23", inTransit: true }, + LUX29: { number: "BL-26-04098", date: "2026-10-02" }, + WEB: { number: "BL-26-04120", date: "2026-10-16" }, +}; + +const REGION_ORDER: string[] = Object.values(REGIONS); + +/** The stores region by region, as a grid grouped on the region lists them. */ +export function storesByRegion(): Store[] { + return [...STORES].sort( + (left, right) => + REGION_ORDER.indexOf(left.region) - REGION_ORDER.indexOf(right.region), + ); +} + +/** Whether a store ordered a size: the others are hatched. */ +export function isInRange(store: Store, size: string): boolean { + return store.sizes.includes(size); +} + +/** A store by its code. */ +export function findStore(id: string): Store | undefined { + return STORES.find((store) => store.id === id); +} diff --git a/packages/dms/playground/src/matrix/stock/page.ts b/packages/dms/playground/src/matrix/stock/page.ts new file mode 100644 index 000000000..e8a45c0f6 --- /dev/null +++ b/packages/dms/playground/src/matrix/stock/page.ts @@ -0,0 +1,173 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { DefaultDataTypes } from "@antelopejs/interface-dms/base/data-types/default-types"; +import { Form } from "@antelopejs/interface-dms/base/form"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { + Matrix, + type MatrixLegendItem, +} from "@antelopejs/interface-dms/base/matrix"; +import { demoGuide } from "../../table-view/guide"; +import { MATRIX_API, matrixCategory } from "../category"; +import { ARTICLE, CURRENT_STORE, STORES, WAREHOUSE } from "./data"; + +export const MATRIX_STOCK_SLUG = "matrix-stock"; +export const MATRIX_STOCK_API = `${MATRIX_API}/stock`; + +const ORDER_URL = `${MATRIX_STOCK_API}/order?store={{row.id}}&size={{row.column}}`; +const ARTICLE_TITLE = `${ARTICLE.label} ${ARTICLE.code} — ${ARTICLE.colour}`; +const OUT_OF_RANGE = "Hors plage commandée"; + +const PICKUP_STORES = STORES.filter((store) => store.id !== WAREHOUSE).map( + (store) => ({ value: store.id, label: `${store.id} — ${store.name}` }), +); + +const STOCK_LEGEND: MatrixLegendItem[] = [ + { label: OUT_OF_RANGE, hatched: true }, + { label: "Sous le minimum", tone: "error" }, + { label: "Votre magasin", tone: "primary" }, +]; + +const SALES_LEGEND: MatrixLegendItem[] = [ + { label: OUT_OF_RANGE, hatched: true }, + { label: "4 paires ou plus", tone: "success" }, +]; + +// The drawer a cell opens: the form reads the cell's store and size from +// its URL ({{row.id}}, {{row.column}}), and posts the request to the same. +const orderForm = Form({ + kind: "action", + fetchUrl: ORDER_URL, + submitUrl: ORDER_URL, + submitUrlMethod: "POST", + submitLabel: "Envoyer la demande", + successMessage: "Demande envoyée au magasin donneur", + fields: [ + { + id: "article", + label: "Article", + type: new DefaultDataTypes.StringType(), + readonly: true, + }, + { + id: "size", + label: "Pointure", + type: new DefaultDataTypes.StringType(), + readonly: true, + }, + { + id: "donor", + label: "Magasin donneur", + type: new DefaultDataTypes.StringType(), + readonly: true, + }, + { + id: "available", + label: "Paires disponibles chez le donneur", + type: new DefaultDataTypes.NumberType(), + readonly: true, + }, + { + id: "customer", + label: "Nom de la cliente", + type: new DefaultDataTypes.StringType({ placeholder: "Mme Dupont" }), + required: true, + }, + { + id: "phone", + label: "Téléphone", + description: "Ou un e-mail : il faut l'un des deux pour la prévenir.", + type: new DefaultDataTypes.PhoneType(), + }, + { + id: "email", + label: "E-mail", + type: new DefaultDataTypes.EmailType(), + }, + { + id: "pickupStore", + label: "Retrait en magasin", + type: new DefaultDataTypes.SelectType({ items: PICKUP_STORES }), + }, + { + id: "note", + label: "Note pour le magasin donneur", + type: new DefaultDataTypes.StringType({ textarea: true, rows: 3 }), + }, + ], +}); + +@RegisterPage() +export class PageMatrixStock extends PageController( + MATRIX_STOCK_SLUG, + { + displayName: "Stock by size and store (read-only)", + icon: "i-ph-sneaker", + category: matrixCategory, + order: 30, + description: + "One article's stock as a grid of stores by sizes, with totals both ways, a cross highlight, hatched sizes the store did not order, alert cells and annex columns; a click on a cell opens an order form for a customer. Under it, the sales of the last 30 days on the same axes.", + }, + DefaultLayout({ fullWidth: true }), +) { + static guide = demoGuide([ + { + label: "Hover a cell", + text: "crossHighlight lights its store and its size; the Total column and the Total row add the sizes (totals), the annex columns are left out (excludeFromTotals on Min.).", + }, + { + label: "Fold a region", + text: 'grouping: { groupByField: "region", collapsible, count, subtotals }: the stores grouped by region (a hidden column, listed sorted by the route), each header counting its stores and carrying its own size sums next to the grand totals.', + }, + { + label: "Read the hatched and red cells", + text: `disabled cells are sizes the store did not order (hatched, "${OUT_OF_RANGE}"); a cell under the store's minimum carries the error tone. The legend explains both.`, + }, + { + label: `Find ${CURRENT_STORE}`, + text: "The current store's row carries a tone (row tone), its description says so.", + }, + { + label: "Click a cell with stock", + text: 'cellAction: a drawer with a Form "Commander pour une cliente", prefilled from {{row.id}} (the store) and {{row.column}} (the size). Send it without a name: the route refuses the field; on an empty cell it answers that no pair is left.', + }, + { + label: "Compare with the sales", + text: "A second Matrix on the same page, same axes, read from the same route (?view=sales): best sellers in success, the warehouse row read-only (it does not sell).", + }, + ]); + + static stock = Matrix({ + title: `Stock — ${ARTICLE_TITLE}`, + description: "Paires en stock aujourd'hui, par magasin et par pointure.", + fetchUrl: `${MATRIX_STOCK_API}/rows?view=stock`, + rowHeader: { label: "Magasin", width: 220 }, + totals: { rows: true, columns: true, label: "Total" }, + grouping: { + groupByField: "region", + collapsible: true, + count: true, + subtotals: true, + }, + crossHighlight: true, + legend: STOCK_LEGEND, + cellAction: { + type: "drawer", + direction: "right", + size: "md", + title: "Commander pour une cliente", + description: + "La paire est réservée chez le magasin donneur et envoyée au magasin de retrait.", + component: orderForm, + }, + }); + + static sales = Matrix({ + title: `Ventes 30 jours — ${ARTICLE_TITLE}`, + description: "Paires vendues du 25 septembre au 24 octobre.", + fetchUrl: `${MATRIX_STOCK_API}/rows?view=sales`, + rowHeader: { label: "Magasin", width: 220 }, + totals: { rows: true, columns: true, label: "Total" }, + crossHighlight: true, + legend: SALES_LEGEND, + }); +} diff --git a/packages/dms/playground/src/matrix/translations/api.ts b/packages/dms/playground/src/matrix/translations/api.ts new file mode 100644 index 000000000..faa07e897 --- /dev/null +++ b/packages/dms/playground/src/matrix/translations/api.ts @@ -0,0 +1,325 @@ +import { + Context, + Controller, + Get, + JSONBody, + Post, + type RequestContext, +} from "@antelopejs/interface-api"; +import type { User } from "@antelopejs/interface-dms/auth/db"; +import type { + MatrixCellError, + MatrixCellState, + MatrixChange, + MatrixColumn, + MatrixConflict, + MatrixData, + MatrixGroup, + MatrixRow, + MatrixSaveRequest, + MatrixSaveResponse, +} from "@antelopejs/interface-dms/base/matrix"; +import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards"; +import { + facetAllows, + facetItems, + type MatrixQuery, + matchesSearch, + pageOf, + readMatrixQuery, +} from "../query"; +import { cellError, readSaveRequest, rowError, sameCellValue } from "../save"; +import { + BASE_LANGUAGE, + CONTESTED_KEY, + CONTESTED_LANGUAGE, + CONTESTED_WORDINGS, + LANGUAGE_INFO, + LANGUAGES, + type Language, + NAMESPACES, + TRANSLATION_KEYS, + type TranslationKey, +} from "./data"; +import { MATRIX_TRANSLATIONS_API, PageMatrixTranslations } from "./page"; + +const PLACEHOLDERS = /\{(\w+)\}/g; +const MAX_TEXT_LENGTH = 500; +const WELL_COVERED = 0.9; +const PERCENT = 100; +const ALL_STATUS = "all"; + +/** Which keys a status segment keeps, given the languages shown. */ +type StatusTest = (entry: TranslationKey, languages: Language[]) => boolean; + +/** The outcome of one change: written, refused, or made on a moved value. */ +interface ChangeOutcome { + error?: MatrixCellError; + conflict?: MatrixConflict; +} + +let contestedWording = 0; + +function placeholdersOf(text: string): Set { + return new Set(Array.from(text.matchAll(PLACEHOLDERS), (match) => match[1]!)); +} + +/** The placeholder mistakes of a translation against its base text. */ +function issuesOf(entry: TranslationKey, language: Language): string[] { + const base = entry.texts[BASE_LANGUAGE]; + const text = entry.texts[language]; + if (language === BASE_LANGUAGE || !base || !text) return []; + const expected = placeholdersOf(base); + const found = placeholdersOf(text); + const missing = [...expected].filter((name) => !found.has(name)); + const unknown = [...found].filter((name) => !expected.has(name)); + return [ + ...missing.map((name) => `Placeholder {${name}} is missing`), + ...unknown.map( + (name) => + `Unknown placeholder {${name}}: the base text has no such value`, + ), + ]; +} + +const isMissing = (entry: TranslationKey, language: Language) => + !entry.texts[language]; + +const hasIssues: StatusTest = (entry, languages) => + languages.some((language) => issuesOf(entry, language).length > 0); + +const hasMissing: StatusTest = (entry, languages) => + languages.some((language) => isMissing(entry, language)); + +const STATUS_TESTS: Record = { + all: () => true, + missing: hasMissing, + complete: (entry, languages) => + !hasMissing(entry, languages) && !hasIssues(entry, languages), + issues: hasIssues, +}; + +function isLanguage(id: string): id is Language { + return LANGUAGES.some((language) => language === id); +} + +/** The base language, then the ones the language facet keeps. */ +function shownLanguages(query: MatrixQuery): Language[] { + return LANGUAGES.filter( + (language) => + language === BASE_LANGUAGE || facetAllows(query, "language", language), + ); +} + +function missingCount(language: Language): number { + return TRANSLATION_KEYS.filter((entry) => isMissing(entry, language)).length; +} + +function coverage(language: Language): number { + return 1 - missingCount(language) / TRANSLATION_KEYS.length; +} + +function languageColumn(language: Language): MatrixColumn { + const { label, locale } = LANGUAGE_INFO[language]; + const column: MatrixColumn = { + id: language, + label, + description: locale, + kind: "longText", + width: 300, + }; + if (language === BASE_LANGUAGE) { + return { ...column, badge: "Base", badgeTone: "primary", required: true }; + } + const missing = missingCount(language); + const covered = coverage(language); + return { + ...column, + badge: missing ? `${missing} missing` : "Complete", + badgeTone: missing ? "warning" : "success", + progress: covered, + progressTone: covered >= WELL_COVERED ? "success" : "warning", + }; +} + +function namespaceGroup(namespace: (typeof NAMESPACES)[number]): MatrixGroup { + const missing = TRANSLATION_KEYS.filter( + (entry) => + entry.namespace === namespace.id && hasMissing(entry, [...LANGUAGES]), + ).length; + return { + id: namespace.id, + label: namespace.label, + description: namespace.description, + badge: missing ? `${missing} incomplete` : "Complete", + badgeTone: missing ? "warning" : "success", + }; +} + +function cellState( + entry: TranslationKey, + language: Language, +): MatrixCellState | undefined { + const base = entry.texts[BASE_LANGUAGE]; + if (isMissing(entry, language)) + return base ? { placeholder: base } : undefined; + const issues = issuesOf(entry, language); + return issues.length ? { issues, tone: "warning" } : undefined; +} + +function toRow(entry: TranslationKey, languages: Language[]): MatrixRow { + const values: Record = {}; + const cells: Record = {}; + for (const language of languages) { + values[language] = entry.texts[language] ?? null; + const state = cellState(entry, language); + if (state) cells[language] = state; + } + return { + id: entry.key, + label: entry.key.slice(entry.namespace.length + 1), + group: entry.namespace, + values, + cells, + }; +} + +function percentOf(language: Language): string { + return `${LANGUAGE_INFO[language].label} ${Math.floor(coverage(language) * PERCENT)} %`; +} + +function footerLine(): string { + const translated = LANGUAGES.filter((language) => language !== BASE_LANGUAGE); + const missing = translated.reduce( + (sum, language) => sum + missingCount(language), + 0, + ); + const withIssues = TRANSLATION_KEYS.filter((entry) => + hasIssues(entry, translated), + ).length; + return `Coverage: ${translated.map(percentOf).join(" · ")}. ${missing} translations missing, ${withIssues} keys with a placeholder issue.`; +} + +function searchKeys(query: MatrixQuery): TranslationKey[] { + return TRANSLATION_KEYS.filter( + (entry) => + facetAllows(query, "namespace", entry.namespace) && + matchesSearch(query.search, [entry.key, ...Object.values(entry.texts)]), + ); +} + +function statusCounts( + entries: TranslationKey[], + languages: Language[], +): Record { + const counts: Record = {}; + for (const [status, test] of Object.entries(STATUS_TESTS)) { + counts[status] = entries.filter((entry) => test(entry, languages)).length; + } + return counts; +} + +/** A colleague rewords the contested key right after each read. */ +function rewordContestedKey(): void { + const entry = TRANSLATION_KEYS.find( + (candidate) => candidate.key === CONTESTED_KEY, + ); + if (!entry) return; + contestedWording = (contestedWording + 1) % CONTESTED_WORDINGS.length; + entry.texts[CONTESTED_LANGUAGE] = CONTESTED_WORDINGS[contestedWording]; +} + +function checkValue(change: MatrixChange): string | undefined { + const { value } = change; + if (value !== null && typeof value !== "string") + return "A translation is text."; + if (typeof value === "string" && value.length > MAX_TEXT_LENGTH) { + return `A translation holds ${MAX_TEXT_LENGTH} characters at most.`; + } + if (change.columnId === BASE_LANGUAGE && !value?.trim()) { + return "The base text cannot be empty: every language translates it."; + } + return undefined; +} + +function applyChange(change: MatrixChange, force: boolean): ChangeOutcome { + const entry = TRANSLATION_KEYS.find( + (candidate) => candidate.key === change.rowId, + ); + if (!entry) return { error: rowError(change.rowId, "This key was deleted.") }; + const language = change.columnId; + if (!isLanguage(language)) { + return { + error: cellError( + change, + `${language} is not a language of this workspace.`, + ), + }; + } + const problem = checkValue(change); + if (problem) return { error: cellError(change, problem) }; + const current = entry.texts[language] ?? null; + if (!force && !sameCellValue(change.previous, current)) { + return { conflict: { rowId: change.rowId, columnId: language, current } }; + } + const text = typeof change.value === "string" ? change.value : ""; + if (text) entry.texts[language] = text; + else delete entry.texts[language]; + return {}; +} + +/** + * The routes of the "Translations" demo: the keys of a workspace by + * language. The languages are columns the route answers, with their + * coverage; the status segments, the namespace and language facets and the + * search are applied here, and the save detects conflicts on `previous`. + */ +export class MatrixTranslationsController extends Controller( + MATRIX_TRANSLATIONS_API, +) { + @AuthUserWithPermission(PageMatrixTranslations) + declare user: User; + + @Get("rows") + list(@Context() ctx: RequestContext): MatrixData { + const query = readMatrixQuery(ctx.url.searchParams); + const languages = shownLanguages(query); + const searched = searchKeys(query); + const test = + STATUS_TESTS[query.status ?? ALL_STATUS] ?? STATUS_TESTS[ALL_STATUS]!; + const matching = searched.filter((entry) => test(entry, languages)); + const data: MatrixData = { + rows: pageOf(matching, query).map((entry) => toRow(entry, languages)), + columns: languages.map(languageColumn), + total: matching.length, + groups: NAMESPACES.map(namespaceGroup), + counts: statusCounts(searched, languages), + facets: { + namespace: facetItems( + TRANSLATION_KEYS, + (entry) => entry.namespace, + Object.fromEntries(NAMESPACES.map(({ id, label }) => [id, label])), + ), + }, + footer: footerLine(), + }; + rewordContestedKey(); + return data; + } + + @Post("save") + save(@JSONBody() body: MatrixSaveRequest): MatrixSaveResponse { + const { changes, force = false } = readSaveRequest(body); + const outcomes = changes.map((change) => applyChange(change, force)); + const rowIds = new Set(changes.map((change) => change.rowId)); + return { + rows: TRANSLATION_KEYS.filter((entry) => rowIds.has(entry.key)).map( + (entry) => toRow(entry, [...LANGUAGES]), + ), + errors: outcomes.flatMap(({ error }) => (error ? [error] : [])), + conflicts: outcomes.flatMap(({ conflict }) => + conflict ? [conflict] : [], + ), + }; + } +} diff --git a/packages/dms/playground/src/matrix/translations/data.ts b/packages/dms/playground/src/matrix/translations/data.ts new file mode 100644 index 000000000..631ecdca0 --- /dev/null +++ b/packages/dms/playground/src/matrix/translations/data.ts @@ -0,0 +1,665 @@ +import { percentileOf } from "../query"; + +/** The languages of the workspace, the base one first. */ +export const LANGUAGES = ["en", "fr", "nl", "de"] as const; +export type Language = (typeof LANGUAGES)[number]; +export const BASE_LANGUAGE: Language = "en"; + +export interface LanguageInfo { + label: string; + locale: string; +} + +export const LANGUAGE_INFO: Record = { + en: { label: "English", locale: "en-GB" }, + fr: { label: "French", locale: "fr-BE" }, + nl: { label: "Dutch", locale: "nl-BE" }, + de: { label: "German", locale: "de-DE" }, +}; + +/** The texts of one key, by language; a language left out is missing. */ +export type KeyTexts = Partial>; + +export interface TranslationKey { + key: string; + namespace: string; + texts: KeyTexts; +} + +export interface NamespaceInfo { + id: string; + label: string; + description: string; +} + +interface FrenchNoun { + /** The bare noun, after "Aucun" / "Aucune". */ + noun: string; + plural: string; + /** With its definite article, elided where French elides it. */ + definite: string; + indefinite: string; + feminine?: boolean; +} + +interface Entity { + id: string; + en: [string, string]; + fr: FrenchNoun; + nl: [string, string]; + de: [string, string]; +} + +type Template = (entity: Entity) => Record; + +const capitalize = (text: string) => + text.charAt(0).toUpperCase() + text.slice(1); +const feminine = (entity: Entity, suffix: string) => + entity.fr.feminine ? suffix : ""; + +// The messages every entity of the back-office has, in the four languages. +const TEMPLATES: Record = { + title: (entity) => ({ + en: capitalize(entity.en[1]), + fr: capitalize(entity.fr.plural), + nl: capitalize(entity.nl[1]), + de: entity.de[1], + }), + empty: (entity) => ({ + en: `No ${entity.en[1]} yet`, + fr: `Aucun${feminine(entity, "e")} ${entity.fr.noun} pour l'instant`, + nl: `Nog geen ${entity.nl[1]}`, + de: `Noch keine ${entity.de[1]}`, + }), + count: (entity) => ({ + en: `{count} ${entity.en[1]}`, + fr: `{count} ${entity.fr.plural}`, + nl: `{count} ${entity.nl[1]}`, + de: `{count} ${entity.de[1]}`, + }), + create: (entity) => ({ + en: `New ${entity.en[0]}`, + fr: `Ajouter ${entity.fr.indefinite}`, + nl: `${capitalize(entity.nl[0])} toevoegen`, + de: `${entity.de[0]} anlegen`, + }), + edit: (entity) => ({ + en: `Edit ${entity.en[0]}`, + fr: `Modifier ${entity.fr.definite}`, + nl: `${capitalize(entity.nl[0])} bewerken`, + de: `${entity.de[0]} bearbeiten`, + }), + delete: (entity) => ({ + en: `Delete ${entity.en[0]}`, + fr: `Supprimer ${entity.fr.definite}`, + nl: `${capitalize(entity.nl[0])} verwijderen`, + de: `${entity.de[0]} löschen`, + }), + deleteConfirm: () => ({ + en: "Delete {name}? This cannot be undone.", + fr: "Supprimer {name} ? Cette action est définitive.", + nl: "{name} verwijderen? Dit kan niet ongedaan worden gemaakt.", + de: "{name} löschen? Dies kann nicht rückgängig gemacht werden.", + }), + saved: (entity) => ({ + en: `${capitalize(entity.en[0])} saved`, + fr: `${capitalize(entity.fr.definite)} a été enregistré${feminine(entity, "e")}`, + nl: `${capitalize(entity.nl[0])} opgeslagen`, + de: `${entity.de[0]} gespeichert`, + }), + search: (entity) => ({ + en: `Search ${entity.en[1]}…`, + fr: `Rechercher des ${entity.fr.plural}…`, + nl: `${capitalize(entity.nl[1])} zoeken…`, + de: `${entity.de[1]} suchen…`, + }), + notFound: (entity) => ({ + en: `This ${entity.en[0]} no longer exists.`, + fr: `${capitalize(entity.fr.definite)} n'existe plus.`, + nl: `${capitalize(entity.nl[0])} bestaat niet meer.`, + de: `${entity.de[0]} wurde nicht gefunden.`, + }), +}; + +const fr = ( + noun: string, + plural: string, + definite: string, + indefinite: string, + isFeminine = false, +): FrenchNoun => ({ noun, plural, definite, indefinite, feminine: isFeminine }); + +const ENTITIES: Record = { + catalog: [ + { + id: "product", + en: ["product", "products"], + fr: fr("produit", "produits", "le produit", "un produit"), + nl: ["product", "producten"], + de: ["Produkt", "Produkte"], + }, + { + id: "category", + en: ["category", "categories"], + fr: fr("catégorie", "catégories", "la catégorie", "une catégorie", true), + nl: ["categorie", "categorieën"], + de: ["Kategorie", "Kategorien"], + }, + { + id: "brand", + en: ["brand", "brands"], + fr: fr("marque", "marques", "la marque", "une marque", true), + nl: ["merk", "merken"], + de: ["Marke", "Marken"], + }, + { + id: "collection", + en: ["collection", "collections"], + fr: fr( + "collection", + "collections", + "la collection", + "une collection", + true, + ), + nl: ["collectie", "collecties"], + de: ["Kollektion", "Kollektionen"], + }, + { + id: "sizeChart", + en: ["size chart", "size charts"], + fr: fr( + "grille de tailles", + "grilles de tailles", + "la grille de tailles", + "une grille de tailles", + true, + ), + nl: ["maattabel", "maattabellen"], + de: ["Größentabelle", "Größentabellen"], + }, + { + id: "colour", + en: ["colour", "colours"], + fr: fr("couleur", "couleurs", "la couleur", "une couleur", true), + nl: ["kleur", "kleuren"], + de: ["Farbe", "Farben"], + }, + { + id: "supplier", + en: ["supplier", "suppliers"], + fr: fr("fournisseur", "fournisseurs", "le fournisseur", "un fournisseur"), + nl: ["leverancier", "leveranciers"], + de: ["Lieferant", "Lieferanten"], + }, + { + id: "priceList", + en: ["price list", "price lists"], + fr: fr( + "liste de prix", + "listes de prix", + "la liste de prix", + "une liste de prix", + true, + ), + nl: ["prijslijst", "prijslijsten"], + de: ["Preisliste", "Preislisten"], + }, + ], + checkout: [ + { + id: "order", + en: ["order", "orders"], + fr: fr("commande", "commandes", "la commande", "une commande", true), + nl: ["bestelling", "bestellingen"], + de: ["Bestellung", "Bestellungen"], + }, + { + id: "cart", + en: ["cart", "carts"], + fr: fr("panier", "paniers", "le panier", "un panier"), + nl: ["winkelwagen", "winkelwagens"], + de: ["Warenkorb", "Warenkörbe"], + }, + { + id: "payment", + en: ["payment", "payments"], + fr: fr("paiement", "paiements", "le paiement", "un paiement"), + nl: ["betaling", "betalingen"], + de: ["Zahlung", "Zahlungen"], + }, + { + id: "shippingMethod", + en: ["shipping method", "shipping methods"], + fr: fr( + "mode de livraison", + "modes de livraison", + "le mode de livraison", + "un mode de livraison", + ), + nl: ["verzendmethode", "verzendmethodes"], + de: ["Versandart", "Versandarten"], + }, + { + id: "coupon", + en: ["coupon", "coupons"], + fr: fr("code promo", "codes promo", "le code promo", "un code promo"), + nl: ["kortingscode", "kortingscodes"], + de: ["Gutschein", "Gutscheine"], + }, + { + id: "invoice", + en: ["invoice", "invoices"], + fr: fr("facture", "factures", "la facture", "une facture", true), + nl: ["factuur", "facturen"], + de: ["Rechnung", "Rechnungen"], + }, + { + id: "refund", + en: ["refund", "refunds"], + fr: fr( + "remboursement", + "remboursements", + "le remboursement", + "un remboursement", + ), + nl: ["terugbetaling", "terugbetalingen"], + de: ["Erstattung", "Erstattungen"], + }, + { + id: "address", + en: ["address", "addresses"], + fr: fr("adresse", "adresses", "l'adresse", "une adresse", true), + nl: ["adres", "adressen"], + de: ["Adresse", "Adressen"], + }, + ], + inventory: [ + { + id: "store", + en: ["store", "stores"], + fr: fr("magasin", "magasins", "le magasin", "un magasin"), + nl: ["winkel", "winkels"], + de: ["Filiale", "Filialen"], + }, + { + id: "warehouse", + en: ["warehouse", "warehouses"], + fr: fr("entrepôt", "entrepôts", "l'entrepôt", "un entrepôt"), + nl: ["magazijn", "magazijnen"], + de: ["Lager", "Lager"], + }, + { + id: "transfer", + en: ["transfer", "transfers"], + fr: fr("transfert", "transferts", "le transfert", "un transfert"), + nl: ["overboeking", "overboekingen"], + de: ["Umlagerung", "Umlagerungen"], + }, + { + id: "stockCount", + en: ["stock count", "stock counts"], + fr: fr("inventaire", "inventaires", "l'inventaire", "un inventaire"), + nl: ["telling", "tellingen"], + de: ["Inventur", "Inventuren"], + }, + { + id: "reception", + en: ["reception", "receptions"], + fr: fr("réception", "réceptions", "la réception", "une réception", true), + nl: ["ontvangst", "ontvangsten"], + de: ["Wareneingang", "Wareneingänge"], + }, + { + id: "adjustment", + en: ["adjustment", "adjustments"], + fr: fr("ajustement", "ajustements", "l'ajustement", "un ajustement"), + nl: ["correctie", "correcties"], + de: ["Korrektur", "Korrekturen"], + }, + { + id: "location", + en: ["location", "locations"], + fr: fr("emplacement", "emplacements", "l'emplacement", "un emplacement"), + nl: ["locatie", "locaties"], + de: ["Lagerplatz", "Lagerplätze"], + }, + { + id: "batch", + en: ["batch", "batches"], + fr: fr("lot", "lots", "le lot", "un lot"), + nl: ["partij", "partijen"], + de: ["Charge", "Chargen"], + }, + ], + account: [ + { + id: "user", + en: ["user", "users"], + fr: fr("utilisateur", "utilisateurs", "l'utilisateur", "un utilisateur"), + nl: ["gebruiker", "gebruikers"], + de: ["Benutzer", "Benutzer"], + }, + { + id: "team", + en: ["team", "teams"], + fr: fr("équipe", "équipes", "l'équipe", "une équipe", true), + nl: ["team", "teams"], + de: ["Team", "Teams"], + }, + { + id: "role", + en: ["role", "roles"], + fr: fr("rôle", "rôles", "le rôle", "un rôle"), + nl: ["rol", "rollen"], + de: ["Rolle", "Rollen"], + }, + { + id: "apiKey", + en: ["API key", "API keys"], + fr: fr("clé d'API", "clés d'API", "la clé d'API", "une clé d'API", true), + nl: ["API-sleutel", "API-sleutels"], + de: ["API-Schlüssel", "API-Schlüssel"], + }, + { + id: "session", + en: ["session", "sessions"], + fr: fr("session", "sessions", "la session", "une session", true), + nl: ["sessie", "sessies"], + de: ["Sitzung", "Sitzungen"], + }, + { + id: "notification", + en: ["notification", "notifications"], + fr: fr( + "notification", + "notifications", + "la notification", + "une notification", + true, + ), + nl: ["melding", "meldingen"], + de: ["Benachrichtigung", "Benachrichtigungen"], + }, + { + id: "subscription", + en: ["subscription", "subscriptions"], + fr: fr("abonnement", "abonnements", "l'abonnement", "un abonnement"), + nl: ["abonnement", "abonnementen"], + de: ["Abonnement", "Abonnements"], + }, + { + id: "device", + en: ["device", "devices"], + fr: fr("appareil", "appareils", "l'appareil", "un appareil"), + nl: ["apparaat", "apparaten"], + de: ["Gerät", "Geräte"], + }, + ], + emails: [ + { + id: "template", + en: ["template", "templates"], + fr: fr("modèle", "modèles", "le modèle", "un modèle"), + nl: ["sjabloon", "sjablonen"], + de: ["Vorlage", "Vorlagen"], + }, + { + id: "campaign", + en: ["campaign", "campaigns"], + fr: fr("campagne", "campagnes", "la campagne", "une campagne", true), + nl: ["campagne", "campagnes"], + de: ["Kampagne", "Kampagnen"], + }, + { + id: "contact", + en: ["contact", "contacts"], + fr: fr("contact", "contacts", "le contact", "un contact"), + nl: ["contactpersoon", "contactpersonen"], + de: ["Kontakt", "Kontakte"], + }, + { + id: "segment", + en: ["segment", "segments"], + fr: fr("segment", "segments", "le segment", "un segment"), + nl: ["segment", "segmenten"], + de: ["Segment", "Segmente"], + }, + { + id: "mailingList", + en: ["mailing list", "mailing lists"], + fr: fr( + "liste de diffusion", + "listes de diffusion", + "la liste de diffusion", + "une liste de diffusion", + true, + ), + nl: ["mailinglijst", "mailinglijsten"], + de: ["Verteiler", "Verteiler"], + }, + { + id: "sender", + en: ["sender", "senders"], + fr: fr("expéditeur", "expéditeurs", "l'expéditeur", "un expéditeur"), + nl: ["afzender", "afzenders"], + de: ["Absender", "Absender"], + }, + { + id: "attachment", + en: ["attachment", "attachments"], + fr: fr( + "pièce jointe", + "pièces jointes", + "la pièce jointe", + "une pièce jointe", + true, + ), + nl: ["bijlage", "bijlagen"], + de: ["Anhang", "Anhänge"], + }, + { + id: "domain", + en: ["sending domain", "sending domains"], + fr: fr( + "domaine d'envoi", + "domaines d'envoi", + "le domaine d'envoi", + "un domaine d'envoi", + ), + nl: ["verzenddomein", "verzenddomeinen"], + de: ["Versanddomain", "Versanddomains"], + }, + ], +}; + +// The shared messages, written by hand. +const COMMON_KEYS: Record> = { + save: { en: "Save", fr: "Enregistrer", nl: "Opslaan", de: "Speichern" }, + cancel: { en: "Cancel", fr: "Annuler", nl: "Annuleren", de: "Abbrechen" }, + close: { en: "Close", fr: "Fermer", nl: "Sluiten", de: "Schließen" }, + retry: { + en: "Retry", + fr: "Réessayer", + nl: "Opnieuw proberen", + de: "Erneut versuchen", + }, + loading: { + en: "Loading…", + fr: "Chargement…", + nl: "Laden…", + de: "Wird geladen…", + }, + signOut: { + en: "Sign out", + fr: "Se déconnecter", + nl: "Afmelden", + de: "Abmelden", + }, + help: { en: "Help", fr: "Aide", nl: "Help", de: "Hilfe" }, + welcome: { + en: "Welcome back, {name}!", + fr: "Bon retour, {name} !", + nl: "Welkom terug, {name}!", + de: "Willkommen zurück, {name}!", + }, + lastSaved: { + en: "Saved {time} ago", + fr: "Enregistré il y a {time}", + nl: "{time} geleden opgeslagen", + de: "Vor {time} gespeichert", + }, + unsaved: { + en: "{count} unsaved changes", + fr: "{count} modifications non enregistrées", + nl: "{count} niet-opgeslagen wijzigingen", + de: "{count} ungespeicherte Änderungen", + }, + noResults: { + en: "No results for “{query}”", + fr: "Aucun résultat pour « {query} »", + nl: "Geen resultaten voor ‘{query}’", + de: "Keine Ergebnisse für „{query}“", + }, + confirmLeave: { + en: "Leave this page? Your changes will be lost.", + fr: "Quitter cette page ? Vos modifications seront perdues.", + nl: "Deze pagina verlaten? Je wijzigingen gaan verloren.", + de: "Diese Seite verlassen? Ihre Änderungen gehen verloren.", + }, + offline: { + en: "You are offline. Your changes are kept on this device and sent as soon as the connection is back.", + fr: "Vous êtes hors ligne. Vos modifications sont conservées sur cet appareil et envoyées dès le retour de la connexion.", + nl: "Je bent offline. Je wijzigingen blijven op dit apparaat bewaard en worden verzonden zodra de verbinding terug is.", + de: "Sie sind offline. Ihre Änderungen bleiben auf diesem Gerät gespeichert und werden gesendet, sobald die Verbindung wieder steht.", + }, + legal: { + en: "By continuing, you accept the terms of service.\nYour data is processed in the European Union and never sold.", + fr: "En continuant, vous acceptez les conditions d'utilisation.\nVos données sont traitées dans l'Union européenne et ne sont jamais vendues.", + nl: "Door verder te gaan, aanvaard je de gebruiksvoorwaarden.\nJe gegevens worden in de Europese Unie verwerkt en nooit verkocht.", + de: "Mit dem Fortfahren akzeptieren Sie die Nutzungsbedingungen.\nIhre Daten werden in der Europäischen Union verarbeitet und nie verkauft.", + }, + copyright: { + en: "© {year} Altab. All rights reserved.", + fr: "© {year} Altab. Tous droits réservés.", + nl: "© {year} Altab. Alle rechten voorbehouden.", + de: "© {year} Altab. Alle Rechte vorbehalten.", + }, + pagination: { + en: "Page {page} of {pages}", + fr: "Page {page} sur {pages}", + nl: "Pagina {page} van {pages}", + de: "Seite {page} von {pages}", + }, +}; + +export const NAMESPACES: NamespaceInfo[] = [ + { + id: "common", + label: "Common", + description: "Buttons and messages shared by every screen", + }, + { + id: "catalog", + label: "Catalog", + description: "Products, brands and collections", + }, + { + id: "checkout", + label: "Checkout", + description: "Cart, payment and invoices", + }, + { + id: "inventory", + label: "Inventory", + description: "Stores, warehouses and stock moves", + }, + { id: "account", label: "Account", description: "Users, teams and access" }, + { + id: "emails", + label: "Emails", + description: "Campaigns and transactional emails", + }, +]; + +// The share of keys left untranslated in each language (out of 100), and of +// translations whose placeholder a translator mistyped. +const MISSING_PERCENT: Record = { + en: 0, + fr: 4, + nl: 11, + de: 23, +}; +const WRONG_PLACEHOLDER_PERCENT = 18; +const PLACEHOLDER = /\{(\w+)\}/; + +// What a translator types when they translate a placeholder's name too. +const TRANSLATED_PLACEHOLDERS: Record = { + count: { fr: "nombre", nl: "aantal", de: "Anzahl" }, + name: { fr: "nom", nl: "naam", de: "Name" }, + query: { fr: "recherche", nl: "zoekterm", de: "Suche" }, + time: { fr: "durée", nl: "tijd", de: "Zeit" }, + year: { fr: "année", nl: "jaar", de: "Jahr" }, + page: { fr: "page", nl: "pagina", de: "Seite" }, +}; + +function withGaps(key: string, texts: Record): KeyTexts { + const kept: KeyTexts = {}; + for (const language of LANGUAGES) { + if (percentileOf(`${key}:${language}`) < MISSING_PERCENT[language]) + continue; + kept[language] = withMistake(key, language, texts[language]); + } + return kept; +} + +function withMistake(key: string, language: Language, text: string): string { + const isBase = language === BASE_LANGUAGE; + if (isBase || !PLACEHOLDER.test(text)) return text; + if ( + percentileOf(`${key}:${language}:placeholder`) >= WRONG_PLACEHOLDER_PERCENT + ) + return text; + return text.replace(PLACEHOLDER, (placeholder, name: string) => { + const translated = TRANSLATED_PLACEHOLDERS[name]?.[language]; + return translated ? `{${translated}}` : placeholder; + }); +} + +function entityKeys(namespace: string, entities: Entity[]): TranslationKey[] { + return entities.flatMap((entity) => + Object.entries(TEMPLATES).map(([templateId, template]) => { + const key = `${namespace}.${entity.id}.${templateId}`; + return { key, namespace, texts: withGaps(key, template(entity)) }; + }), + ); +} + +function commonKeys(): TranslationKey[] { + return Object.entries(COMMON_KEYS).map(([id, texts]) => { + const key = `common.${id}`; + return { key, namespace: "common", texts: withGaps(key, texts) }; + }); +} + +/** The workspace's keys, kept in memory: a restart puts them back. */ +export const TRANSLATION_KEYS: TranslationKey[] = [ + ...commonKeys(), + ...Object.entries(ENTITIES).flatMap(([namespace, entities]) => + entityKeys(namespace, entities), + ), +]; + +/** + * The key a "colleague" keeps rewording in French: the route changes it just + * after answering each read, so an edit of it always started from a value + * that moved, and the save answers a conflict. + */ +export const CONTESTED_KEY = "common.welcome"; +export const CONTESTED_LANGUAGE: Language = "fr"; +export const CONTESTED_WORDINGS = [ + "Bon retour, {name} !", + "Ravi de vous revoir, {name} !", + "Bienvenue à nouveau, {name} !", + "Content de vous revoir, {name} !", +]; diff --git a/packages/dms/playground/src/matrix/translations/page.ts b/packages/dms/playground/src/matrix/translations/page.ts new file mode 100644 index 000000000..02ba7bd96 --- /dev/null +++ b/packages/dms/playground/src/matrix/translations/page.ts @@ -0,0 +1,115 @@ +import { PageController, RegisterPage } from "@antelopejs/interface-dms/page"; +import { DefaultLayout } from "@antelopejs/interface-dms/base/layouts"; +import { Matrix } from "@antelopejs/interface-dms/base/matrix"; +import { demoGuide } from "../../table-view/guide"; +import { MATRIX_API, matrixCategory } from "../category"; +import { + BASE_LANGUAGE, + CONTESTED_KEY, + LANGUAGE_INFO, + LANGUAGES, + TRANSLATION_KEYS, +} from "./data"; + +export const MATRIX_TRANSLATIONS_SLUG = "matrix-translations"; +export const MATRIX_TRANSLATIONS_API = `${MATRIX_API}/translations`; + +const PAGE_SIZE = 100; +const COLLAPSE_ABOVE = 300; + +@RegisterPage() +export class PageMatrixTranslations extends PageController( + MATRIX_TRANSLATIONS_SLUG, + { + displayName: "Translations (dynamic columns)", + icon: "i-ph-translate", + category: matrixCategory, + order: 20, + description: + "A translation workspace: keys by namespace as rows, the languages as columns the route answers with their coverage. Click a cell to edit it, Enter saves and moves down, each cell saved on its own with conflict detection.", + }, + DefaultLayout({ fullWidth: true }), +) { + static guide = demoGuide([ + { + label: "Look at the headers", + text: "The block declares no column: the route answers the languages, each with a badge (Base, N missing) and a coverage meter (badge, progress).", + }, + { + label: "Click a French cell, type, Enter", + text: 'editTrigger: "click", saveMode: "immediate": the cell saves on its own (Saving → Saved), Enter moves down (enterMove), Shift+Enter adds a line, Esc cancels.', + }, + { + label: "Fill a missing translation", + text: "An empty cell shows the English text greyed (placeholder). N and Shift+N jump to the next and previous empty cell (jumpToEmpty), opening its group.", + }, + { + label: "Fix a placeholder", + text: 'Status "Issues": translations whose placeholder does not match the base text ({nombre} for {count}) carry the warning (issues); fix it and the warning goes.', + }, + { + label: `Edit the French of ${CONTESTED_KEY}`, + text: 'conflicts: "detect": a colleague rewords it right after each read, so the save answers a conflict; the cell offers Overwrite (sent again with force) or Discard.', + }, + { + label: "Filter, then keep editing", + text: 'Status segments with their counts (statusFilters, counts), the namespace and language facets, the search over keys and texts. Under "Missing", a key you complete stays on screen (keepEditedRows).', + }, + { + label: "Scroll the 400 keys", + text: 'pagination: "infinite", 100 keys at a time. Groups the server builds: each row names its namespace (group), the response describes them (groups: label, description, badge); collapsible, with a row count, collapsed past 300 rows (grouping: { collapsible, count, collapseAbove }).', + }, + { + label: "Columns and export", + text: "Hide or reorder the languages (columnsMenu), export the rows shown as CSV (exportCsv). The footer line comes from the route.", + }, + ]); + + static translations = Matrix({ + title: "Back-office translations", + description: `${TRANSLATION_KEYS.length} keys in ${LANGUAGES.length} languages, ${LANGUAGE_INFO[BASE_LANGUAGE].label} the base.`, + fetchUrl: `${MATRIX_TRANSLATIONS_API}/rows`, + saveUrl: `${MATRIX_TRANSLATIONS_API}/save`, + rowHeader: { label: "Key", width: 260 }, + editTrigger: "click", + saveMode: "immediate", + conflicts: "detect", + enterMove: "down", + pagination: "infinite", + pageSize: PAGE_SIZE, + grouping: { collapsible: true, collapseAbove: COLLAPSE_ABOVE, count: true }, + statusFilters: [ + { id: "all", label: "All" }, + { id: "missing", label: "Missing", tone: "warning" }, + { id: "complete", label: "Complete", tone: "success" }, + { id: "issues", label: "Issues", tone: "error" }, + ], + facets: [ + { + id: "namespace", + label: "Namespace", + icon: "i-ph-folder", + multiple: true, + }, + { + id: "language", + label: "Language", + icon: "i-ph-globe", + multiple: true, + items: LANGUAGES.filter((language) => language !== BASE_LANGUAGE).map( + (language) => ({ + value: language, + label: LANGUAGE_INFO[language].label, + }), + ), + }, + ], + search: true, + jumpToEmpty: true, + keepEditedRows: true, + columnsMenu: true, + exportCsv: true, + emptyLabel: "No key matches the search and the filters.", + maxHeight: "75vh", + }); +} diff --git a/packages/dms/src/test/unit/interfaces/dms-base/matrix.test.ts b/packages/dms/src/test/unit/interfaces/dms-base/matrix.test.ts new file mode 100644 index 000000000..ec5ed96b2 --- /dev/null +++ b/packages/dms/src/test/unit/interfaces/dms-base/matrix.test.ts @@ -0,0 +1,165 @@ +import { expect } from "chai"; +import { + GetBlockType, + ValidateBlockOptions, +} from "@antelopejs/interface-dms/base/block-types"; +import { CodeBlock } from "@antelopejs/interface-dms/base"; +import { + Matrix, + type MatrixProps, +} from "@antelopejs/interface-dms/base/matrix"; + +const COMPONENT_NAME = "dms-matrix-block"; + +/** Every option set at once, as a page author may write them. */ +const FULL_OPTIONS: MatrixProps = { + title: "Stock", + description: "Pairs by store and size", + fetchUrl: "/api/stock?article={{params.article}}", + fetchUrlMethod: "GET", + realtimeTopic: ["stock"], + saveUrl: "/api/stock/save", + saveUrlMethod: "POST", + columns: [ + { id: "38", label: "38", kind: "number", integer: true, min: 0 }, + { + id: "status", + label: "Status", + kind: "select", + options: [{ value: "ok", label: "OK", tone: "success" }], + display: { type: "status_pill", options: { tones: { ok: "success" } } }, + excludeFromTotals: true, + }, + ], + rowHeader: { label: "Store", width: 200, numbers: true }, + editable: true, + editTrigger: "click", + typeToEdit: true, + saveMode: "staged", + review: true, + undoSeconds: 10, + conflicts: "detect", + enterMove: "right", + rowPanel: { title: "Store", showJson: true }, + fillActions: [ + { + id: "clear", + label: "Clear", + url: "/api/stock/fill/clear", + method: "POST", + }, + ], + pagination: "pages", + pageSize: 50, + pageSizes: [25, 50, 100], + search: true, + statusFilters: [{ id: "missing", label: "Missing", tone: "warning" }], + facets: [{ id: "region", label: "Region", multiple: true }], + sortable: true, + urlState: false, + grouping: { + groupByField: "region", + collapsible: true, + collapseAbove: 300, + count: true, + subtotals: true, + }, + totals: { rows: true, columns: true, label: "Total" }, + targets: { + columns: { 38: 6 }, + total: 24, + blockSave: true, + message: "Split all", + }, + crossHighlight: true, + columnsMenu: true, + resizableColumns: true, + jumpToEmpty: true, + keepEditedRows: true, + exportCsv: true, + legend: [{ label: "Out of range", hatched: true }], + emptyLabel: "No store", + maxHeight: "60vh", + density: "compact", +}; + +/** + * The Matrix block: a grid of rows by columns read and edited in place. Its + * factory hands the options through, serializing the cell action's + * component, and the catalog lists it with the schema of every option. + */ +describe("[unit] interfaces/dms-base — Matrix", () => { + it("serializes under its block component name", () => { + const serialized = Matrix({ title: "Stock" }).serializeSync(); + expect(serialized.componentName).to.equal(COMPONENT_NAME); + expect(serialized.options).to.deep.include({ title: "Stock" }); + }); + + it("takes the bare call of a page under construction", () => { + const serialized = Matrix().serializeSync(); + expect(serialized.componentName).to.equal(COMPONENT_NAME); + expect(serialized.options).to.deep.equal({}); + }); + + it("hands every option through as written", () => { + const { realtimeTopic: _topic, ...options } = FULL_OPTIONS; + const serialized = Matrix(FULL_OPTIONS).serializeSync(); + expect(serialized.options).to.deep.include(options); + expect(serialized.options?.grouping).to.deep.equal(FULL_OPTIONS.grouping); + }); + + it("serializes the component a cell action opens", () => { + const serialized = Matrix({ + cellAction: { + type: "drawer", + direction: "right", + title: "Order", + component: CodeBlock({ code: "{{row.id}} {{row.column}}" }), + }, + }).serializeSync(); + const action = serialized.options?.cellAction; + expect(action?.type).to.equal("drawer"); + const component = action?.type === "drawer" ? action.component : undefined; + expect(component?.componentName).to.be.a("string"); + expect(component?.options).to.deep.include({ + code: "{{row.id}} {{row.column}}", + }); + }); + + it("leaves a page or link cell action as it is", () => { + const target = { type: "page" as const, url: "/stock/{{row.id}}" }; + const serialized = Matrix({ cellAction: target }).serializeSync(); + expect(serialized.options?.cellAction).to.deep.equal(target); + }); + + it("is listed in the catalog with its schema", () => { + const block = GetBlockType("Matrix"); + expect(block?.componentName).to.equal(COMPONENT_NAME); + expect(block?.meta.group).to.equal("data"); + expect(block?.config.editTrigger?.enum).to.deep.equal([ + "click", + "doubleClick", + ]); + expect(block?.config.saveMode?.enum).to.deep.equal(["immediate", "staged"]); + expect(block?.config.pagination?.enum).to.deep.equal([ + "none", + "pages", + "infinite", + ]); + expect(block?.config.grouping).to.not.equal(undefined); + }); + + it("accepts a full set of options, and no option at all", () => { + const { cellAction: _action, ...options } = FULL_OPTIONS; + expect(ValidateBlockOptions("Matrix", options).valid).to.equal(true); + expect(ValidateBlockOptions("Matrix", {}).valid).to.equal(true); + }); + + it("refuses values outside its enums", () => { + const valid = (options: Record) => + ValidateBlockOptions("Matrix", options).valid; + expect(valid({ saveMode: "later" })).to.equal(false); + expect(valid({ editTrigger: "hover" })).to.equal(false); + expect(valid({ pageSize: 0 })).to.equal(false); + }); +}); From c4c4793e3f43441e1317134f72a8aa5b30be4bf1 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:26:44 +0100 Subject: [PATCH 06/41] feat(interface): offer a TableView inlineEdit option Simple edit in the grid: eligible cells become their form input and each edit is written at once through the Edit route. Dropped without the edit grant, ignored on source tables. --- .../src/base/table-view/factory.ts | 4 ++ .../src/base/table-view/options.ts | 40 +++++++++++++++++++ .../src/base/table-view/schema.ts | 19 +++++++++ 3 files changed, 63 insertions(+) diff --git a/packages/interface-dms/src/base/table-view/factory.ts b/packages/interface-dms/src/base/table-view/factory.ts index 78c6beafd..56a5040e8 100644 --- a/packages/interface-dms/src/base/table-view/factory.ts +++ b/packages/interface-dms/src/base/table-view/factory.ts @@ -220,6 +220,7 @@ export function TableView( pageSize: options.pageSize, pagination: options.pagination, reorder: options.reorder, + inlineEdit: options.inlineEdit, footer: serializeFooter(controller.name, meta, options.footer), emptyStates: serializeEmptyStates(options.emptyStates), displays: serializeTableViewDisplays(options), @@ -407,6 +408,9 @@ export function TableView( // entry is left out too, like the add/edit/delete buttons. enableTableExport: options.enableTableExport && grants.export, formComponents: adaptedFormComponents, + // Inline edits go through the edit route, like the edit form it reads + // its fields from: a caller without the edit action has neither. + inlineEdit: grants.edit ? options.inlineEdit : undefined, rowActions: adaptedRowActions, customButtons: adaptedCustomButtons, tabs: adaptedTabs, diff --git a/packages/interface-dms/src/base/table-view/options.ts b/packages/interface-dms/src/base/table-view/options.ts index c95f580d7..c206cc565 100644 --- a/packages/interface-dms/src/base/table-view/options.ts +++ b/packages/interface-dms/src/base/table-view/options.ts @@ -399,6 +399,19 @@ export interface TableViewReorderOptions { field: string; } +/** + * Which cells a table view edits in place (see + * {@link TableViewOptions.inlineEdit}). + */ +export interface TableViewInlineEditOptions { + /** + * The columns edited in place, by field id, among those that can be. Left + * out, every column that can be. + * @example ["price", "stock", "active"] + */ + columns?: string[]; +} + /** What a footer summary computes over the rows the table lists. */ export type TableViewSummaryOperation = "sum" | "count"; @@ -1130,6 +1143,33 @@ export interface TableViewOptions< * filter or a tab narrows the rows. Needs the `edit` action. */ reorder?: TableViewReorderOptions; + /** + * Lets the user edit a row's simple values in the grid, one cell at a + * time, each saved at once by a partial edit (`PUT /edit` with + * that field alone): a click on a cell turns it into its field's input, + * Enter or leaving the cell saves, Esc cancels; a pick in a select or a + * date picker saves, and a switch or a checkbox saves as it toggles, + * without opening anything. The click edits the cell and does not open + * the row; a click anywhere else on the row still does. + * + * A cell is edited in place when its column is listed, is in the edit + * form and writable there, is not localized, and its input is a simple + * one: a text, email, phone or URL, a number, price or percentage, a + * switch or checkbox, a single select or segmented select, a single date, + * a time or a colour. Any other column (a relation, rich text, code, + * files, images, a list, an address, key-values, tags) keeps its display + * and is edited through the edit form. A row the `edit` action's `rule` + * refuses keeps its display, and so does a field its `disabledWhen` makes + * read-only or its `visibleWhen` hides, evaluated on the listed row. + * + * On the grid and the `grouped` display; the board and the cards are + * left as they are. Needs the `edit` action: a caller without it gets the + * read-only grid. Ignored by `TableView.fromSource`, which has no edit + * route. + * @example true + * @example { columns: ["price", "stock", "active"] } + */ + inlineEdit?: boolean | TableViewInlineEditOptions; /** * Offers the `grouped` display: the grid's columns with a header row per * group of rows. A view may open in it (`display: "grouped"`). diff --git a/packages/interface-dms/src/base/table-view/schema.ts b/packages/interface-dms/src/base/table-view/schema.ts index 051c6c9b6..2f3cc87d4 100644 --- a/packages/interface-dms/src/base/table-view/schema.ts +++ b/packages/interface-dms/src/base/table-view/schema.ts @@ -269,6 +269,25 @@ export const TableViewSchema = z.object({ .describe("Whether a row opens with one click or two."), { label: "Row click", group: "features", widget: "segmented" }, ), + inlineEdit: ui( + z + .union([ + z.boolean(), + z.object({ + columns: ui(z.array(z.string()).optional(), { + label: "Columns", + widget: "field", + // Only a listed column has a cell to edit. + fieldAspect: "listable", + }), + }), + ]) + .optional() + .describe( + "Edit a row's simple values in the grid, each saved at once; `{ columns }` names the ones edited.", + ), + { label: "Edit in the grid", group: "features", widget: "switch" }, + ), expandable: ui( expandableSchema .optional() From cdc2a694569b2f50d71c6ef22628963b01efc842 Mon Sep 17 00:00:00 2001 From: Maxime Westhoven Date: Sun, 25 Oct 2026 10:26:44 +0100 Subject: [PATCH 07/41] feat(ui): edit a TableView's simple cells in place, saved at once --- .../build/components/table/InlineEditCell.vue | 273 ++++++++++++++++ .../table-view/useTableInlineEdit.ts | 309 ++++++++++++++++++ .../table-view/utils/inlineEdit.ts | 133 ++++++++ .../app/components/table-view/TableView.vue | 38 +++ .../composables/table-view/types/config.ts | 8 + .../layers/dms-ui/i18n/locales/ui-en-GB.json | 7 + .../layers/dms-ui/i18n/locales/ui-fr-FR.json | 7 + .../tests/table-view-inline-edit.test.ts | 246 ++++++++++++++ .../dms-base/table-view-inline-edit.test.ts | 104 ++++++ 9 files changed, 1125 insertions(+) create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/components/table/InlineEditCell.vue create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableInlineEdit.ts create mode 100644 packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/inlineEdit.ts create mode 100644 packages/dms/frontend-vue/tests/table-view-inline-edit.test.ts create mode 100644 packages/dms/src/test/unit/interfaces/dms-base/table-view-inline-edit.test.ts diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/components/table/InlineEditCell.vue b/packages/dms/frontend-vue/layers/dms-ui/app/build/components/table/InlineEditCell.vue new file mode 100644 index 000000000..ab25b5f5b --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/components/table/InlineEditCell.vue @@ -0,0 +1,273 @@ + + + diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableInlineEdit.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableInlineEdit.ts new file mode 100644 index 000000000..32f4e90b1 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/useTableInlineEdit.ts @@ -0,0 +1,309 @@ +import { get } from "@nuxt/ui/runtime/utils/index.js"; +import type { ComputedRef, Ref } from "vue"; +import type { DataType } from "#dms-core/app/composables/data-types/useDataType"; +import type { FormFieldOrGroup } from "../../../composables/form/types/field"; +import { + collectSubmitData, + createFieldValueComparer, + withConditionFields, +} from "../../../composables/form/useForm"; +import type { + TableViewColumn, + TableViewInlineEditConfig, + TableViewListResponse, +} from "../../../composables/table-view/types"; +import { + type InlineEditColumn, + resolveInlineEditColumns, +} from "./utils/inlineEdit"; + +export interface TableInlineEditOptions { + /** The backend `inlineEdit` option. */ + inlineEdit: boolean | TableViewInlineEditConfig | undefined; + /** + * The fields of the edit form, which say what may be edited and how. The + * server leaves the form out for a caller without the edit action. + */ + editFields: ReadonlyArray | undefined; + columns: ReadonlyArray; + /** The page listed; a saved value updates it in place. */ + data: Ref | null | undefined>; + rowIdKey: string; + /** The field naming a row, for the label of its cells' inputs. */ + labelKey?: string; + location: string; + api: ReturnType; + getDataType: (type: string) => DataType | undefined; + /** The `edit` action's rule accepts the row. */ + canEditRow: (row: T) => boolean; + /** Cells may be edited now (not while the archived rows are listed). */ + isEnabled: ComputedRef; + /** Reads a saved row again, for what the server derived from the edit. */ + refreshRow: (id: string) => Promise | void; + /** After a save: what counts or summarises the rows reads them again. */ + onSaved: () => Promise | void; + onError: (error: unknown) => void; +} + +/** The cell open for editing, and the value its input holds. */ +interface ActiveInlineEdit { + rowId: string; + columnId: string; + draft: unknown; + /** The row's value as the input started with it. */ + initial: unknown; +} + +/** A save in flight, and the value it writes. */ +interface PendingInlineSave { + value: unknown; +} + +const cellKey = (rowId: string, columnId: string) => + `${rowId}\u0000${columnId}`; + +/** + * The simple values of a row edited in the grid, one cell at a time, each + * saved at once by a partial edit of its field (backend `inlineEdit`). An + * unchanged value sends nothing; a refused one keeps its cell open on the + * value typed, marked invalid, whichever cell the user went on to. + */ +export function useTableInlineEdit(options: TableInlineEditOptions) { + const { data, rowIdKey } = options; + const isSameValue = createFieldValueComparer(options.getDataType); + + const editableColumns = resolveInlineEditColumns( + options.inlineEdit, + options.editFields, + options.columns, + ); + const conditionFields = [...editableColumns.values()].map( + (column) => column.field, + ); + + const active = ref(null); + const pending = ref>({}); + const invalidKey = ref(null); + + const columns = computed(() => + options.isEnabled.value ? [...editableColumns.values()] : [], + ); + + const rowIdOf = (row: T): string | undefined => { + const id = get(row as never, rowIdKey); + return id === undefined || id === null ? undefined : String(id); + }; + + const rowLabel = (row: T): string => { + const label = options.labelKey + ? get(row as never, options.labelKey) + : undefined; + return String(label ?? rowIdOf(row) ?? ""); + }; + + const columnOf = (columnId: string) => + options.isEnabled.value ? editableColumns.get(columnId) : undefined; + + // A field's `visibleWhen` / `disabledWhen` read on the listed row: the + // edit route strips a field they hide or lock, so its cell is not offered. + const isLockedOnRow = (row: T, fieldId: string): boolean => { + const { disabled, hidden } = withConditionFields( + conditionFields, + row as Record, + {}, + ); + return disabled.has(fieldId) || hidden.has(fieldId); + }; + + const isCellEditable = (row: T, columnId: string): boolean => { + const column = columnOf(columnId); + if (!column || rowIdOf(row) === undefined) return false; + if (!options.canEditRow(row)) return false; + return !isLockedOnRow(row, column.field.id); + }; + + const rowValue = (row: T, column: InlineEditColumn): unknown => + get(row as never, column.field.id); + + // The value as the edit form would hold it: its data type maps the row's + // value into the form's state first (a relation's row to its id). + const stateValue = (row: T, column: InlineEditColumn): unknown => { + const value = rowValue(row, column); + const type = column.field.type; + const mapper = type + ? options.getDataType(type)?.beforeStateMapper + : undefined; + return mapper && value !== undefined + ? mapper(value, column.field.component.options) + : value; + }; + + const isEditing = (row: T, columnId: string): boolean => { + const cell = active.value; + return !!cell && cell.columnId === columnId && cell.rowId === rowIdOf(row); + }; + + const keyOf = (row: T, columnId: string): string => + cellKey(rowIdOf(row) ?? "", columnId); + + const isSaving = (row: T, columnId: string): boolean => + !!pending.value[keyOf(row, columnId)]; + + const isInvalid = (row: T, columnId: string): boolean => + invalidKey.value === keyOf(row, columnId); + + /** The value the cell shows: the one being saved, else the row's. */ + const valueOf = (row: T, columnId: string): unknown => { + const saving = pending.value[keyOf(row, columnId)]; + if (saving) return saving.value; + const column = columnOf(columnId); + return column ? stateValue(row, column) : undefined; + }; + + const start = (row: T, columnId: string): boolean => { + const column = columnOf(columnId); + const rowId = rowIdOf(row); + if (!column || rowId === undefined || !isCellEditable(row, columnId)) { + return false; + } + if (isEditing(row, columnId)) return true; + // One cell at a time: the one left saves first, as leaving it does. + if (active.value) void commitCell(active.value); + const initial = stateValue(row, column); + active.value = { rowId, columnId, draft: initial, initial }; + invalidKey.value = null; + return true; + }; + + const setDraft = (value: unknown) => { + if (active.value) active.value = { ...active.value, draft: value }; + }; + + const cancel = () => { + active.value = null; + invalidKey.value = null; + }; + + // The body the edit form would send for this field alone: nothing when the + // value did not change, a cleared value as the form clears it. + const changeBody = ( + column: InlineEditColumn, + value: unknown, + initial: unknown, + ): Record | undefined => { + const { field } = column; + const body = collectSubmitData({ [field.id]: value }, [field], { + initialValues: { [field.id]: initial }, + onlyChanged: true, + isSameValue, + }); + return field.id in body ? body : undefined; + }; + + const patchRow = (rowId: string, body: Record) => { + const page = data.value; + if (!page) return; + data.value = { + ...page, + results: page.results.map((row) => + rowIdOf(row) === rowId ? ({ ...row, ...body } as T) : row, + ), + }; + }; + + const write = async ( + rowId: string, + columnId: string, + body: Record, + ): Promise => { + const key = cellKey(rowId, columnId); + const [value] = Object.values(body); + pending.value = { ...pending.value, [key]: { value } }; + try { + await options.api(`${options.location}/edit`, { + method: "PUT", + query: { id: rowId }, + body, + }); + } catch (error) { + options.onError(error); + return false; + } finally { + const { [key]: _done, ...rest } = pending.value; + pending.value = rest; + } + patchRow(rowId, body); + void options.refreshRow(rowId); + void options.onSaved(); + return true; + }; + + const commitCell = async (cell: ActiveInlineEdit): Promise => { + const key = cellKey(cell.rowId, cell.columnId); + if (pending.value[key]) return false; + const column = columnOf(cell.columnId); + const body = column && changeBody(column, cell.draft, cell.initial); + const isActive = () => + active.value?.rowId === cell.rowId && + active.value.columnId === cell.columnId; + if (!body) { + if (isActive()) cancel(); + return true; + } + if (await write(cell.rowId, cell.columnId, body)) { + if (isActive()) active.value = null; + if (invalidKey.value === key) invalidKey.value = null; + return true; + } + // Back to the refused cell with what was typed, even if the user went on. + active.value = cell; + invalidKey.value = key; + return false; + }; + + /** + * Saves the open cell's value (Enter, leaving the cell, a pick); without a + * change, only closes it. Given a cell, only if that one is open. + */ + const commit = (row?: T, columnId?: string): Promise => { + const cell = active.value; + if (!cell) return Promise.resolve(false); + const isOtherCell = + row !== undefined && + (cell.rowId !== rowIdOf(row) || cell.columnId !== columnId); + return isOtherCell ? Promise.resolve(false) : commitCell(cell); + }; + + /** Saves a switch or a checkbox as it toggles: no cell opens. */ + const toggle = async (row: T, columnId: string, value: unknown) => { + const column = columnOf(columnId); + const rowId = rowIdOf(row); + if (!column || rowId === undefined || !isCellEditable(row, columnId)) { + return false; + } + if (pending.value[cellKey(rowId, columnId)]) return false; + const body = changeBody(column, value, stateValue(row, column)); + if (!body) return true; + return write(rowId, columnId, body); + }; + + return { + columns, + columnOf, + rowLabel, + isCellEditable, + isEditing, + isSaving, + isInvalid, + valueOf, + draft: computed(() => active.value?.draft), + start, + setDraft, + cancel, + commit, + toggle, + }; +} + +/** The inline edit of a table view, as its cells use it. */ +export type TableInlineEdit = ReturnType>; diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/inlineEdit.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/inlineEdit.ts new file mode 100644 index 000000000..383c21c6a --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/table-view/utils/inlineEdit.ts @@ -0,0 +1,133 @@ +import type { + FormField, + FormFieldOrGroup, +} from "../../../../composables/form/types/field"; +import { isFieldGroup } from "../../../../composables/form/types/field"; +import type { TableViewColumn } from "../../../../composables/table-view/types/column"; +import type { TableViewInlineEditConfig } from "../../../../composables/table-view/types/config"; + +/** + * How an edited cell saves: `type` on Enter or when the cell loses focus, + * `pick` as soon as a value is picked (a select, a date), `toggle` as the + * control toggles, without an edit state (a switch, a checkbox). + */ +export type InlineEditCommit = "type" | "pick" | "toggle"; + +/** How a cell opens the picker of its control (see `opensPicker`). */ +export type InlineEditPickerOpening = "defaultOpen" | "click"; + +/** What a simple control needs to be edited in a cell. */ +interface InlineEditControl { + commit: InlineEditCommit; + /** + * The control is a trigger opening a picker, which the cell opens with the + * edit rather than asking for a second click: through the control's + * `defaultOpen` prop, or by clicking its trigger. + */ + opensPicker?: InlineEditPickerOpening; +} + +/** A column edited in place: its form field and how its cell saves. */ +export interface InlineEditColumn extends InlineEditControl { + columnId: string; + field: FormField; +} + +// The simple controls, by normalized component name (see +// `normalizeControlName`). Anything else, a relation, rich text, code, files, +// a list, keeps its display and is edited through the form. +const INLINE_EDIT_CONTROLS: Record = { + inputtext: { commit: "type" }, + inputemail: { commit: "type" }, + inputphone: { commit: "type" }, + inputnumber: { commit: "type" }, + inputpercentage: { commit: "type" }, + inputtime: { commit: "type" }, + inputcolor: { commit: "type" }, + select: { commit: "pick", opensPicker: "defaultOpen" }, + datepicker: { commit: "pick", opensPicker: "click" }, + segmentedselect: { commit: "pick" }, + switch: { commit: "toggle" }, + checkbox: { commit: "toggle" }, +}; + +// Options turning a simple control into a list or a range of values, which a +// cell does not edit. +const LIST_VALUE_OPTIONS = ["multiple", "range"]; + +const DMS_COMPONENT_PREFIX = "dms"; + +/** `dms-input-text`, `DmsInputText` and `InputText` all read `inputtext`. */ +function normalizeControlName(name: string): string { + const flat = name.toLowerCase().replace(/[^a-z0-9]/g, ""); + return flat.startsWith(DMS_COMPONENT_PREFIX) + ? flat.slice(DMS_COMPONENT_PREFIX.length) + : flat; +} + +/** The fields of a form, its groups' included. */ +export function flattenFormFields( + entries: ReadonlyArray, +): FormField[] { + return entries.flatMap((entry) => + isFieldGroup(entry) ? entry.fields : [entry], + ); +} + +/** + * How a field of the edit form is edited in a cell, or `undefined` when it + * is not: read-only there, localized (one value per language), or drawn by a + * control other than a simple one. + */ +export function inlineEditControl( + field: FormField, +): InlineEditControl | undefined { + if (field.disabled || field.readonly || field.localized) return undefined; + const name = field.component?.componentName; + if (!name) return undefined; + const control = INLINE_EDIT_CONTROLS[normalizeControlName(name)]; + if (!control) return undefined; + const options = (field.component.options ?? {}) as Record; + if (LIST_VALUE_OPTIONS.some((key) => !!options[key])) return undefined; + return control; +} + +/** The ids `inlineEdit` restricts the edit to, or `undefined` for all. */ +function restrictedFieldIds( + inlineEdit: boolean | TableViewInlineEditConfig, +): Set | undefined { + if (typeof inlineEdit !== "object" || !inlineEdit.columns) return undefined; + return new Set(inlineEdit.columns); +} + +/** + * The columns the grid edits in place, by column id: listed, in the edit + * form (the fields it leaves out are hidden there) and edited there by a + * simple control, among those `inlineEdit.columns` names. None without the + * option or without an edit form, which the server leaves out for a caller + * without the edit action. + */ +export function resolveInlineEditColumns( + inlineEdit: boolean | TableViewInlineEditConfig | undefined, + editFields: ReadonlyArray | undefined, + columns: ReadonlyArray< + Pick + >, +): Map { + const resolved = new Map(); + if (!inlineEdit || !editFields) return resolved; + const restricted = restrictedFieldIds(inlineEdit); + const fields = new Map( + flattenFormFields(editFields).map((field) => [field.id, field]), + ); + for (const column of columns) { + if (!column.listable) continue; + if (restricted && !restricted.has(column.accessorKey)) continue; + const field = fields.get(column.accessorKey); + const control = field && inlineEditControl(field); + if (!field || !control) continue; + const columnId = column.id ?? column.accessorKey; + resolved.set(columnId, { columnId, field, ...control }); + } + return resolved; +} diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/TableView.vue b/packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/TableView.vue index 9e97e1aa7..133280db6 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/TableView.vue +++ b/packages/dms/frontend-vue/layers/dms-ui/app/components/table-view/TableView.vue @@ -41,6 +41,7 @@ import type { TableViewPaginationMode, TableViewSourceConfig, TableViewReorderConfig, + TableViewInlineEditConfig, TableViewTab, } from "../../composables/table-view/types"; import { @@ -162,6 +163,8 @@ import type { TableViewLiveHoldOptions } from "../../types/live"; import { usePageLive } from "../../composables/live/usePageLive"; import LiveHoldBanner from "../../build/components/table-view/LiveHoldBanner.vue"; import { useTableReorder } from "../../build/composables/table-view/useTableReorder"; +import { useTableInlineEdit } from "../../build/composables/table-view/useTableInlineEdit"; +import InlineEditCell from "../../build/components/table/InlineEditCell.vue"; import { groupedOptionsFor, listTableSorting, @@ -241,6 +244,8 @@ interface TableViewProps extends TableViewConfig { source?: TableViewSourceConfig; /** Rows ordered by hand on a number column (backend `reorder`). */ reorder?: TableViewReorderConfig; + /** Simple values edited in the grid (backend `inlineEdit`). */ + inlineEdit?: boolean | TableViewInlineEditConfig; /** Rows listed first whatever the sort (backend `pinnedRows`). */ pinnedRows?: RowActionRule; /** Footer texts and figures: row count, hint, summaries and legend. */ @@ -1398,6 +1403,36 @@ const { reorderState } = useTableReorder({ }), }); +// Simple values edited in the grid, each saved at once. The edit form says +// which fields may be edited and how: the server leaves it out for a caller +// without the edit action, and a source table has none, so neither edits. +const inlineEditing = useTableInlineEdit({ + inlineEdit: props.inlineEdit, + editFields: formComponents.edit?.options?.fields, + columns: allColumns, + data, + rowIdKey: props.rowIdKey ?? ROW_ID_DEFAULT_KEY, + labelKey, + location, + api: $authFetch, + getDataType, + canEditRow: (row) => + isRowActionEnabled(tableProps.value.rowActions?.edit, row), + isEnabled: computed(() => !tableRows.isSource && !showArchived.value), + refreshRow: (id) => patchRowLocal(id), + onSaved: () => refreshCounts(), + onError: (failure) => + toast.add({ + title: t("dms.table.inline_edit.error"), + description: describeTableWriteError(failure, t, allColumns, processI18n), + color: Color.error, + icon: "i-ph-warning-circle", + }), +}); +const inlineEditSlots = computed(() => + inlineEditing.columns.value.map(({ columnId }) => `${columnId}-cell`), +); + const { grouping, refreshCounts: refreshGroupCounts } = useGroupedRows({ grouped: activeGroupedOptions, isActive: isGroupedDisplay, @@ -2527,6 +2562,9 @@ onMounted(() => { @delete="deleteView" /> + diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixColumns.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixColumns.ts index 1f8f7ec42..a88500925 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixColumns.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixColumns.ts @@ -94,17 +94,21 @@ const KIND_WIDTHS: Partial, number>> = boolean: BOOLEAN_COLUMN_WIDTH, }; -/** A column's width: dragged to, declared, or its kind's. */ +/** + * A column's width: dragged to (within the drag's bounds), else declared as + * it is, else its kind's. + */ export function matrixColumnWidth( column: MatrixColumn, preferences: MatrixColumnPreferences, ): number { - const width = - preferences.widths?.[column.id] ?? + const dragged = preferences.widths?.[column.id]; + if (dragged !== undefined) return clampColumnWidth(dragged); + return ( column.width ?? KIND_WIDTHS[column.kind ?? "text"] ?? - MATRIX_DEFAULT_COLUMN_WIDTH; - return clampColumnWidth(width); + MATRIX_DEFAULT_COLUMN_WIDTH + ); } /** The order after moving `columnId` by `step` places among `columns`. */ diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixCsv.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixCsv.ts index 668332dbe..fc2324145 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixCsv.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixCsv.ts @@ -57,5 +57,6 @@ export function downloadTextFile( link.href = url; link.download = fileName; link.click(); - URL.revokeObjectURL(url); + // Revoked once the browser took the download over, not before. + setTimeout(() => URL.revokeObjectURL(url)); } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixLayout.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixLayout.ts new file mode 100644 index 000000000..129d67cb4 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixLayout.ts @@ -0,0 +1,72 @@ +import type { MatrixAlign, MatrixColumn } from "../../../types/matrix"; +import { totalColumnIndex } from "./matrixTotals"; +import { kindOf } from "./matrixValues"; + +/** A data column of the grid, where it sits. */ +export interface MatrixColumnSlot { + type: "column"; + key: string; + column: MatrixColumn; + /** From 1, the row header being 1. */ + colIndex: number; + /** Inline start of a pinned column, in pixels. */ + stickyStart?: number; +} + +/** The Total column, where it sits. */ +export interface MatrixTotalSlot { + type: "total"; + key: string; + colIndex: number; +} + +/** A column of the grid, data or Total, in the order drawn. */ +export type MatrixGridSlot = MatrixColumnSlot | MatrixTotalSlot; + +const TOTAL_SLOT_KEY = "\u0000total"; +// The row header is column 1. +const FIRST_COLUMN_INDEX = 2; + +/** + * The columns in the order drawn, with the Total column after the last one + * it adds up and before the ones left out of the totals (annexes stay at + * the right). Pinned columns stick after the row header, one after another. + */ +export function matrixGridSlots( + columns: MatrixColumn[], + widthOf: (column: MatrixColumn) => number, + rowHeaderWidth: number, + hasTotalColumn: boolean, +): MatrixGridSlot[] { + const totalAt = hasTotalColumn ? totalColumnIndex(columns) : -1; + const slots: MatrixGridSlot[] = []; + let stickyStart = rowHeaderWidth; + let isPinnedRun = true; + columns.forEach((column, index) => { + if (index === totalAt) slots.push(totalSlot(slots.length)); + isPinnedRun = isPinnedRun && column.pinned === true; + slots.push({ + type: "column", + key: column.id, + column, + colIndex: slots.length + FIRST_COLUMN_INDEX, + ...(isPinnedRun && { stickyStart }), + }); + if (isPinnedRun) stickyStart += widthOf(column); + }); + if (totalAt >= columns.length) slots.push(totalSlot(slots.length)); + return slots; +} + +function totalSlot(position: number): MatrixTotalSlot { + return { + type: "total", + key: TOTAL_SLOT_KEY, + colIndex: position + FIRST_COLUMN_INDEX, + }; +} + +/** How a column's cells, sums and subtotals align: its own, or numbers at the end. */ +export function columnAlign(column: MatrixColumn): MatrixAlign { + return column.align ?? (kindOf(column) === "number" ? "end" : "start"); +} diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixQuery.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixQuery.ts index 17e2f0716..264a24031 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixQuery.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixQuery.ts @@ -12,6 +12,20 @@ export interface MatrixSort { direction: MatrixSortDirection; } +/** How a column filter compares: the value holds the text, or is it. */ +export type MatrixColumnFilterMode = "contains" | "is"; + +/** A column's header filter. */ +export interface MatrixColumnFilter { + mode: MatrixColumnFilterMode; + value: string; +} + +export const MATRIX_COLUMN_FILTER_MODES: readonly MatrixColumnFilterMode[] = [ + "contains", + "is", +]; + /** What the grid asks its route for, besides the page's own URL. */ export interface MatrixQueryState { /** From 0. */ @@ -23,6 +37,8 @@ export interface MatrixQueryState { /** The values picked in each facet, by facet id. */ facets: Record; sort: MatrixSort | null; + /** The header filters in use, by column id. */ + filters: Record; } export const DEFAULT_MATRIX_PAGE_SIZE = 50; @@ -30,6 +46,8 @@ export const DEFAULT_MATRIX_PAGE_SIZES = [25, 50, 100, 200]; /** Pages shown on each side of the current one in the pager. */ const PAGE_WINDOW = 2; const FACET_PREFIX = "facet_"; +const FILTER_PREFIX = "filter_"; +const FILTER_SEPARATOR = ":"; const FACET_SEPARATOR = ","; export function emptyMatrixQuery(pageSize: number): MatrixQueryState { @@ -40,6 +58,7 @@ export function emptyMatrixQuery(pageSize: number): MatrixQueryState { status: "", facets: {}, sort: null, + filters: {}, }; } @@ -48,6 +67,33 @@ export function facetParam(facetId: string): string { return `${FACET_PREFIX}${facetId}`; } +/** The query parameter a column filter is sent under. */ +export function columnFilterParam(columnId: string): string { + return `${FILTER_PREFIX}${columnId}`; +} + +/** `contains:alma`: a column filter as its parameter's value. */ +export function columnFilterText(filter: MatrixColumnFilter): string { + return `${filter.mode}${FILTER_SEPARATOR}${filter.value}`; +} + +/** A column filter read back from its parameter's value, if it is one. */ +export function parseColumnFilter(text: string): MatrixColumnFilter | null { + const separator = text.indexOf(FILTER_SEPARATOR); + if (separator < 0) return null; + const mode = text.slice(0, separator) as MatrixColumnFilterMode; + const value = text.slice(separator + 1); + if (!MATRIX_COLUMN_FILTER_MODES.includes(mode) || !value) return null; + return { mode, value }; +} + +/** The column a filter parameter names, if it is one. */ +export function columnOfFilterParam(param: string): string | null { + return param.startsWith(FILTER_PREFIX) + ? param.slice(FILTER_PREFIX.length) || null + : null; +} + /** The query parameters of the filters and the sort, without the page. */ export function matrixFilterParams( state: MatrixQueryState, @@ -59,6 +105,10 @@ export function matrixFilterParams( for (const [id, values] of Object.entries(state.facets)) { if (values.length) params[facetParam(id)] = values.join(FACET_SEPARATOR); } + for (const [columnId, filter] of Object.entries(state.filters)) { + if (filter.value) + params[columnFilterParam(columnId)] = columnFilterText(filter); + } if (state.sort) { params.sort = state.sort.columnId; params.direction = state.sort.direction; @@ -102,10 +152,20 @@ export function pageCountOf(total: number, pageSize: number): number { return Math.max(1, Math.ceil(total / Math.max(1, pageSize))); } -/** A page button, or the gap between two that are not neighbours. */ -export type MatrixPagerItem = - | { type: "page"; page: number } - | { type: "gap"; key: string }; +/** A page button of the pager. */ +export interface MatrixPagerPage { + type: "page"; + /** From 0. */ + page: number; +} + +/** The gap (…) between two page buttons that are not neighbours. */ +export interface MatrixPagerGap { + type: "gap"; + key: string; +} + +export type MatrixPagerItem = MatrixPagerPage | MatrixPagerGap; /** * The pager's buttons: the first and last pages, the ones around the current @@ -146,6 +206,26 @@ function rowMatches(row: MatrixRow, needle: string): boolean { return haystack.some((text) => text.toLowerCase().includes(needle)); } +const FILTER_MATCHERS: Record< + MatrixColumnFilterMode, + (text: string, needle: string) => boolean +> = { + contains: (text, needle) => text.includes(needle), + is: (text, needle) => text === needle, +}; + +function matchesFilters( + row: MatrixRow, + filters: Record, +): boolean { + return Object.entries(filters).every(([columnId, filter]) => + FILTER_MATCHERS[filter.mode]( + valueText(row.values[columnId]).toLowerCase(), + filter.value.toLowerCase(), + ), + ); +} + function compareValues(left: unknown, right: unknown): number { if (typeof left === "number" && typeof right === "number") return left - right; @@ -155,7 +235,7 @@ function compareValues(left: unknown, right: unknown): number { } /** - * The rows of `staticData` under the grid's search, sort and page, read in + * The rows of `staticData` under the grid's search, column filters, sort and page, read in * the browser as the route would (status and facets name a route's own * filters: static rows keep them all). */ @@ -165,9 +245,11 @@ export function applyStaticQuery( pagination: MatrixPagination, ): MatrixData { const needle = state.search.trim().toLowerCase(); - let rows = needle - ? data.rows.filter((row) => rowMatches(row, needle)) - : [...data.rows]; + let rows = data.rows.filter( + (row) => + (!needle || rowMatches(row, needle)) && + matchesFilters(row, state.filters), + ); const sort = state.sort; if (sort) { const sign = sort.direction === "asc" ? 1 : -1; diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixRender.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixRender.ts new file mode 100644 index 000000000..80f7c3937 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixRender.ts @@ -0,0 +1,43 @@ +import type { BlockText } from "#dms-core/app/types/composed-text"; +import type { MatrixCellKind, MatrixColumn } from "../../../types/matrix"; +import type { RenderableColumn } from "../data-types/useColumnValueRenderer"; +import { kindOf } from "./matrixValues"; + +/** The DMS data type a kind's values are drawn with, as a table view draws them. */ +const RENDER_TYPE_IDS: Partial> = { + number: "number", + boolean: "boolean", + date: "date", + select: "select", + tags: "select", +}; +const FALLBACK_TYPE_ID = "string"; + +/** A select option as a data type's `items` read it: value, label, icon. */ +type MatrixRenderItem = Record; + +/** + * A Matrix column as the DMS's value renderer takes it: its `display`, and a + * data type built from its kind whose options are the column's choices, so + * a display drawing a select's value (`status_pill`) shows their labels. + */ +export function matrixRenderColumn( + column: MatrixColumn, + text: (value: BlockText) => string, +): RenderableColumn { + const items: MatrixRenderItem[] = (column.options ?? []).map((option) => ({ + value: option.value, + label: text(option.label), + ...(option.icon && { icon: option.icon }), + })); + return { + id: column.id, + display: column.display, + type: { + id: RENDER_TYPE_IDS[kindOf(column)] ?? FALLBACK_TYPE_ID, + compareModes: [], + filterComponents: {}, + inputComponent: { options: { items } }, + }, + }; +} diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSaveEngine.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSaveEngine.ts index af798ec88..057ddb204 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSaveEngine.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSaveEngine.ts @@ -12,11 +12,21 @@ import { isSameValue } from "./matrixValues"; /** * An edited cell not written yet: `pending` (staged, or held in immediate * mode while a `blockSave` target is missed), `saving`, or `failed` (the - * draft kept with the server's message, or the value it holds now on a - * conflict). + * draft kept with the server's message, or with the value stored meanwhile + * on a conflict). */ export type MatrixEditStatus = "pending" | "saving" | "failed"; +/** The value stored meanwhile, after a conflict: Overwrite or Discard. */ +export interface MatrixEditConflict { + current: unknown; +} + +/** A value committed while the cell's previous write still runs. */ +export interface MatrixQueuedValue { + value: unknown; +} + export interface MatrixEdit { rowId: string; columnId: string; @@ -25,10 +35,17 @@ export interface MatrixEdit { after: unknown; status: MatrixEditStatus; message?: BlockText; - /** The value stored meanwhile, after a conflict: Overwrite or Discard. */ - conflict?: { current: unknown }; + conflict?: MatrixEditConflict; + /** Written once the write in flight settles, from the value it wrote. */ + queued?: MatrixQueuedValue; } +/** A value a cell now holds on the server, to show without a read. */ +export type MatrixWrittenValue = Pick< + MatrixChange, + "rowId" | "columnId" | "value" +>; + /** What a cell shows of its saving. */ export type MatrixCellSaveState = | "idle" @@ -46,6 +63,12 @@ export interface MatrixSaveEngineOptions { isBlocked: () => boolean; /** Every answer of `saveUrl`: its rows, counts and targets go on screen. */ onResponse?: (response: MatrixSaveResponse) => void; + /** + * Values the server now holds that no returned row shows: a change the + * answer does not name counts as written, its cell keeping the value sent + * (after an undo, the value written back). + */ + onWritten?: (values: MatrixWrittenValue[]) => void; /** A change the server answered a conflict for. */ onConflict?: (conflict: MatrixConflict) => void; /** The changes a request wrote (some of them, or all). */ @@ -72,18 +95,25 @@ export function matrixCellKey(rowId: string, columnId: string): string { return `${rowId}${KEY_SEPARATOR}${columnId}`; } -const changeOf = (edit: MatrixEdit): MatrixChange => ({ +const keyOf = (edit: MatrixEdit) => matrixCellKey(edit.rowId, edit.columnId); + +/** + * The change an edit sends. Overwriting a conflict replaces the value stored + * meanwhile: that is its `previous`, and what an Undo writes back. + */ +const changeOf = (edit: MatrixEdit, isForced = false): MatrixChange => ({ rowId: edit.rowId, columnId: edit.columnId, value: edit.after, - previous: edit.before, + previous: isForced && edit.conflict ? edit.conflict.current : edit.before, }); -/** The refusals of an answer, by cell and by row. */ +/** The refusals of an answer, by cell and by row, and the rows it returns. */ interface AnswerIndex { cellErrors: Map; rowErrors: Map; conflicts: Map; + returnedRows: Set; } function indexAnswer(response: MatrixSaveResponse): AnswerIndex { @@ -91,6 +121,7 @@ function indexAnswer(response: MatrixSaveResponse): AnswerIndex { cellErrors: new Map(), rowErrors: new Map(), conflicts: new Map(), + returnedRows: new Set((response.rows ?? []).map((row) => row.id)), }; for (const error of response.errors ?? []) { if (error.columnId) @@ -109,8 +140,29 @@ function indexAnswer(response: MatrixSaveResponse): AnswerIndex { return index; } +function isRefused(answer: AnswerIndex, change: MatrixWrittenValue): boolean { + const key = matrixCellKey(change.rowId, change.columnId); + return ( + answer.cellErrors.has(key) || + answer.conflicts.has(key) || + answer.rowErrors.has(change.rowId) + ); +} + +/** The written values no returned row shows: they are patched on screen. */ +function unreturned( + answer: AnswerIndex, + values: MatrixWrittenValue[], +): MatrixWrittenValue[] { + return values + .filter((value) => !answer.returnedRows.has(value.rowId)) + .map(({ rowId, columnId, value }) => ({ rowId, columnId, value })); +} + export type MatrixSaveEngine = ReturnType; +type EditOutcome = "saved" | "failed"; + /** * The edits of a grid and their way to `saveUrl`. `immediate` writes each * committed cell at once (Saving, then Saved; a failure keeps the draft with @@ -118,6 +170,9 @@ export type MatrixSaveEngine = ReturnType; * until `saveAll` writes them together, and a cell put back as it was is no * longer an edit. While a `blockSave` target is missed nothing is written: * immediate edits wait, held, and go together once every target is met. + * A cell has one write at a time: a value committed while it runs waits, + * then goes from the value it wrote. A conflict is only written over by + * Overwrite, never by a save of every edit. */ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { const edits = reactive(new Map()); @@ -130,11 +185,13 @@ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { const editOf = (rowId: string, columnId: string) => edits.get(matrixCellKey(rowId, columnId)); + const isCurrent = (edit: MatrixEdit) => edits.get(keyOf(edit)) === edit; - /** The value a cell shows: its edit's, else what the server holds. */ + /** The value a cell shows: its edit's (a queued one first), else the server's. */ function valueOf(rowId: string, columnId: string, stored: unknown): unknown { const edit = editOf(rowId, columnId); - return edit ? edit.after : stored; + if (!edit) return stored; + return edit.queued ? edit.queued.value : edit.after; } function stateOf(rowId: string, columnId: string): MatrixCellSaveState { @@ -151,19 +208,20 @@ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { } const list = computed(() => [...edits.values()]); - const waiting = (edit: MatrixEdit) => edit.status !== "saving"; + /** An edit a save may send: not in flight, and no conflict to settle. */ + const isSendable = (edit: MatrixEdit) => + edit.status !== "saving" && !edit.conflict; - async function send(batch: MatrixEdit[], force = false): Promise { + async function send(batch: MatrixEdit[], isForced = false): Promise { if (!batch.length) return true; + const request: MatrixSaveRequest = { + changes: batch.map((edit) => changeOf(edit, isForced)), + ...(isForced && { force: true }), + }; for (const edit of batch) { edit.status = "saving"; edit.message = undefined; - edit.conflict = undefined; } - const request: MatrixSaveRequest = { - changes: batch.map(changeOf), - ...(force && { force: true }), - }; let response: MatrixSaveResponse; try { response = (await options.send(request)) ?? {}; @@ -172,81 +230,99 @@ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { return false; } options.onResponse?.(response); - return settle(batch, indexAnswer(response)); + const isWritten = settle(batch, request.changes, indexAnswer(response)); + // A value committed during the write goes now, from the value written. + if (options.mode() === "immediate") void flush(); + return isWritten; } /** A request that failed as a whole: every change keeps its draft. */ function failAll(batch: MatrixEdit[], message: BlockText): void { - for (const edit of batch) { - if (edits.get(matrixCellKey(edit.rowId, edit.columnId)) !== edit) - continue; - edit.status = "failed"; - edit.message = message; - } + for (const edit of batch) markFailed(edit, { message }); } - function settle(batch: MatrixEdit[], answer: AnswerIndex): boolean { + /** A value committed during a write that failed becomes the draft. */ + function takeQueued(edit: MatrixEdit): void { + if (!edit.queued) return; + edit.after = edit.queued.value; + edit.queued = undefined; + } + + function settle( + batch: MatrixEdit[], + changes: MatrixChange[], + answer: AnswerIndex, + ): boolean { const saved: MatrixChange[] = []; - let failures = 0; - for (const edit of batch) { - const outcome = settleEdit(edit, answer); - if (outcome === "failed") failures++; - if (outcome === "saved") saved.push(changeOf(edit)); - } + batch.forEach((edit, index) => { + if (settleEdit(edit, answer) === "saved") + saved.push(changes[index] as MatrixChange); + }); if (saved.length) { lastSaved.value = saved; + options.onWritten?.(unreturned(answer, saved)); options.onSaved?.(saved); } - return failures === 0; + return saved.length === batch.length; } - function settleEdit( - edit: MatrixEdit, - answer: AnswerIndex, - ): "saved" | "failed" { - const key = matrixCellKey(edit.rowId, edit.columnId); + function settleEdit(edit: MatrixEdit, answer: AnswerIndex): EditOutcome { + const key = keyOf(edit); const conflict = answer.conflicts.get(key); const message = answer.cellErrors.get(key) ?? answer.rowErrors.get(edit.rowId); if (conflict) { options.onConflict?.(conflict); - // The stored value is what an Overwrite now replaces. - markFailed(edit, key, { conflict: { current: conflict.current } }); + markFailed(edit, { conflict: { current: conflict.current } }); return "failed"; } if (message !== undefined) { if (answer.rowErrors.has(edit.rowId)) rowErrors.set(edit.rowId, message); - markFailed(edit, key, { message }); + markFailed(edit, { message }); return "failed"; } rowErrors.delete(edit.rowId); - const current = edits.get(key); - if (current === edit) { - edits.delete(key); + if (isCurrent(edit)) settleWritten(edit, key); + return "saved"; + } + + /** A written edit: gone, or followed by the value committed meanwhile. */ + function settleWritten(edit: MatrixEdit, key: string): void { + edits.delete(key); + const queued = edit.queued; + if (!queued || isSameValue(queued.value, edit.after)) { flashSaved(key); - } else if (current) { - // Edited again while this write ran: the next write starts from it. - current.before = edit.after; + return; } - return "saved"; + edits.set(key, { + rowId: edit.rowId, + columnId: edit.columnId, + before: edit.after, + after: queued.value, + status: "pending", + }); } function markFailed( edit: MatrixEdit, - key: string, failure: Pick, ): void { - if (edits.get(key) !== edit) return; + if (!isCurrent(edit)) return; + takeQueued(edit); edit.status = "failed"; edit.message = failure.message; - edit.conflict = failure.conflict; - if (failure.conflict) edit.before = failure.conflict.current; + // The edit keeps the value it started from; the stored one is apart. + edit.conflict = failure.conflict ?? edit.conflict; } /** Writes the immediate edits held so far, unless a target holds them. */ function flush(): Promise { if (options.isBlocked()) return Promise.resolve(false); - return send(list.value.filter((edit) => edit.status === "pending")); + return send( + list.value.filter( + (edit) => edit.status === "pending" && isSendable(edit), + ), + ); } /** @@ -267,60 +343,75 @@ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { function record(change: MatrixCommit): void { const key = matrixCellKey(change.rowId, change.columnId); const existing = edits.get(key); - const before = existing ? existing.before : change.original; touchedRows.add(change.rowId); - if (isSameValue(change.value, before)) { - if (existing && existing.status !== "saving") edits.delete(key); + if (existing?.status === "saving") { + existing.queued = { value: change.value }; + return; + } + const before = existing ? existing.before : change.original; + if (isSameValue(change.value, before) && !existing?.conflict) { + if (existing) edits.delete(key); return; } + // Edited again, a conflicting cell stays one until Overwrite or Discard. + const conflict = existing?.conflict; edits.set(key, { rowId: change.rowId, columnId: change.columnId, before, after: change.value, - status: "pending", + status: conflict ? "failed" : "pending", + ...(conflict && { conflict }), }); } - /** Writes every edit not being written (the save bar, Ctrl+S). */ + /** Writes every edit that may go (the save bar, Ctrl+S); conflicts wait. */ function saveAll(): Promise { if (options.isBlocked()) return Promise.resolve(false); - return send(list.value.filter(waiting)); + return send(list.value.filter(isSendable)); } /** Writes one failed cell again. */ function retry(rowId: string, columnId: string): Promise { const edit = editOf(rowId, columnId); - if (!edit || edit.status === "saving") return Promise.resolve(false); - if (options.isBlocked()) return Promise.resolve(false); + if (!edit || !isSendable(edit) || options.isBlocked()) + return Promise.resolve(false); return send([edit]); } /** Writes a conflicting cell over the value stored meanwhile. */ function overwrite(rowId: string, columnId: string): Promise { const edit = editOf(rowId, columnId); - if (!edit || edit.status === "saving") return Promise.resolve(false); + if (!edit || edit.status === "saving" || options.isBlocked()) + return Promise.resolve(false); return send([edit], true); } /** Drops a cell's edit: it shows what the server holds. */ function discard(rowId: string, columnId: string): void { const key = matrixCellKey(rowId, columnId); - if (edits.get(key)?.status === "saving") return; + const edit = edits.get(key); + if (!edit) return; + // A write in flight cannot be called back; what was committed after it can. + if (edit.status === "saving") { + edit.queued = undefined; + return; + } edits.delete(key); } /** Drops every edit not being written. */ function discardAll(): void { for (const [key, edit] of edits) { - if (waiting(edit)) edits.delete(key); + if (edit.status === "saving") edit.queued = undefined; + else edits.delete(key); } rowErrors.clear(); } /** * Writes back the values the last save replaced (its `previous`), as the - * Undo of its toast. Resolves whether the route took them. + * Undo of its toast. Resolves whether the route took them all. */ async function undo(changes: MatrixChange[]): Promise { if (!changes.length) return true; @@ -332,19 +423,19 @@ export function createMatrixSaveEngine(options: MatrixSaveEngineOptions) { previous: change.value, })), }; + let response: MatrixSaveResponse; try { - const response = (await options.send(request)) ?? {}; - options.onResponse?.(response); - const answer = indexAnswer(response); - return ( - answer.cellErrors.size + - answer.rowErrors.size + - answer.conflicts.size === - 0 - ); + response = (await options.send(request)) ?? {}; } catch { return false; } + options.onResponse?.(response); + const answer = indexAnswer(response); + const written = request.changes.filter( + (change) => !isRefused(answer, change), + ); + options.onWritten?.(unreturned(answer, written)); + return written.length === request.changes.length; } const count: ComputedRef = computed(() => edits.size); diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSections.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSections.ts index da657b26d..720aa90d8 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSections.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixSections.ts @@ -80,13 +80,15 @@ export function buildMatrixSections( /** * The groups that start folded: the ones the response says so, or every - * group once the grid holds more than `collapseAbove` rows. + * group once the grid holds more than `collapseAbove` rows. None when + * `collapsible` is `false`: a folded group could never be opened. */ export function initiallyCollapsed( sections: MatrixSection[], grouping: MatrixGrouping | undefined, rowCount: number, ): string[] { + if (grouping?.collapsible === false) return []; const isLarge = grouping?.collapseAbove !== undefined && rowCount > grouping.collapseAbove; return sections diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTones.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTones.ts index 2c572a3dd..879e1de16 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTones.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTones.ts @@ -3,7 +3,7 @@ import type { MatrixAlign, MatrixTone } from "../../../types/matrix"; /** * The tint each tone lays on a cell or a row, a DMS token in both themes. * Laid as a background image over the cell's own colour (see - * `MATRIX_TINT_CLASS`), so a sticky cell stays opaque under its tint. + * `cellBackground`), so a sticky cell stays opaque under its tint. */ export const MATRIX_TONE_TINTS: Record = { neutral: "var(--dms-neutral-tint)", @@ -34,23 +34,34 @@ export const MATRIX_TONE_BAR: Record = { info: "shadow-[inset_2px_0_0_0_var(--ui-info)]", }; -/** Paints `--dms-matrix-tint` over the cell's background. */ -export const MATRIX_TINT_CLASS = - "bg-[image:linear-gradient(var(--dms-matrix-tint),var(--dms-matrix-tint))]"; - -/** The diagonal hatching of a disabled cell (and of its legend swatch). */ -export const MATRIX_HATCH_CLASS = - "bg-[image:repeating-linear-gradient(-45deg,var(--ui-border-accented)_0_1px,transparent_1px_7px)]"; - export const MATRIX_ALIGN_CLASSES: Record = { start: "justify-start text-start", center: "justify-center text-center", end: "justify-end text-end", }; -/** The style giving a cell a tint, or none. */ -export function tintStyle( - tint: string | undefined, +/** The diagonal hatching of a disabled cell (and of its legend swatch). */ +const HATCH_IMAGE = + "repeating-linear-gradient(-45deg, var(--ui-border-accented) 0 1px, transparent 1px 7px)"; + +/** What is painted over a cell's own background. */ +export interface MatrixCellPaint { + /** A tone's tint (`MATRIX_TONE_TINTS`). */ + tint?: string; + /** Hatched, as a disabled cell. */ + isHatched?: boolean; +} + +/** + * The style painting a cell: its hatching and its tint laid as background + * images over its own colour, both at once, so a sticky cell stays opaque. + */ +export function cellBackground( + paint: MatrixCellPaint, ): Record | undefined { - return tint ? { "--dms-matrix-tint": tint } : undefined; + const layers = [ + paint.isHatched ? HATCH_IMAGE : "", + paint.tint ? `linear-gradient(${paint.tint}, ${paint.tint})` : "", + ].filter(Boolean); + return layers.length ? { backgroundImage: layers.join(", ") } : undefined; } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTotals.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTotals.ts index 7532ed4fc..d3eb6f07a 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTotals.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixTotals.ts @@ -17,16 +17,14 @@ export interface MatrixTotalsResult { /** The columns a row total adds up: numbers, minus the excluded ones. */ export function totalledColumns(columns: MatrixColumn[]): MatrixColumn[] { - return columns.filter( - (column) => kindOf(column) === "number" && !column.excludeFromTotals, - ); + return columns.filter(isTotalledColumn); } /** - * Row totals, column totals and the grand total. A row total adds the - * totalled columns; a column total adds every row's cell of a number column - * (an excluded column still has its own footer); the grand total adds the - * row totals, so it matches the Total column. + * Row totals, column totals and the grand total, over the totalled columns + * only: a column left out of the totals (an annex, a price, a rate) is part + * of no total, not even its own footer. The grand total adds the row + * totals, so it matches the Total column. */ export function computeMatrixTotals( rows: MatrixRow[], @@ -34,15 +32,14 @@ export function computeMatrixTotals( valueOf: MatrixCellValueOf, ): MatrixTotalsResult { const counted = totalledColumns(columns); - const numberColumns = columns.filter((column) => kindOf(column) === "number"); const result: MatrixTotalsResult = { rows: {}, columns: {}, total: 0 }; - for (const column of numberColumns) result.columns[column.id] = 0; + for (const column of counted) result.columns[column.id] = 0; for (const row of rows) { let rowTotal = 0; - for (const column of numberColumns) { + for (const column of counted) { const value = numericValue(valueOf(row, column.id)); result.columns[column.id] = (result.columns[column.id] ?? 0) + value; - if (counted.includes(column)) rowTotal += value; + rowTotal += value; } result.rows[row.id] = rowTotal; result.total += rowTotal; @@ -50,6 +47,24 @@ export function computeMatrixTotals( return result; } +/** Whether a column has a sum in the Total row and the group subtotals. */ +export function isTotalledColumn(column: MatrixColumn): boolean { + return kindOf(column) === "number" && !column.excludeFromTotals; +} + +/** + * Where the Total column is drawn among the columns shown: after the last + * column it adds up, so the columns left out of the totals (annexes) stay + * at its right. At the end when no column is added up. + */ +export function totalColumnIndex(columns: MatrixColumn[]): number { + let last = -1; + columns.forEach((column, index) => { + if (isTotalledColumn(column)) last = index; + }); + return last < 0 ? columns.length : last + 1; +} + /** Totals that differ from their target. */ export interface MatrixTargetMisses { rows: Set; diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixUrlState.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixUrlState.ts index dd8725ff6..ff222dcbe 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixUrlState.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixUrlState.ts @@ -1,5 +1,10 @@ import { + columnFilterParam, + columnFilterText, + columnOfFilterParam, facetParam, + parseColumnFilter, + type MatrixColumnFilter, type MatrixQueryState, type MatrixSortDirection, } from "./matrixQuery"; @@ -9,7 +14,9 @@ import { * component id (`stock.page=3`, `stock.facet_store=ENT,WEB`): two grids on a * page never read each other's keys, and none collides with the page's own * query (`{{query.X}}` of a `fetchUrl`). A value at its default is left out. - * The page is written from 1, as a person reads it. + * The page is written from 1, as a person reads it; a column filter as + * `.filter_=:`; the row a drawer has open as + * `.row=` (`rowPanel.deepLink`). */ const URL_KEYS = { page: "page", @@ -18,6 +25,7 @@ const URL_KEYS = { status: "status", sort: "sort", direction: "dir", + row: "row", } as const; const FACET_SEPARATOR = ","; @@ -63,6 +71,7 @@ export function readMatrixUrlState( if (value) facets[id] = value.split(FACET_SEPARATOR).filter(Boolean); } return { + filters: readColumnFilters(query, componentId, defaults.filters), page: page ? page - 1 : defaults.page, pageSize: pageSize ?? defaults.pageSize, search: read(URL_KEYS.search) ?? defaults.search, @@ -78,6 +87,35 @@ export function readMatrixUrlState( }; } +function readColumnFilters( + query: Record, + componentId: string, + defaults: Record, +): Record { + const prefix = matrixUrlKey(componentId, ""); + const filters = { ...defaults }; + for (const [key, value] of Object.entries(query)) { + if (!key.startsWith(prefix)) continue; + const columnId = columnOfFilterParam(key.slice(prefix.length)); + const filter = parseColumnFilter(firstValue(value) ?? ""); + if (columnId && filter) filters[columnId] = filter; + } + return filters; +} + +/** The URL key of the row a grid's drawer has open. */ +export function matrixRowUrlKey(componentId: string): string { + return matrixUrlKey(componentId, URL_KEYS.row); +} + +/** The row the URL says the grid's drawer has open. */ +export function readMatrixUrlRow( + query: Record, + componentId: string, +): string | undefined { + return firstValue(query[matrixRowUrlKey(componentId)]) || undefined; +} + /** * The URL keys of the state, each with its value or `undefined` to remove * it (at its default). Facets the grid offers are always listed, so one @@ -88,6 +126,8 @@ export function matrixUrlEntries( state: MatrixQueryState, defaults: MatrixQueryState, facetIds: string[], + /** The filters of the state written before, to remove the ones gone. */ + previousFilters?: Record, ): Record { const key = (name: string) => matrixUrlKey(componentId, name); const unlessDefault = (value: T, fallback: T, text: string) => @@ -118,6 +158,17 @@ export function matrixUrlEntries( ? values.join(FACET_SEPARATOR) : undefined; } + // A filter removed must leave the URL: the ones written before are listed. + const filtered = new Set([ + ...Object.keys(previousFilters ?? {}), + ...Object.keys(state.filters), + ]); + for (const columnId of filtered) { + const filter = state.filters[columnId]; + entries[key(columnFilterParam(columnId))] = filter?.value + ? columnFilterText(filter) + : undefined; + } return entries; } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixValues.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixValues.ts index 6fe22f24a..10bd7391a 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixValues.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/matrixValues.ts @@ -10,8 +10,11 @@ const DEFAULT_KIND: MatrixCellKind = "text"; const LINE_BREAK = "\n"; /** Typed in a nullable text cell, it empties the cell. */ export const NULL_DRAFT = "null"; -/** Typed in a text cell, it writes the word "null" itself. */ -export const ESCAPED_NULL_DRAFT = "\\null"; +// In a nullable text cell the text "null" itself is typed escaped, `\null` +// (and `\\null` for `\null`): an editor opens such a text with one more +// backslash, and reading a draft takes one away. +const NULL_LIKE_TEXT = /^\\*null$/; +const ESCAPED_NULL = /^\\+null$/; const NO_INDENT = 0; const JSON_INDENT = 2; @@ -57,6 +60,14 @@ export function valueText(value: unknown): string { return String(value); } +/** Stands for no value where one is listed (a "was", a review line). */ +export const EMPTY_MARK = "—"; + +/** A value on one line, or the empty mark for none. */ +export function shownValueText(value: unknown): string { + return isEmptyValue(value) ? EMPTY_MARK : valueText(value); +} + /** The text an editor opens with for a value. */ export function draftTextOf(value: unknown, kind: MatrixCellKind): string { if (value === null || value === undefined) return ""; @@ -65,13 +76,21 @@ export function draftTextOf(value: unknown, kind: MatrixCellKind): string { } /** - * The value a typed text stands for: `null` empties a nullable cell, and - * `\null` writes the word itself. + * The value a typed text stands for. In a nullable cell `null` empties it, + * and a backslash before it writes the text (`\null` → "null"). */ export function parseTextDraft(draft: string, nullable?: boolean): unknown { - if (draft === ESCAPED_NULL_DRAFT) return NULL_DRAFT; - if (nullable && draft.trim() === NULL_DRAFT) return null; - return draft; + if (!nullable) return draft; + if (draft.trim() === NULL_DRAFT) return null; + return ESCAPED_NULL.test(draft) ? draft.slice(1) : draft; +} + +/** The text a cell's editor opens with: see the escape above. */ +export function textDraftOf(value: unknown, nullable?: boolean): string { + const text = valueText(value); + return nullable && typeof value === "string" && NULL_LIKE_TEXT.test(value) + ? `\\${text}` + : text; } /** A finite number, or `undefined` for a draft that is none. */ @@ -110,7 +129,8 @@ export type MatrixInvalidReason = | "number" | "min" | "max" - | "json"; + | "json" + | "datetime"; type ValueCheck = ( column: MatrixColumn, @@ -163,12 +183,40 @@ const EDIT_IN_PANEL: Record< (TEXT_KINDS.has(kind) && isLongText(value)), }; +/** Kinds whose value is written as text: an object there is no text. */ +const STRING_KINDS: ReadonlySet = new Set([ + "text", + "longText", + "code", +]); + /** - * Whether a cell is edited in a drawer rather than in place: `editIn`, or by - * default its kind (json, code...) and, for a text, its value. + * The column a cell is edited as: its own, or `json` for an object or a list + * found in a text column, so it is never written back as a JSON string. */ -export function editsInPanel(column: MatrixColumn, value: unknown): boolean { - return EDIT_IN_PANEL[column.editIn ?? "auto"](kindOf(column), value); +export function editingColumnOf( + column: MatrixColumn, + value: unknown, +): MatrixColumn { + if (!STRING_KINDS.has(kindOf(column)) || !isStructuredValue(value)) + return column; + return { ...column, kind: "json" }; +} + +/** + * Whether a cell is edited in a drawer rather than in place: the cell's + * `editIn`, else the column's, else (`auto`) by its kind (json, code...) and + * for a text by its value (long, on several lines). An object in a text + * column always goes to the drawer, edited as JSON. + */ +export function editsInPanel( + column: MatrixColumn, + value: unknown, + cellEditIn?: MatrixEditIn, +): boolean { + if (editingColumnOf(column, value) !== column) return true; + const editIn = cellEditIn ?? column.editIn ?? "auto"; + return EDIT_IN_PANEL[editIn](kindOf(column), value); } /** The kinds a typed character may start editing (as a spreadsheet does). */ @@ -190,13 +238,22 @@ export function numericValue(value: unknown): number { return Number.isFinite(parsed) ? parsed : 0; } -const asString = (value: unknown): string => - isStructuredValue(value) ? JSON.stringify(value) : valueText(value); +const pad = (value: number) => String(value).padStart(2, "0"); + +/** A date and time as a `datetime-local` input takes it, in local time. */ +export function datetimeInputOf(value: unknown): string { + if (isEmptyValue(value)) return ""; + const date = new Date(value as string | number); + if (Number.isNaN(date.getTime())) return ""; + const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; + return `${day}T${pad(date.getHours())}:${pad(date.getMinutes())}`; +} const EDITOR_MODELS: Partial< Record unknown> > = { json: (value) => draftTextOf(value, "json"), + datetime: datetimeInputOf, number: (value) => parseNumberDraft(value) ?? null, boolean: (value) => value === true, tags: (value) => (Array.isArray(value) ? value.map(String) : []), @@ -213,13 +270,25 @@ const EDITOR_MODELS: Partial< */ export function editorModelOf(column: MatrixColumn, value: unknown): unknown { const toModel = EDITOR_MODELS[kindOf(column)]; - return toModel ? toModel(value) : asString(value); + return toModel ? toModel(value) : textDraftOf(value, column.nullable); +} + +/** A value the column takes. */ +export interface EditorValueAccepted { + ok: true; + value: unknown; +} + +/** A model the column refuses, and why. */ +export interface EditorValueRefused { + ok: false; + reason: MatrixInvalidReason; + /** The parser's own words (a JSON syntax error). */ + detail?: string; } /** The value an editor's model stands for, or why the column refuses it. */ -export type EditorValueResult = - | { ok: true; value: unknown } - | { ok: false; reason: MatrixInvalidReason; detail?: string }; +export type EditorValueResult = EditorValueAccepted | EditorValueRefused; type ModelReader = (column: MatrixColumn, model: unknown) => EditorValueResult; @@ -249,6 +318,13 @@ const MODEL_READERS: Partial> = { }, select: (_column, model) => ({ ok: true, value: model ?? null }), date: (_column, model) => ({ ok: true, value: model || null }), + datetime: (_column, model) => { + if (!model) return { ok: true, value: null }; + const date = new Date(String(model)); + return Number.isNaN(date.getTime()) + ? { ok: false, reason: "datetime" } + : { ok: true, value: date.toISOString() }; + }, }; /** diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrix.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrix.ts index c32b6272c..f157facee 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrix.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrix.ts @@ -1,8 +1,8 @@ import { computed, - h, inject, markRaw, + onMounted, provide, ref, watch, @@ -10,15 +10,14 @@ import { type InjectionKey, type Ref, } from "vue"; -import { useEventListener } from "@vueuse/core"; import { useComposedText } from "#dms-core/app/composables/translation/useComposedText"; import type { BlockText } from "#dms-core/app/types/composed-text"; import type { MatrixCellState, - MatrixChange, MatrixColumn, MatrixOptions, MatrixRow, + MatrixRowAction, MatrixSaveRequest, MatrixSaveResponse, MatrixTargets, @@ -26,9 +25,6 @@ import type { import { resolveUrlVariables } from "../../utils/urlVariables"; import { resolveActionError } from "../confirm/actionError"; import { useActionTargets } from "../actions/useActionTargets"; -import { useUnsavedChanges } from "../../../composables/unsaved-changes/useUnsavedChanges"; -import { useConfirm } from "../../../composables/confirm/useConfirm"; -import MatrixReviewList from "../../components/matrix/MatrixReviewList.vue"; import { createMatrixSaveEngine, type MatrixSaveEngine, @@ -61,6 +57,13 @@ import { import { useMatrixRows, type MatrixRowsControls } from "./useMatrixRows"; import { useMatrixTools } from "./useMatrixTools"; import { matrixFilterParams } from "./matrixQuery"; +import { useMatrixSaving } from "./useMatrixSaving"; +import { useMatrixSelection, type MatrixSelection } from "./useMatrixSelection"; +import { + matrixRowUrlKey, + readMatrixUrlRow, + writeMatrixUrlEntries, +} from "./matrixUrlState"; /** Everything the grid's parts read and call, provided by the block. */ export interface MatrixContext { @@ -75,6 +78,8 @@ export interface MatrixContext { rows: MatrixRowsControls; engine: MatrixSaveEngine; interaction: MatrixInteraction; + /** Where the keyboard enters the grid while no cell has the focus. */ + entryCell: ComputedRef; /** Editing is on: a `saveUrl`, and `editable` not turned off. */ canEdit: ComputedRef; totals: ComputedRef; @@ -96,6 +101,10 @@ export interface MatrixContext { openRowPanel: (rowId: string) => void; openCellDrawer: (address: MatrixCellAddress, editing?: MatrixEditing) => void; hasRowPanel: ComputedRef; + /** The rows checked in a `selectable` grid. */ + selection: MatrixSelection; + /** Runs an action of a row's header menu. */ + runRowAction: (action: MatrixRowAction, row: MatrixRow) => void; /** The save bar and Ctrl+S: the review first when `review` is on. */ requestSave: () => Promise; tools: ReturnType; @@ -109,9 +118,6 @@ export function useMatrixContext(): MatrixContext { return context; } -const MS_PER_SECOND = 1000; -const SAVE_KEY = "s"; - /** What the block hands `useMatrix`: its options and where it stands. */ export interface MatrixSetup extends MatrixOptions { componentId: string; @@ -128,6 +134,9 @@ function useSaveRequest( routeParams: () => Record | undefined, listQuery: () => Record, ) { + // The block's mode goes with every save: a generic route reads it to know + // whether to check each change's `previous`. + const conflicts = options.conflicts ?? "overwrite"; const { $authFetch } = useAuthFetch(); const route = useDmsRoute(); return async ( @@ -140,7 +149,7 @@ function useSaveRequest( if (!url) throw new Error("dms.matrix.save_unresolved"); return $authFetch(url, { method: (options.saveUrlMethod ?? "POST") as "POST", - body: { ...request, query: listQuery() }, + body: { ...request, conflicts, query: listQuery() }, }); }; } @@ -159,7 +168,6 @@ export function useMatrix( const options = props; const { t } = useI18n(); const { processText } = useComposedText(); - const toast = useToast(); const root = ref(null); const text = (value: BlockText | undefined) => value === undefined || value === "" ? "" : processText(value); @@ -194,9 +202,16 @@ export function useMatrix( ), isBlocked: () => isBlockedNow(), onResponse: (response) => source.applySaveResponse(response), + onWritten: (values) => source.patchValues(values), onConflict: (conflict) => - source.patchValue(conflict.rowId, conflict.columnId, conflict.current), - onSaved: (changes) => offerUndo(changes), + source.patchValues([ + { + rowId: conflict.rowId, + columnId: conflict.columnId, + value: conflict.current, + }, + ]), + onSaved: (changes) => saving.offerUndo(changes), describeError: (error) => resolveActionError(error, t, (field) => { const column = columns.columnById.value.get(field); @@ -210,6 +225,9 @@ export function useMatrix( groupOf: (row) => fieldGroupOf(row), stateKey: `dms-matrix-folds:${props.pageId}:${props.componentId}`, keepEditedRows: () => options.keepEditedRows === true, + // Pages are not filters: a row edited on another page stays there. + pageKey: () => + options.pagination === "pages" ? String(query.state.value.page) : "", touched: engine.touchedRows, hasEdit: (rowId) => engine.edits.value.some((edit) => edit.rowId === rowId), }); @@ -274,6 +292,12 @@ export function useMatrix( handleApiError: (error, title) => useApiError(error, { title }), rowIdKey: "id", }); + const runRowAction = (action: MatrixRowAction, row: MatrixRow) => + handleCustomRowAction( + { label: text(action.label), icon: action.icon, target: action.target }, + { ...row.values, id: row.id }, + ); + // An empty cell has nothing to act on: it is not clickable. const hasCellAction = (row: MatrixRow, column: MatrixColumn) => Boolean(options.cellAction) && !cellState(row, column.id).disabled && @@ -322,6 +346,34 @@ export function useMatrix( onClosed: (address) => { if (address) interaction.focusCell(address); }, + onRowShown: (rowId) => { + if (isRowDeepLinked) + writeMatrixUrlEntries({ [matrixRowUrlKey(props.componentId)]: rowId }); + }, + }); + + // `rowPanel.deepLink`: the open row is in the URL, and opened again once + // the rows are there. + const isRowDeepLinked = + typeof options.rowPanel === "object" && options.rowPanel.deepLink === true; + let linkedRow = isRowDeepLinked + ? readMatrixUrlRow( + useDmsRoute().query as Record, + props.componentId, + ) + : undefined; + onMounted(() => { + if (!linkedRow) return; + watch( + () => rows.rowById.value, + (byId) => { + if (!linkedRow || !byId.has(linkedRow)) return; + const rowId = linkedRow; + linkedRow = undefined; + drawers.openRowPanel(rowId); + }, + { immediate: true }, + ); }); const interaction = useMatrixInteraction({ @@ -341,108 +393,25 @@ export function useMatrix( openRowPanel: drawers.openRowPanel, hasRowPanel: () => hasRowPanel.value, expandGroupOf: rows.expandGroupOf, + cellEditIn: (row, columnId) => cellState(row, columnId).editIn, }); - // --- saving: review, undo, leave guard, Ctrl+S --- - const { confirm } = useConfirm(); - const undoToastId = `dms-matrix-undo-${props.componentId}`; - - function offerUndo(changes: MatrixChange[]): void { - const seconds = options.undoSeconds ?? 0; - if (seconds <= 0) return; - toast.remove(undoToastId); - toast.add({ - id: undoToastId, - title: t( - "dms.matrix.saved_toast", - { count: changes.length }, - changes.length, - ), - color: "success", - icon: "i-ph-check-circle", - duration: seconds * MS_PER_SECOND, - actions: [ - { - label: t("dms.matrix.undo"), - icon: "i-ph-arrow-counter-clockwise", - color: "neutral", - variant: "outline", - onClick: () => void undo(changes), - }, - ], - }); - } - - async function undo(changes: MatrixChange[]): Promise { - const isUndone = await engine.undo(changes); - toast.add({ - title: isUndone ? t("dms.matrix.undone") : t("dms.matrix.undo_failed"), - color: isUndone ? "neutral" : "error", - icon: isUndone ? "i-ph-arrow-counter-clockwise" : "i-ph-warning-circle", - }); - } - - async function saveNow(): Promise { - const isSaved = await engine.saveAll(); - if (isSaved || isBlocked.value) return; - toast.add({ - title: t( - "dms.matrix.not_saved_toast", - { count: engine.failedCount.value }, - engine.failedCount.value, - ), - color: "error", - icon: "i-ph-warning-circle", - }); - } - - async function requestSave(): Promise { - if (!engine.count.value || engine.isSaving.value) return; - if (isBlocked.value) { - toast.add({ - title: t("dms.matrix.blocked"), - description: targetMessage.value ?? undefined, - color: "warning", - icon: "i-ph-scales", - }); - return; - } - if (!options.review) return saveNow(); - const changes = engine.edits.value.map((edit) => ({ ...edit })); - await confirm({ - title: t( - "dms.matrix.review.title", - { count: changes.length }, - changes.length, - ), - description: t("dms.matrix.review.description"), - confirmLabel: t( - "dms.matrix.save_label", - { count: changes.length }, - changes.length, - ), - cancelLabel: t("dms.matrix.review.back"), - icon: "i-ph-list-checks", - color: "primary", - body: () => - h(MatrixReviewList, { changes, context: context as MatrixContext }), - onConfirm: () => saveNow(), - }); - } - - useUnsavedChanges({ dirty: () => engine.hasUnsaved.value }); + const entryCell = computed(() => { + const row = rows.shown.value[0]; + const column = columns.visible.value[0]; + return row && column ? { rowId: row.id, columnId: column.id } : null; + }); - useEventListener( - typeof window === "undefined" ? undefined : window, - "keydown", - (event: KeyboardEvent) => { - if (event.key.toLowerCase() !== SAVE_KEY) return; - if (!(event.ctrlKey || event.metaKey) || event.altKey) return; - if (options.saveMode !== "staged" || !engine.count.value) return; - event.preventDefault(); - void requestSave(); - }, - ); + const saving = useMatrixSaving({ + options, + engine, + isBlocked, + targetMessage, + root, + commitEditor: () => interaction.commitOpenEditor(), + context: () => context as MatrixContext, + }); + const selection = useMatrixSelection(() => rows.shown.value); const tools = useMatrixTools({ options, @@ -458,6 +427,9 @@ export function useMatrix( totals: () => totals.value, commitMany: (changes) => void engine.commitMany(changes), rowOf: (rowId) => rows.rowById.value.get(rowId), + columnOf: (columnId) => columns.columnById.value.get(columnId), + isEditable, + selected: () => (options.selectable ? selection.ids.value : undefined), labelOfValue: (column, value) => optionLabel(column, value, text), }); @@ -475,6 +447,7 @@ export function useMatrix( rows, engine, interaction, + entryCell, canEdit, totals, sectionTotals, @@ -492,7 +465,9 @@ export function useMatrix( openRowPanel: drawers.openRowPanel, openCellDrawer: drawers.openCellDrawer, hasRowPanel, - requestSave, + selection, + runRowAction, + requestSave: saving.requestSave, tools, }); provide(MATRIX_CONTEXT, context); diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixColumns.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixColumns.ts index 6142fda29..e3c4f7273 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixColumns.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixColumns.ts @@ -23,7 +23,10 @@ export interface MatrixColumnsControls { isHidden: (column: MatrixColumn) => boolean; toggle: (columnId: string) => void; move: (columnId: string, step: number) => void; + /** A width dragged to: on screen at once, remembered by `saveWidths`. */ resize: (columnId: string, width: number) => void; + /** Remembers the widths on the device, once a drag ends. */ + saveWidths: () => void; reset: () => void; } @@ -92,13 +95,16 @@ export function useMatrixColumns( }, move: (columnId, step) => update({ order: moveColumnOrder(columns.value, columnId, step) }), - resize: (columnId, width) => - update({ + resize: (columnId, width) => { + preferences.value = { + ...preferences.value, widths: { ...preferences.value.widths, [columnId]: clampColumnWidth(width), }, - }), + }; + }, + saveWidths: () => writePreferences(storageKey, preferences.value), reset: () => update({ order: [], hidden: {}, widths: {} }), }; } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixData.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixData.ts index aab454543..d17822d95 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixData.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixData.ts @@ -19,6 +19,7 @@ import type { MatrixRow, MatrixSaveResponse, } from "../../../types/matrix"; +import type { MatrixWrittenValue } from "./matrixSaveEngine"; import { applyStaticQuery, buildMatrixQuery, @@ -38,10 +39,13 @@ export interface MatrixDataSource { isLoadingMore: ComputedRef; refresh: () => Promise; loadMore: () => Promise; - /** Puts what a save answered on screen: its rows, counts and targets. */ + /** + * Puts what a save answered on screen: its rows in place, and its counts, + * targets, columns, groups and footer over the read's until the next read. + */ applySaveResponse: (response: MatrixSaveResponse) => void; - /** Shows the value a conflict says is stored. */ - patchValue: (rowId: string, columnId: string, value: unknown) => void; + /** Shows values the server now holds (a conflict's, a write no row returned). */ + patchValues: (values: MatrixWrittenValue[]) => void; } export interface MatrixDataOptions { @@ -58,48 +62,119 @@ function replaceRows(rows: MatrixRow[], answered: MatrixRow[]): MatrixRow[] { return rows.map((row) => byId.get(row.id) ?? row); } -function withValue( +function withValues( rows: MatrixRow[], - rowId: string, - columnId: string, - value: unknown, + values: MatrixWrittenValue[], ): MatrixRow[] { - return rows.map((row) => - row.id === rowId - ? { ...row, values: { ...row.values, [columnId]: value } } - : row, - ); + if (!values.length) return rows; + const byRow = new Map(); + for (const value of values) { + byRow.set(value.rowId, [...(byRow.get(value.rowId) ?? []), value]); + } + return rows.map((row) => { + const written = byRow.get(row.id); + if (!written) return row; + const patched = { ...row.values }; + for (const value of written) patched[value.columnId] = value.value; + return { ...row, values: patched }; + }); } -/** An answer with a save's rows, counts and targets laid over it. */ -export function withSaveResponse( - data: MatrixData, +/** What a save answered over the read: kept apart, until the next read. */ +export type MatrixAnswerOverrides = Pick< + MatrixData, + "counts" | "targets" | "columns" | "groups" | "footer" +>; + +/** The overrides after a save's answer: each part it holds replaces its own. */ +export function answerOverridesOf( + previous: MatrixAnswerOverrides, response: MatrixSaveResponse, +): MatrixAnswerOverrides { + return { + ...previous, + ...(response.counts && { + counts: { ...previous.counts, ...response.counts }, + }), + ...(response.targets && { targets: response.targets }), + ...(response.columns && { columns: response.columns }), + ...(response.groups && { groups: response.groups }), + ...(response.footer !== undefined && { footer: response.footer }), + }; +} + +/** A read with a save's answer laid over it. */ +export function withAnswerOverrides( + data: MatrixData, + overrides: MatrixAnswerOverrides, ): MatrixData { return { ...data, - rows: replaceRows(data.rows, response.rows ?? []), - ...(response.counts && { counts: { ...data.counts, ...response.counts } }), - ...(response.targets && { targets: response.targets }), + ...overrides, + ...((data.counts || overrides.counts) && { + counts: { ...data.counts, ...overrides.counts }, + }), }; } -/** The data a source edits in place: a ref it can read and replace. */ -type EditableData = Ref; +/** Where a source keeps its rows: the read, and how to rewrite them. */ +interface MatrixRowStore { + read: ComputedRef; + writeRows: (rewrite: (rows: MatrixRow[]) => MatrixRow[]) => void; +} + +/** The parts of a source that put a save's answer on screen. */ +type MatrixAnswerParts = Pick< + MatrixDataSource, + "data" | "applySaveResponse" | "patchValues" +>; -function editors( - data: EditableData, -): Pick { +/** + * The data shown: the read with the last save's answer over it. Rows are + * rewritten where the read keeps them (a page among the infinite pages); the + * rest of an answer is kept apart, so a later page read cannot drop it, and + * goes with the next read of the query. + */ +function useAnswerOverrides(store: MatrixRowStore): MatrixAnswerParts { + const overrides = shallowRef({}); + let isWriting = false; + watch( + store.read, + () => { + if (!isWriting) overrides.value = {}; + }, + { flush: "sync" }, + ); + const writeRows = (rewrite: (rows: MatrixRow[]) => MatrixRow[]) => { + isWriting = true; + try { + store.writeRows(rewrite); + } finally { + isWriting = false; + } + }; return { + data: computed(() => + store.read.value + ? withAnswerOverrides(store.read.value, overrides.value) + : null, + ), applySaveResponse: (response) => { - if (data.value) data.value = withSaveResponse(data.value, response); + overrides.value = answerOverridesOf(overrides.value, response); + if (response.rows?.length) + writeRows((rows) => replaceRows(rows, response.rows ?? [])); }, - patchValue: (rowId, columnId, value) => { - if (!data.value) return; - data.value = { - ...data.value, - rows: withValue(data.value.rows, rowId, columnId, value), - }; + patchValues: (values) => writeRows((rows) => withValues(rows, values)), + }; +} + +/** The rows of a data ref, rewritten in place. */ +function refRowStore(data: Ref): MatrixRowStore { + return { + read: computed(() => data.value), + writeRows: (rewrite) => { + if (data.value) + data.value = { ...data.value, rows: rewrite(data.value.rows) }; }, }; } @@ -146,21 +221,20 @@ function usePagedMatrixData(source: MatrixDataOptions): MatrixDataSource { const refresh = () => loaded.refresh(); useRefreshTriggers(options.realtimeTopic, refresh); return { - data: computed(() => loaded.data.value), isLoading: computed(() => loaded.status.value === "pending"), error: loaded.error, hasMore: computed(() => false), isLoadingMore: computed(() => false), refresh, loadMore: async () => {}, - ...editors(loaded.data), + ...useAnswerOverrides(refRowStore(loaded.data)), }; } const KEY_PREFIX = "dms-matrix"; -/** The rows read so far, from the first page on. */ -function mergePages(pages: MatrixData[]): MatrixData | null { +/** The rows read so far, from the first page on; the rest from the last page read. */ +export function mergePages(pages: MatrixData[]): MatrixData | null { const [first] = pages; if (!first) return null; const last = pages.at(-1) ?? first; @@ -207,26 +281,22 @@ function useInfiniteMatrixData(source: MatrixDataOptions): MatrixDataSource { ); const refresh = () => paged.refresh(); useRefreshTriggers(options.realtimeTopic, refresh); - const data = computed(() => mergePages(paged.pages.value)); - // Edits go into the page that holds the row. - const editable = computed({ - get: () => data.value, - set: (next) => { + // Rows are rewritten in the page that holds them. + const store: MatrixRowStore = { + read: computed(() => mergePages(paged.pages.value)), + writeRows: (rewrite) => { const value = paged.data.value; - if (!next || !value) return; - const byId = new Map(next.rows.map((row) => [row.id, row])); + if (!value) return; paged.data.value = { ...value, - pages: value.pages.map((page, index) => ({ + pages: value.pages.map((page) => ({ ...page, - ...(index === 0 && { counts: next.counts, targets: next.targets }), - rows: page.rows.map((row) => byId.get(row.id) ?? row), + rows: rewrite(page.rows), })), }; }, - }); + }; return { - data, isLoading: computed( () => paged.status.value === "pending" && !paged.loadingMore.value, ), @@ -235,7 +305,7 @@ function useInfiniteMatrixData(source: MatrixDataOptions): MatrixDataSource { isLoadingMore: computed(() => paged.loadingMore.value), refresh, loadMore: () => paged.loadMore(), - ...editors(editable), + ...useAnswerOverrides(store), }; } @@ -267,13 +337,16 @@ function useStaticMatrixData(source: MatrixDataOptions): MatrixDataSource { ) : null, ); - const data = computed(() => { - const value = queried.value; - if (!value || pagination !== "infinite") return value; - return { ...value, rows: value.rows.slice(0, revealed.value) }; - }); + const store: MatrixRowStore = { + read: computed(() => { + const value = queried.value; + if (!value || pagination !== "infinite") return value; + return { ...value, rows: value.rows.slice(0, revealed.value) }; + }), + // The static rows themselves: the query reads them again as they change. + writeRows: refRowStore(local).writeRows, + }; return { - data, isLoading: computed(() => false), error: ref(null), hasMore: computed( @@ -286,6 +359,6 @@ function useStaticMatrixData(source: MatrixDataOptions): MatrixDataSource { loadMore: async () => { revealed.value += query.value.pageSize; }, - ...editors(local), + ...useAnswerOverrides(store), }; } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixDrawers.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixDrawers.ts index 618c5c084..deec14a74 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixDrawers.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixDrawers.ts @@ -20,6 +20,8 @@ export interface MatrixDrawersOptions { panelTitle: () => BlockText | undefined; /** Gives the keyboard back to the grid's cell once a drawer closes. */ onClosed: (address?: MatrixCellAddress) => void; + /** The row the row drawer shows, as it opens and steps; none once closed. */ + onRowShown?: (rowId?: string) => void; } const ROW_POSITION_KEY = "$dms.matrix.drawer.row_position"; @@ -90,12 +92,15 @@ export function useMatrixDrawers(options: MatrixDrawersOptions) { function showRow(index: number): void { const row = options.shownRows()[index]; - if (row && rowDrawer) rowDrawer.patch(rowDrawerOptions(row)); + if (!row || !rowDrawer) return; + rowDrawer.patch(rowDrawerOptions(row)); + options.onRowShown?.(row.id); } function openRowPanel(rowId: string): void { const row = options.rowOf(rowId); if (!row) return; + options.onRowShown?.(row.id); if (rowDrawer) { rowDrawer.patch(rowDrawerOptions(row)); return; @@ -108,6 +113,7 @@ export function useMatrixDrawers(options: MatrixDrawersOptions) { }); rowDrawer.result.finally(() => { rowDrawer = null; + options.onRowShown?.(); options.onClosed(); }); } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixInteraction.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixInteraction.ts index 98c6c61f1..f42610432 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixInteraction.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixInteraction.ts @@ -1,6 +1,7 @@ import { computed, nextTick, ref, type Ref } from "vue"; import type { MatrixColumn, + MatrixEditIn, MatrixEnterMove, MatrixOptions, MatrixRow, @@ -14,7 +15,12 @@ import { type MatrixCellAddress, type MatrixGridShape, } from "./matrixNavigation"; -import { acceptsTypedStart, editsInPanel, isEmptyValue } from "./matrixValues"; +import { + acceptsTypedStart, + editsInPanel, + isEmptyValue, + kindOf, +} from "./matrixValues"; /** The cell being edited in place, and the text it was started with. */ export interface MatrixEditing extends MatrixCellAddress { @@ -48,11 +54,41 @@ export interface MatrixInteractionOptions { openRowPanel: (rowId: string) => void; hasRowPanel: () => boolean; expandGroupOf: (rowId: string) => void; + /** A cell's own `editIn`, over its column's. */ + cellEditIn: (row: MatrixRow, columnId: string) => MatrixEditIn | undefined; } const CELL_SELECTOR = "[data-matrix-cell]"; +const JUMP_KEY_CODE = "KeyN"; +const JUMP_KEYS: ReadonlySet = new Set(["n", "N"]); type KeyHandler = (event: KeyboardEvent, focus: MatrixCellAddress) => boolean; +/** A step through the cells: `1` to the next, `-1` to the previous. */ +export type MatrixJumpStep = 1 | -1; + +/** + * The step a key asks of `jumpToEmpty`: N and Shift+N, or, when a typed + * letter starts editing (`typeToEdit`), Alt+N and Alt+Shift+N, read from the + * key's position since Alt+N types another character on a Mac. + */ +export function jumpStepOf( + event: KeyboardEvent, + hasTypeToEdit: boolean, +): MatrixJumpStep | null { + if (event.ctrlKey || event.metaKey) return null; + const isJump = hasTypeToEdit + ? event.altKey && event.code === JUMP_KEY_CODE + : !event.altKey && JUMP_KEYS.has(event.key); + if (!isJump) return null; + return event.shiftKey ? -1 : 1; +} + +/** A key pressed on a cell itself, not on a button inside the grid. */ +function isOnCell(event: KeyboardEvent): boolean { + const target = event.target as Element | null; + return typeof target?.matches === "function" && target.matches(CELL_SELECTOR); +} + /** * The grid's keyboard and pointer: one focused cell moved with the arrows, * Home / End and PageUp / PageDown; Enter (or the edit trigger) edits it in @@ -66,6 +102,8 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { const editing = ref(null); const hover = ref(null); const editTrigger = computed(() => options.editTrigger ?? "doubleClick"); + /** The in-place editor's commit, while one is open (Ctrl+S runs it first). */ + let openEditorCommit: (() => void) | null = null; function cellElement(address: MatrixCellAddress): HTMLElement | null { const cells = @@ -107,18 +145,21 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { } const hasDraft = draft !== undefined; const value = hasDraft ? draft : source.valueOf(row, column.id); - if (column.kind === "boolean") { + if (kindOf(column) === "boolean") { source.commitValue(row, column, !source.valueOf(row, column.id)); return; } const entry: MatrixEditing = { ...address, draft, hasDraft }; - if (editsInPanel(column, value)) { + if (inPanel(row, column, value)) { source.openCellDrawer(address, entry); return; } editing.value = entry; } + const inPanel = (row: MatrixRow, column: MatrixColumn, value: unknown) => + editsInPanel(column, value, source.cellEditIn(row, column.id)); + function stopEditing(): void { const current = editing.value; editing.value = null; @@ -161,14 +202,16 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { function continueEditing(address: MatrixCellAddress): void { const cell = resolve(address); - if (!cell || cell.column.kind === "boolean") return; - if (editsInPanel(cell.column, source.valueOf(cell.row, cell.column.id))) + if (!cell || kindOf(cell.column) === "boolean") return; + if ( + inPanel(cell.row, cell.column, source.valueOf(cell.row, cell.column.id)) + ) return; editing.value = { ...address, hasDraft: false }; } /** N: the next empty cell the user can fill, groups expanded on the way. */ - function jumpToEmpty(step: 1 | -1): void { + function jumpToEmpty(step: MatrixJumpStep): void { const target = findMatrixCell( source.allShape(), focus.value, @@ -206,14 +249,16 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { focus.value = null; return true; }, - n: (event) => { - if (!options.jumpToEmpty) return false; - jumpToEmpty(event.shiftKey ? -1 : 1); - return true; - }, - N: (event) => KEY_HANDLERS.n!(event, focus.value as MatrixCellAddress), }; + function jump(event: KeyboardEvent): boolean { + if (!options.jumpToEmpty) return false; + const step = jumpStepOf(event, options.typeToEdit === true); + if (!step) return false; + jumpToEmpty(step); + return true; + } + function typeToEdit(event: KeyboardEvent, current: MatrixCellAddress) { if (!options.typeToEdit || !isTypedCharacter(event)) return false; const cell = resolve(current); @@ -223,9 +268,12 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { return true; } - /** The grid's keydown, while no cell is being edited. */ + /** + * The grid's keydown, while no cell is being edited: only a key pressed on + * a cell, a button inside the grid (Retry, a fold, a sort) keeps its own. + */ function onKeydown(event: KeyboardEvent): void { - if (editing.value || event.defaultPrevented) return; + if (editing.value || event.defaultPrevented || !isOnCell(event)) return; const current = focus.value ?? null; if (isMatrixMoveKey(event.key)) { event.preventDefault(); @@ -234,6 +282,10 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { return; } if (!current) return; + if (jump(event)) { + event.preventDefault(); + return; + } if (event.ctrlKey || event.metaKey || event.altKey) return; const handler = KEY_HANDLERS[event.key]; const handled = @@ -268,6 +320,14 @@ export function useMatrixInteraction(source: MatrixInteractionOptions) { focus, editing, hover, + /** The editor open in place hands its commit over while it is open. */ + registerEditor: (commit: () => void) => { + openEditorCommit = commit; + return () => { + if (openEditorCommit === commit) openEditorCommit = null; + }; + }, + commitOpenEditor: () => openEditorCommit?.(), focusCell, startEdit, stopEditing, diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixQueryState.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixQueryState.ts index 33fc487dd..14f880f3c 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixQueryState.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixQueryState.ts @@ -4,6 +4,7 @@ import { DEFAULT_MATRIX_PAGE_SIZE, emptyMatrixQuery, nextMatrixSort, + type MatrixColumnFilter, type MatrixQueryState, } from "./matrixQuery"; import { @@ -22,6 +23,12 @@ export interface MatrixQueryControls { setStatus: (status: string) => void; setFacet: (facetId: string, values: string[]) => void; toggleSort: (columnId: string) => void; + /** A column's header filter; `null` removes it. */ + setColumnFilter: ( + columnId: string, + filter: MatrixColumnFilter | null, + ) => void; + clearColumnFilters: () => void; clearFilters: () => void; } @@ -50,15 +57,19 @@ export function useMatrixQueryState( : defaults; const state = ref(initial); - if (keepsUrl) + if (keepsUrl) { + let written = state.value.filters; watch( state, - (next) => + (next) => { writeMatrixUrlEntries( - matrixUrlEntries(componentId, next, defaults, facetIds), - ), + matrixUrlEntries(componentId, next, defaults, facetIds, written), + ); + written = next.filters; + }, { deep: true }, ); + } const refine = (patch: Partial) => { state.value = { ...state.value, ...patch, page: 0 }; @@ -69,7 +80,8 @@ export function useMatrixQueryState( isFiltered: () => Boolean(state.value.search.trim()) || Boolean(state.value.status) || - Object.values(state.value.facets).some((values) => values.length > 0), + Object.values(state.value.facets).some((values) => values.length > 0) || + Object.keys(state.value.filters).length > 0, setPage: (page) => { state.value = { ...state.value, page: Math.max(0, page) }; }, @@ -83,6 +95,14 @@ export function useMatrixQueryState( refine({ facets: { ...state.value.facets, [facetId]: values } }), toggleSort: (columnId) => refine({ sort: nextMatrixSort(state.value.sort, columnId) }), - clearFilters: () => refine({ search: "", status: "", facets: {} }), + setColumnFilter: (columnId, filter) => { + const filters = { ...state.value.filters }; + if (filter?.value) filters[columnId] = filter; + else Reflect.deleteProperty(filters, columnId); + refine({ filters }); + }, + clearColumnFilters: () => refine({ filters: {} }), + clearFilters: () => + refine({ search: "", status: "", facets: {}, filters: {} }), }; } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixRows.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixRows.ts index e3066c958..36f069b95 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixRows.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixRows.ts @@ -40,6 +40,11 @@ export interface MatrixRowsOptions { /** Where the folds are kept while the page stays open. */ stateKey: string; keepEditedRows: () => boolean; + /** + * The page the rows are read on (`pagination: "pages"`): a row kept is + * only kept on the page it was edited on, a page change is no filter. + */ + pageKey: () => string; /** Rows edited in this view (the save engine's). */ touched: Set; /** A row still holding an edit, never let go. */ @@ -52,19 +57,41 @@ interface MatrixFoldState { seen: string[]; } -/** The rows a touched row is remembered by: as last read. */ +/** A row edited in this view, as last read, and the page it was read on. */ +export interface MatrixKeptRow { + row: MatrixRow; + pageKey: string; +} + +/** + * The kept rows drawn though the read no longer lists them: the ones edited + * on the page shown (a filter or a search dropped them), never the rows of + * another page. + */ +export function keptRowIds( + kept: ReadonlyMap, + answeredIds: ReadonlySet, + pageKey: string, +): string[] { + return [...kept.entries()] + .filter(([id, entry]) => !answeredIds.has(id) && entry.pageKey === pageKey) + .map(([id]) => id); +} + +/** The rows a touched row is remembered by: as last read, on its page. */ function useKeptRows( options: MatrixRowsOptions, answered: ComputedRef, ) { - const kept: Ref> = shallowRef(new Map()); + const kept: Ref> = shallowRef(new Map()); watch( [answered, () => options.touched.size], ([rows]) => { if (!options.keepEditedRows()) return; const next = new Map(kept.value); + const pageKey = options.pageKey(); for (const row of rows) { - if (options.touched.has(row.id)) next.set(row.id, row); + if (options.touched.has(row.id)) next.set(row.id, { row, pageKey }); } kept.value = next; }, @@ -74,18 +101,15 @@ function useKeptRows( () => new Set(answered.value.map((row) => row.id)), ); const keptIds = computed( - () => - new Set( - [...kept.value.keys()].filter((id) => !answeredIds.value.has(id)), - ), + () => new Set(keptRowIds(kept.value, answeredIds.value, options.pageKey())), ); const keptRows = computed(() => - [...keptIds.value].map((id) => kept.value.get(id) as MatrixRow), + [...keptIds.value].map((id) => (kept.value.get(id) as MatrixKeptRow).row), ); const hideKept = () => { - const next = new Map(); - for (const [id, row] of kept.value) { - if (options.hasEdit(id)) next.set(id, row); + const next = new Map(); + for (const [id, entry] of kept.value) { + if (options.hasEdit(id)) next.set(id, entry); else options.touched.delete(id); } kept.value = next; diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSaving.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSaving.ts new file mode 100644 index 000000000..373a7f245 --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSaving.ts @@ -0,0 +1,155 @@ +import { h, type ComputedRef, type Ref } from "vue"; +import { useEventListener } from "@vueuse/core"; +import type { MatrixChange, MatrixOptions } from "../../../types/matrix"; +import { useUnsavedChanges } from "../../../composables/unsaved-changes/useUnsavedChanges"; +import { useConfirm } from "../../../composables/confirm/useConfirm"; +import MatrixReviewList from "../../components/matrix/MatrixReviewList.vue"; +import type { MatrixSaveEngine } from "./matrixSaveEngine"; +import type { MatrixContext } from "./useMatrix"; + +const MS_PER_SECOND = 1000; +const SAVE_KEY = "s"; +const BLOCK_SELECTOR = "[data-dms-matrix]"; + +export interface MatrixSavingOptions { + options: MatrixOptions; + engine: MatrixSaveEngine; + isBlocked: ComputedRef; + targetMessage: ComputedRef; + /** The grid's own element, inside the block's. */ + root: Ref; + /** Commits the cell being edited in place, if any. */ + commitEditor: () => void; + context: () => MatrixContext; +} + +/** + * Whether a keyboard shortcut is this block's: the focus is inside it, or + * nowhere in another Matrix and it is the page's only one. + */ +export function ownsShortcut(block: Element | null | undefined): boolean { + const active = document.activeElement?.closest(BLOCK_SELECTOR); + if (active) return active === block; + return document.querySelectorAll(BLOCK_SELECTOR).length === 1; +} + +/** + * The saving around the engine: the save bar and Ctrl+S (the review first + * with `review`, refused while a `blockSave` target is missed), the Undo + * toast after a save, and the guard on leaving with unsaved edits. + */ +export function useMatrixSaving(saving: MatrixSavingOptions) { + const { options, engine, isBlocked } = saving; + const { t } = useI18n(); + const toast = useToast(); + const { confirm } = useConfirm(); + // Each save's toast has an id of its own: Nuxt UI drops every toast of an + // id a moment after `remove(id)`, a new one of that id included. + let undoToastId: string | number | null = null; + + function offerUndo(changes: MatrixChange[]): void { + const seconds = options.undoSeconds ?? 0; + if (seconds <= 0) return; + if (undoToastId !== null) toast.remove(undoToastId); + undoToastId = toast.add({ + title: t( + "dms.matrix.saved_toast", + { count: changes.length }, + changes.length, + ), + color: "success", + icon: "i-ph-check-circle", + duration: seconds * MS_PER_SECOND, + actions: [ + { + label: t("dms.matrix.undo"), + icon: "i-ph-arrow-counter-clockwise", + color: "neutral", + variant: "outline", + onClick: () => void undo(changes), + }, + ], + }).id; + } + + async function undo(changes: MatrixChange[]): Promise { + const isUndone = await engine.undo(changes); + toast.add({ + title: isUndone ? t("dms.matrix.undone") : t("dms.matrix.undo_failed"), + color: isUndone ? "neutral" : "error", + icon: isUndone ? "i-ph-arrow-counter-clockwise" : "i-ph-warning-circle", + }); + } + + async function saveNow(): Promise { + const isSaved = await engine.saveAll(); + if (isSaved || isBlocked.value) return; + toast.add({ + title: t( + "dms.matrix.not_saved_toast", + { count: engine.failedCount.value }, + engine.failedCount.value, + ), + color: "error", + icon: "i-ph-warning-circle", + }); + } + + function warnBlocked(): void { + toast.add({ + title: t("dms.matrix.blocked"), + description: saving.targetMessage.value ?? undefined, + color: "warning", + icon: "i-ph-scales", + }); + } + + /** The save bar and Ctrl+S: the review first when `review` is on. */ + async function requestSave(): Promise { + if (!engine.count.value || engine.isSaving.value) return; + if (isBlocked.value) return warnBlocked(); + if (!options.review) return saveNow(); + const changes = engine.edits.value + .filter((edit) => !edit.conflict) + .map((edit) => ({ ...edit })); + await confirm({ + title: t( + "dms.matrix.review.title", + { count: changes.length }, + changes.length, + ), + description: t("dms.matrix.review.description"), + confirmLabel: t( + "dms.matrix.save_label", + { count: changes.length }, + changes.length, + ), + cancelLabel: t("dms.matrix.review.back"), + icon: "i-ph-list-checks", + color: "primary", + body: () => h(MatrixReviewList, { changes, context: saving.context() }), + onConfirm: () => saveNow(), + }); + } + + useUnsavedChanges({ dirty: () => engine.hasUnsaved.value }); + + // Ctrl / ⌘ S saves this grid's staged edits, the cell being typed in + // first, when the shortcut is the grid's (see `ownsShortcut`). + useEventListener( + typeof window === "undefined" ? undefined : window, + "keydown", + (event: KeyboardEvent) => { + if (event.key.toLowerCase() !== SAVE_KEY) return; + if (!(event.ctrlKey || event.metaKey) || event.altKey) return; + if (options.saveMode !== "staged") return; + const block = saving.root.value?.closest(BLOCK_SELECTOR); + if (!ownsShortcut(block)) return; + event.preventDefault(); + saving.commitEditor(); + void requestSave(); + }, + ); + + return { offerUndo, requestSave }; +} diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSelection.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSelection.ts new file mode 100644 index 000000000..b47d57fda --- /dev/null +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixSelection.ts @@ -0,0 +1,48 @@ +import { computed, reactive, type ComputedRef } from "vue"; +import type { MatrixRow } from "../../../types/matrix"; + +/** The header checkbox: every row shown checked, some, or none. */ +export type MatrixSelectAllState = boolean | "indeterminate"; + +export interface MatrixSelection { + /** The checked row ids, in no particular order. */ + ids: ComputedRef; + isSelected: (rowId: string) => boolean; + toggle: (rowId: string) => void; + /** Checks every row shown, or unchecks them when they all are. */ + toggleAll: () => void; + allState: ComputedRef; + clear: () => void; +} + +/** + * The rows checked in a `selectable` grid: a checkbox per row and one in the + * header for the rows shown. The fills receive the checked ids (`selected`). + */ +export function useMatrixSelection(rows: () => MatrixRow[]): MatrixSelection { + const selected = reactive(new Set()); + const shownIds = () => rows().map((row) => row.id); + const allState = computed(() => { + const ids = shownIds(); + const checked = ids.filter((id) => selected.has(id)).length; + if (checked === 0) return false; + return checked === ids.length ? true : "indeterminate"; + }); + return { + ids: computed(() => [...selected]), + isSelected: (rowId) => selected.has(rowId), + toggle: (rowId) => { + if (selected.has(rowId)) selected.delete(rowId); + else selected.add(rowId); + }, + toggleAll: () => { + const isAll = allState.value === true; + for (const id of shownIds()) { + if (isAll) selected.delete(id); + else selected.add(id); + } + }, + allState, + clear: () => selected.clear(), + }; +} diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixTools.ts b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixTools.ts index b30c1f4b4..c82971a63 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixTools.ts +++ b/packages/dms/frontend-vue/layers/dms-ui/app/build/composables/matrix/useMatrixTools.ts @@ -3,6 +3,7 @@ import type { BlockText } from "#dms-core/app/types/composed-text"; import type { MatrixColumn, MatrixFillAction, + MatrixFillChange, MatrixFillResponse, MatrixOptions, MatrixRow, @@ -30,6 +31,11 @@ export interface MatrixToolsOptions { totals: () => MatrixTotalsResult; commitMany: (changes: MatrixCommit[]) => void; rowOf: (rowId: string) => MatrixRow | undefined; + columnOf: (columnId: string) => MatrixColumn | undefined; + /** A fill sets only the cells the user could edit. */ + isEditable: (row: MatrixRow, column: MatrixColumn) => boolean; + /** The checked rows of a `selectable` grid, posted to the fills. */ + selected: () => string[] | undefined; /** A select's value as its option reads. */ labelOfValue: (column: MatrixColumn, value: unknown) => string | undefined; } @@ -74,6 +80,7 @@ export function useMatrixTools(tools: MatrixToolsOptions) { rows: tools .rows() .map((row) => shownRow(row, columnIds, tools.valueOf)), + ...(tools.selected() && { selected: tools.selected() }), }, }); applyFill(response?.changes ?? []); @@ -84,12 +91,15 @@ export function useMatrixTools(tools: MatrixToolsOptions) { } } - function applyFill(changes: NonNullable) { + // A change on a cell the user cannot edit is left out, and an answered + // `previous` ignored: the edit starts from the value on screen. + function applyFill(changes: MatrixFillChange[]) { const commits: MatrixCommit[] = []; - for (const change of changes) { - const row = tools.rowOf(change.rowId); - if (!row) continue; - commits.push({ ...change, original: row.values[change.columnId] }); + for (const { rowId, columnId, value } of changes) { + const row = tools.rowOf(rowId); + const column = tools.columnOf(columnId); + if (!row || !column || !tools.isEditable(row, column)) continue; + commits.push({ rowId, columnId, value, original: row.values[columnId] }); } if (commits.length) tools.commitMany(commits); } diff --git a/packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/MatrixBlock.vue b/packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/MatrixBlock.vue index 1be35298e..45c715eca 100644 --- a/packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/MatrixBlock.vue +++ b/packages/dms/frontend-vue/layers/dms-ui/app/components/blocks/MatrixBlock.vue @@ -9,10 +9,8 @@ import MatrixToolbar from "../../build/components/matrix/MatrixToolbar.vue"; import { useMatrix } from "../../build/composables/matrix/useMatrix"; import { clampPage } from "../../build/composables/matrix/matrixQuery"; import { - MATRIX_HATCH_CLASS, - MATRIX_TINT_CLASS, + cellBackground, MATRIX_TONE_TINTS, - tintStyle, } from "../../build/composables/matrix/matrixTones"; import { readFetchNotFound } from "../../build/utils/fetchNotFound"; import { useComponentEvent } from "../../../../dms-core/app/composables/components/useComponentEvent"; @@ -41,6 +39,8 @@ const props = withDefaults(defineProps(), { jumpToEmpty: undefined, keepEditedRows: undefined, exportCsv: undefined, + selectable: undefined, + columnFilters: undefined, }); useComponentEvent(props.componentId); @@ -196,12 +196,11 @@ const legend = computed(() => props.legend ?? []); >