diff --git a/.changeset/36370-kanban-view-settings.md b/.changeset/36370-kanban-view-settings.md new file mode 100644 index 00000000000..9abc244082c --- /dev/null +++ b/.changeset/36370-kanban-view-settings.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-kanban': minor +'@object-ui/plugin-list': minor +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +'@object-ui/plugin-view': minor +'@objectstack/lint': minor +--- + +feat(kanban): the board's own 视图设置, a lane header 「+」 and 「⋯」, and a lane statistic and card toggles on `KanbanConfig` + +Clause-②: yes (widening) +Metadata-protocol: added + +`KanbanConfigSchema` gains three optional keys, none with a default; a view that declares none of them renders as before: + +- `summary` — a lane statistic drawn at the foot of each lane (`KanbanLaneSummary`): `{ type: 'count' }`, or `{ type: 'sum', field }` of a number field over the cards the lane has loaded, not every record of the lane; `{ type: 'none' }` shows nothing. It takes precedence over `summarizeField`. A sum over a lane holding more cards than were loaded says so (「仅已加载的卡片」). The whole-lane sum, and average, minimum and maximum, wait for a server lane read (#36520). +- `showFieldLabels` — absent means `true`: a card names each field beside its value; `false` draws the values alone. +- `hideEmptyFields` — absent means `true`: a card leaves out an empty field; `false` keeps its line. + +On a board, the view settings show the lane field, which lanes show and in what order, the card fields (order, hide, add), the two card toggles and the lane-foot statistic, in place of the table's columns, group, row height and row colour. Each change applies at once and is held as the list's draft until Save. Each lane header gets 「+」 (a new record with the lane prefilled; an empty lane also gets a 「+ New」 row) and 「⋯」 (collapse, kept in this browser; hide). Hiding a lane moves its cards into 「未分类」, as `kanban.lanes` (#28211) always has, and the menu and the lanes list say so. The lane field picker offers select and radio fields; collapse is kept per reader, object and view. The Console now relays the view's `kanban.lanes`, which it used to drop, and both producers of the board node (`ListView` and `ObjectView#generateViewSchema`) relay the three new keys. `ObjectKanban` takes the host's `laneMenu` request (`KanbanLaneMenuRequest`). `@objectstack/lint` walks `kanban.summary.field` and refuses a `sum` over a field that is no number, a yes / no field included (`list-view-summary-field-type-refused`). Saving a board whose view declares no `kanban` block stores the lane field the board draws with the changed keys. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 25f7db3cd71..f12f8c0a186 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1997,7 +1997,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -2077,7 +2077,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 00d97ec787b..3677d64a4e3 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -411,7 +411,7 @@ const result = ApiMethod.parse(data); | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 2e98af49095..e21f7d0c705 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1713 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1714 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -33,8 +33,8 @@ counts are sums of the rows they head. Regenerate with | [Shared Protocol](/docs/references/shared) | 10 | 31 | Primitives used across every protocol — identifiers, HTTP, expressions, error maps, enums. | | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | -| [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1713** | 14 protocol modules | +| [UI Protocol](/docs/references/ui) | 16 | 181 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | +| **Total** | **219** | **1714** | 14 protocol modules | --- @@ -386,7 +386,7 @@ The runtime environment — logging, jobs, cache, metrics, notifications, i18n a ## UI Protocol -**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 180 schemas** +**Source:** `packages/spec/src/ui/` · **Import:** `@objectstack/spec/ui` · **16 pages, 181 schemas** Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. @@ -407,7 +407,7 @@ Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI lay | [`report.zod.ts`](/docs/references/ui/report) | `JoinedReportBlock`, `Report`, `ReportChart`, `ReportSort`, `ReportType` | | [`responsive.zod.ts`](/docs/references/ui/responsive) | `ResponsiveStyles`, `StyleMap` | | [`sharing.zod.ts`](/docs/references/ui/sharing) | `SharingConfig` | -| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | +| [`view.zod.ts`](/docs/references/ui/view) | `AddRecordConfig`, `AppearanceConfig`, `CalendarConfig`, `ColumnPrefix`, `ColumnSummary`, `ColumnSummaryConfig`, `EmptyState`, `FormButtonConfig`, `FormField`, `FormSection`, `FormSelectOption`, `FormView`, `GalleryConfig`, `GanttConfig`, `GanttQuickFilter`, `GroupingConfig`, `GroupingField`, `HttpMethodSubset`, `HttpRequest`, `KanbanConfig`, `KanbanLaneSummary`, `ListChartConfig`, `ListColumn`, `ListMapConfig`, `ListView`, `NavigationConfig`, `NavigationMode`, `ObjectListView`, `ObjectUserFilters`, `PaginationConfig`, `RowColorConfig`, `RowHeight`, `SelectionConfig`, `TimelineConfig`, `TimesheetConfig`, `TreeConfig`, `UserActionsConfig`, `UserFilterField`, `UserFilters`, `View`, `ViewData`, `ViewFilterElement`, `ViewFilterOrGroup`, `ViewFilterRule`, `ViewItem`, `ViewItemName`, `ViewItemWire`, `ViewKind`, `ViewScope`, `ViewSharing`, `ViewTab`, `VisualizationType` | --- diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 4e0379d50c8..0330a617a04 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -59,8 +59,8 @@ nothing. The one item-name grammar itself lives in ## TypeScript Usage ```typescript -import { AddRecordConfigSchema, AppearanceConfigSchema, CalendarConfigSchema, ColumnPrefixSchema, ColumnSummarySchema, ColumnSummaryConfigSchema, EmptyStateSchema, FormButtonConfigSchema, FormFieldSchema, FormSectionSchema, FormSelectOptionSchema, FormViewSchema, GalleryConfigSchema, GanttConfigSchema, GanttQuickFilterSchema, GroupingConfigSchema, GroupingFieldSchema, HttpMethodSubsetSchema, HttpRequestSchema, KanbanConfigSchema, ListChartConfigSchema, ListColumnSchema, ListMapConfigSchema, ListViewSchema, NavigationConfigSchema, NavigationModeSchema, ObjectListViewSchema, ObjectUserFiltersSchema, PaginationConfigSchema, RowColorConfigSchema, RowHeightSchema, SelectionConfigSchema, TimelineConfigSchema, TimesheetConfigSchema, TreeConfigSchema, UserActionsConfigSchema, UserFilterFieldSchema, UserFiltersSchema, ViewSchema, ViewDataSchema, ViewFilterElementSchema, ViewFilterOrGroupSchema, ViewFilterRuleSchema, ViewItemSchema, ViewItemNameSchema, ViewItemWireSchema, ViewKindSchema, ViewScopeSchema, ViewSharingSchema, ViewTabSchema, VisualizationTypeSchema } from '@objectstack/spec/ui'; -import type { AddRecordConfig, AppearanceConfig, CalendarConfig, ColumnPrefix, ColumnSummary, ColumnSummaryConfig, EmptyState, FormButtonConfig, FormField, FormSection, FormSelectOption, FormView, GalleryConfig, GanttConfig, GanttQuickFilter, GroupingConfig, HttpMethodSubset, HttpRequest, KanbanConfig, ListChartConfig, ListColumn, ListMapConfig, ListView, NavigationConfig, NavigationMode, PaginationConfig, RowColorConfig, RowHeight, SelectionConfig, TimelineConfig, TimesheetConfig, TreeConfig, UserActionsConfig, UserFilterField, UserFilters, View, ViewData, ViewFilterElement, ViewFilterOrGroup, ViewFilterRule, ViewItem, ViewItemName, ViewItemWire, ViewKind, ViewScope, ViewSharing, ViewTab, VisualizationType } from '@objectstack/spec/ui'; +import { AddRecordConfigSchema, AppearanceConfigSchema, CalendarConfigSchema, ColumnPrefixSchema, ColumnSummarySchema, ColumnSummaryConfigSchema, EmptyStateSchema, FormButtonConfigSchema, FormFieldSchema, FormSectionSchema, FormSelectOptionSchema, FormViewSchema, GalleryConfigSchema, GanttConfigSchema, GanttQuickFilterSchema, GroupingConfigSchema, GroupingFieldSchema, HttpMethodSubsetSchema, HttpRequestSchema, KanbanConfigSchema, KanbanLaneSummarySchema, ListChartConfigSchema, ListColumnSchema, ListMapConfigSchema, ListViewSchema, NavigationConfigSchema, NavigationModeSchema, ObjectListViewSchema, ObjectUserFiltersSchema, PaginationConfigSchema, RowColorConfigSchema, RowHeightSchema, SelectionConfigSchema, TimelineConfigSchema, TimesheetConfigSchema, TreeConfigSchema, UserActionsConfigSchema, UserFilterFieldSchema, UserFiltersSchema, ViewSchema, ViewDataSchema, ViewFilterElementSchema, ViewFilterOrGroupSchema, ViewFilterRuleSchema, ViewItemSchema, ViewItemNameSchema, ViewItemWireSchema, ViewKindSchema, ViewScopeSchema, ViewSharingSchema, ViewTabSchema, VisualizationTypeSchema } from '@objectstack/spec/ui'; +import type { AddRecordConfig, AppearanceConfig, CalendarConfig, ColumnPrefix, ColumnSummary, ColumnSummaryConfig, EmptyState, FormButtonConfig, FormField, FormSection, FormSelectOption, FormView, GalleryConfig, GanttConfig, GanttQuickFilter, GroupingConfig, HttpMethodSubset, HttpRequest, KanbanConfig, KanbanLaneSummary, ListChartConfig, ListColumn, ListMapConfig, ListView, NavigationConfig, NavigationMode, PaginationConfig, RowColorConfig, RowHeight, SelectionConfig, TimelineConfig, TimesheetConfig, TreeConfig, UserActionsConfig, UserFilterField, UserFilters, View, ViewData, ViewFilterElement, ViewFilterOrGroup, ViewFilterRule, ViewItem, ViewItemName, ViewItemWire, ViewKind, ViewScope, ViewSharing, ViewTab, VisualizationType } from '@objectstack/spec/ui'; // Validate data const result = AddRecordConfigSchema.parse(data); @@ -689,9 +689,67 @@ HTTP methods a view data source may request — the subset of `HttpMethod` witho | **groupByField** | `string` | ✅ | Field to group columns by (usually status/select). NO leading or trailing whitespace: the board reads this name off every card verbatim, so a padded spelling collapses the whole board into one `Uncategorized` lane. | | **lanes** | `string[]` | optional | The lanes the board draws, in this order: stored option values of the groupByField field (the option `value`, not its label). Omit to draw one lane per option in the options' own order. A record whose value is not listed is not hidden: it lands in the `Uncategorized` lane, as a record whose value matches no lane does. To keep records off the board, filter the view. List each value once. | | **summarizeField** | `string` | optional | Field to sum at top of column (e.g. amount) | +| **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string }` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over the cards the lane has loaded, not every record of the lane (the foot says so when the lane holds more); `{ type: 'none' }` shows nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | +| **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | +| **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | +### Nested Shape: `KanbanConfig.summary[type='sum']` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `'sum'` | ✅ | | +| **field** | `string` | ✅ | The number field the lane totals over its loaded cards (e.g. amount) | + + +--- + +## KanbanLaneSummary + +Lane foot statistic: none, the count of the lane's records, or the sum of a number field over the lane's loaded cards + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +**Type:** `none` + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `'none'` | ✅ | | + +--- + +#### Option 2 + +**Type:** `count` + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `'count'` | ✅ | | + +--- + +#### Option 3 + +**Type:** `sum` + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `'sum'` | ✅ | | +| **field** | `string` | ✅ | The number field the lane totals over its loaded cards (e.g. amount) | + +--- + --- @@ -792,7 +850,7 @@ Map view configuration | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -925,6 +983,9 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **groupByField** | `string` | ✅ | Field to group columns by (usually status/select). NO leading or trailing whitespace: the board reads this name off every card verbatim, so a padded spelling collapses the whole board into one `Uncategorized` lane. | | **lanes** | `string[]` | optional | The lanes the board draws, in this order: stored option values of the groupByField field (the option `value`, not its label). Omit to draw one lane per option in the options' own order. A record whose value is not listed is not hidden: it lands in the `Uncategorized` lane, as a record whose value matches no lane does. To keep records off the board, filter the view. List each value once. | | **summarizeField** | `string` | optional | Field to sum at top of column (e.g. amount) | +| **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string }` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over the cards the lane has loaded, not every record of the lane (the foot says so when the lane holds more); `{ type: 'none' }` shows nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | +| **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | +| **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | @@ -1189,7 +1250,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -1313,6 +1374,9 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **groupByField** | `string` | ✅ | Field to group columns by (usually status/select). NO leading or trailing whitespace: the board reads this name off every card verbatim, so a padded spelling collapses the whole board into one `Uncategorized` lane. | | **lanes** | `string[]` | optional | The lanes the board draws, in this order: stored option values of the groupByField field (the option `value`, not its label). Omit to draw one lane per option in the options' own order. A record whose value is not listed is not hidden: it lands in the `Uncategorized` lane, as a record whose value matches no lane does. To keep records off the board, filter the view. List each value once. | | **summarizeField** | `string` | optional | Field to sum at top of column (e.g. amount) | +| **summary** | `{ type: 'none' } \| { type: 'count' } \| { type: 'sum'; field: string }` | optional | The statistic each lane shows at its foot. `{ type: 'count' }` counts the lane records; `{ type: 'sum', field: 'amount' }` totals a number field over the cards the lane has loaded, not every record of the lane (the foot says so when the lane holds more); `{ type: 'none' }` shows nothing. Takes precedence over summarizeField. Omit to keep summarizeField's sum, or no statistic without it. | +| **showFieldLabels** | `boolean` | optional | Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone. | +| **hideEmptyFields** | `boolean` | optional | Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value. | | **titleField** | `string` | optional | Field displayed as the card title. Omit to fall back to the record display name (ADR-0079 resolver chain) | | **columns** | `string[]` | ✅ | Fields to show on cards | @@ -1793,7 +1857,7 @@ Tab configuration for multi-tab view interface | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -1873,7 +1937,7 @@ Tab configuration for multi-tab view interface | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -2171,7 +2235,7 @@ This schema accepts one of the following structures: | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | @@ -2360,7 +2424,7 @@ This schema accepts one of the following structures: | **selection** | `{ type?: Enum<'none' \| 'single' \| 'multiple'> }` | optional | Row selection configuration | | **navigation** | `{ mode?: Enum<'drawer' \| 'page' \| 'new_window' \| 'none'>; preventNavigation?: boolean; openNewTab?: boolean; size?: Enum<'auto' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'full'>; … }` | optional | Configuration for item click navigation: the drawer size, and `preventNavigation` for a list whose rows open nothing (`mode` is deprecated — the record name opens the page, the hover icon the side panel) | | **pagination** | `{ pageSize?: integer; pageSizeOptions?: integer[] }` | optional | Pagination configuration | -| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; titleField?: string; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | +| **kanban** | `{ groupByField: string; lanes?: string[]; summarizeField?: string; summary?: object \| object \| object; … }` | optional | Kanban-board configuration — applies when the view renders as a kanban layout | | **calendar** | `{ startDateField: string; endDateField?: string; titleField?: string; colorField?: string; … }` | optional | Calendar configuration — applies when the view renders as a calendar layout | | **gantt** | `{ startDateField: string; endDateField: string; titleField: string; progressField?: string; … }` | optional | Gantt-timeline configuration — applies when the view renders as a gantt layout | | **gallery** | `{ coverField?: string; coverFit?: Enum<'cover' \| 'contain'>; cardSize?: Enum<'small' \| 'medium' \| 'large'>; titleField?: string; … }` | optional | Gallery/card view configuration | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md index 206c3ad36ea..91a65b14c1e 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ui.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `ui/` | 224 | 214 | 6 | 0 | 4 | +| `ui/` | 227 | 217 | 6 | 0 | 4 | ## `ui/` — sites @@ -44,9 +44,9 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `report.zod.ts` | 4 | | `responsive.zod.ts` | 1 | | `sharing.zod.ts` | 1 | -| `view.zod.ts` | 59 | +| `view.zod.ts` | 62 | | `widget.zod.ts` | 1 | -| **total** | **224** | +| **total** | **227** | ## `ui/` — open @@ -54,15 +54,15 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**4 strip of 224**, in 4 file(s). +**4 strip of 227**, in 4 file(s). | File | Strip | Sites | |---|---|---| | `action-params.zod.ts` | 1 | 1 | | `app.zod.ts` | 1 | 20 | -| `view.zod.ts` | 1 | 59 | +| `view.zod.ts` | 1 | 62 | | `widget.zod.ts` | 1 | 1 | -| **total** | **4** | **224** | +| **total** | **4** | **227** | | Bucket | Sites | |---|---| diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 5153f4f09e0..056351737f4 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -4328,6 +4328,11 @@ const LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED_EXPLANATION: RuleExplanation = { 'judged the same way, under this id, and refused when the page is saved. The grid is bound by its ' + '`dataSource.object`, else `properties.objectName`; its grouped header numbers come from its ' + '`aggregations` (`grid-aggregation-field-type-refused`), not from the column summaries.', + 'A board\'s lane foot statistic, `kanban.summary`, is judged under this id too: a `sum` totals its ' + + 'field over each lane, so the pair is the table\'s `sum` row over the field\'s declaration, and a ' + + 'refused pair is reported at `kanban.summary`, as is a `sum` over a `boolean` or `toggle` field, which the ' + + 'board does not add. `count` and `none` compare no value. The board totals ' + + 'its loaded cards in the browser today, where a value that is no number draws no figure.', AGGREGATE_PAIR_ROWS, 'The yes / no counts of a boolean column, `count_true` and `count_false`, lower to `SUM(field)` ' + '(booleans aggregate as numbers, so the sum is the number of true cells) and `COUNT(field)`. The ' + diff --git a/packages/lint/src/validate-list-view-field-refs.test.ts b/packages/lint/src/validate-list-view-field-refs.test.ts index d3908c5d1fb..de05f10b429 100644 --- a/packages/lint/src/validate-list-view-field-refs.test.ts +++ b/packages/lint/src/validate-list-view-field-refs.test.ts @@ -103,7 +103,13 @@ const FULL_LIST_VIEW: AnyRec = { fields: [{ field: 'status' }], tabs: [{ name: 'open', filter: [{ field: 'status', operator: 'equals', value: 'open' }] }], }, - kanban: { groupByField: 'status', summarizeField: 'estimate', columns: ['title'], titleField: 'title' }, + kanban: { + groupByField: 'status', + summarizeField: 'estimate', + columns: ['title'], + titleField: 'title', + summary: { type: 'sum', field: 'estimate' }, + }, calendar: { startDateField: 'due_at', endDateField: 'visible_from', @@ -319,6 +325,9 @@ describe('#14107 — every other walked position', () => { ], [{ kanban: { summarizeField: BAD } }, 'views[0].list.kanban.summarizeField', 'warning'], [{ kanban: { columns: [BAD] } }, 'views[0].list.kanban.columns[0]', 'warning'], + // [#36370] The lane foot statistic: a stale name prints a sum of 0 at every + // lane's foot, the `columns[].summary.field` level. + [{ kanban: { summary: { type: 'sum', field: BAD } } }, 'views[0].list.kanban.summary.field', 'error'], // [#18565] Calendar's level, not the required siblings' — see the row's // own note in the rule. The board renders every card; only the title is // not the one the author named. @@ -1695,3 +1704,45 @@ describe('[#32449] a column summary whose function the aggregate door refuses', } }); }); + +/** + * [#36370] `kanban.summary`, the lane foot statistic: `sum` over the field it + * totals is judged by the aggregate × field-type table's `sum` row, the verdict + * `columns[].summary` asks; `count` and `none` compare no value. + */ +describe('[#36370] the lane foot statistic of a board', () => { + const withSummary = (summary: unknown) => + validateListViewFieldRefs(stackWith(mutate({ kanban: { summary } }))).filter( + (f) => f.rule === LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, + ); + + it('refuses a sum over a text field, at `kanban.summary`, with the count as the way out', () => { + const findings = withSummary({ type: 'sum', field: 'title' }); + expect(findings.map((f) => [f.path, f.severity])).toEqual([['views[0].list.kanban.summary', 'error']]); + expect(findings[0].message).toContain('summary "sum" over "title" (`text`) totals no number'); + expect(findings[0].hint).toContain("summary: { type: 'count' }"); + }); + + it('refuses a sum over a formula the same way the column summary does (the field stores no value)', () => { + expect(withSummary({ type: 'sum', field: 'score' })).toHaveLength(1); + }); + + it('refuses a sum over a boolean, which the aggregate table admits but the board does not add', () => { + const findings = withSummary({ type: 'sum', field: 'is_locked' }); + expect(findings).toHaveLength(1); + expect(findings[0].message).toContain('summary "sum" over "is_locked" (`boolean`) totals no number'); + // A toggle is the same true / false class: refused at the same place. + const objects = [{ name: 'duly_task', label: 'Task', fields: [{ name: 'probe', type: 'toggle', label: 'Probe' }] }]; + const toggle = validateListViewFieldRefsUnrecorded( + stackWith({ data: { provider: 'object', object: 'duly_task' }, type: 'kanban', columns: ['probe'], kanban: { groupByField: 'probe', summary: { type: 'sum', field: 'probe' } } }, objects), + ).filter((f) => f.rule === LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED); + expect(toggle.map((f) => [f.path, f.severity])).toEqual([['views[0].list.kanban.summary', 'error']]); + expect(toggle[0].message).toContain('(`toggle`) totals no number'); + }); + + it('accepts a sum over a number, and judges nothing for count or none', () => { + expect(withSummary({ type: 'sum', field: 'estimate' })).toEqual([]); + expect(withSummary({ type: 'count' })).toEqual([]); + expect(withSummary({ type: 'none' })).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-list-view-field-refs.ts b/packages/lint/src/validate-list-view-field-refs.ts index bf8d370efa9..690798aa9de 100644 --- a/packages/lint/src/validate-list-view-field-refs.ts +++ b/packages/lint/src/validate-list-view-field-refs.ts @@ -163,7 +163,7 @@ * through `resolvePath(record, fieldName)`, which walks dots. Excluded. * - **Every renderer binding** (`kanban` / `calendar` / `timeline` / * `gallery` / `map` / `tree` scalars, `rowColor.field`, `hiddenFields`, - * `fieldOrder`, `grouping.fields`, `columns[].summary.field`, + * `fieldOrder`, `grouping.fields`, `columns[].summary.field`, `kanban.summary.field`, * `columns[].prefix.field`). These reach no door this card measured. A * dotted name at one of them is very likely still wrong — the gantt * scalars, for instance, read `record[startDateField]` flat — but "likely @@ -969,6 +969,60 @@ export function columnSummaryRefusal( }; } +/** + * [#36370] The field-naming position inside `kanban.summary`, the lane foot + * statistic. Its own table rather than a `POSITIONS` row: the key lives one + * record further down, as `columns[].summary.field` does. A stale name draws + * nothing: the board finds no such field on the object and every lane's foot + * goes blank, the statistic the author asked for gone without a word. The + * `columns[].summary.field` level, not `summarizeField`'s. + */ +const KANBAN_SUMMARY_POSITIONS: Array<{ key: string; severity: Sev }> = [{ key: 'field', severity: 'error' }]; + +/** + * [#36370] The refusal a `kanban.summary` of type `sum` earns over the field it + * totals on `object`, or `undefined` when nothing is judged or the pair is + * accepted. The same verdict `columns[].summary` asks ({@link columnSummaryRefusal}): + * the aggregate × field-type table's `sum` row over the field's declaration, + * less the true / false class the board does not add. The board totals its loaded cards in the browser today, and a value that is + * no number blanks the lane's foot; the whole lane's figure is the server's + * `sum`, so the pair is judged by the door that will answer it. `count` and + * `none` compare no value. + */ +function kanbanSummaryRefusal( + summary: Record, + graph: ObjectGraph, + object: string, +): { message: string; hint: string } | undefined { + if (summary.type !== 'sum') return undefined; + const field = strName(summary.field); + if (!field || field.includes('.')) return undefined; + const verdict = resolveFieldPath(graph, object, field); + if (!verdict || isUnjudgeable(verdict) || verdict.kind !== 'ok') return undefined; + const fieldType = verdict.meta?.type; + if (!isJudgeableAggregateType(fieldType)) return undefined; + const shape = { type: fieldType, multiple: verdict.meta?.multiple === true }; + // A true / false field the door would sum as a count of trues; the board + // totals numbers only (a `true` reads as no number and blanks the foot), so + // the board's picker leaves the class out and so does this verdict. + const yesNo = fieldType === 'boolean' || fieldType === 'toggle'; + if (!yesNo && aggregateAcceptsDeclaration('sum', shape)) return undefined; + if (yesNo) { + return { + message: + `summary "sum" over "${field}" (${declaredAs(shape)}) totals no number: the board adds number values, ` + + 'and a true / false value draws no figure at the lane\'s foot', + hint: `Total a number field of "${object}", or count each lane's cards with \`summary: { type: 'count' }\`.`, + }; + } + return { + message: + `summary "sum" over "${field}" (${declaredAs(shape)}) totals no number: the aggregate door refuses ` + + 'the pair (400 INVALID_FIELD), and the board\'s own total over its loaded cards draws no figure', + hint: `Total a number field of "${object}", or count each lane's cards with \`summary: { type: 'count' }\`.`, + }; +} + /** The nested field positions inside one `columns[]` entry record. */ const COLUMN_ENTRY_POSITIONS: Array<{ block: string; key: string; severity: Sev }> = [ // `summary` aggregates a column; a stale name aggregates nothing and the @@ -1034,6 +1088,7 @@ export function listViewWalkedPositions(): string[] { ), ...COLUMN_ENTRY_POSITIONS.map(({ block, key }) => `columns.${block}.${key}`), ...GROUPING_ENTRY_POSITIONS.map(({ key }) => `grouping.fields.${key}`), + ...KANBAN_SUMMARY_POSITIONS.map(({ key }) => `kanban.summary.${key}`), ]; } @@ -1568,6 +1623,25 @@ export function validateListViewFieldRefs( checkKanbanLanes(listView, bound, where, path); + // [#36370] The lane foot statistic: the field it names, then the `sum` + // over that field's declaration. + const kanbanSummary = isRec(listView.kanban) ? listView.kanban.summary : undefined; + if (isRec(kanbanSummary)) { + for (const { key, severity } of KANBAN_SUMMARY_POSITIONS) { + check(kanbanSummary[key], bound, severity, `${where} › kanban.summary`, `${path}.kanban.summary.${key}`, `summary.${key}`); + } + const refusal = kanbanSummaryRefusal(kanbanSummary, graph, bound); + if (refusal !== undefined) { + findings.push({ + severity: 'error', + rule: LIST_VIEW_SUMMARY_FIELD_TYPE_REFUSED, + where: `${where} › kanban.summary`, + path: `${path}.kanban.summary`, + ...refusal, + }); + } + } + // ── Filter KEYS: the view's own filter and the tab presets inside // `userFilters`. `walkFilterFieldKeys` handles all three authored filter // shapes (Mongo condition object, `{ field, operator, value }` rules, diff --git a/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index 362baf65595..99e688ee856 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -272,6 +272,9 @@ "KNOWN_COMPONENT_TYPE_CANDIDATES (const)", "KanbanConfig (type)", "KanbanConfigSchema (const)", + "KanbanLaneSummary (type)", + "KanbanLaneSummaryParsed (type)", + "KanbanLaneSummarySchema (const)", "LIST_VIEW_GROUP_COUNT_ALIAS (const)", "ListChartConfig (type)", "ListChartConfigParsed (type)", diff --git a/packages/spec/authorable-surface/ui.json b/packages/spec/authorable-surface/ui.json index 46973fc53a0..a510f9427e9 100644 --- a/packages/spec/authorable-surface/ui.json +++ b/packages/spec/authorable-surface/ui.json @@ -721,8 +721,11 @@ "ui/JoinedReportBlock:values", "ui/KanbanConfig:columns", "ui/KanbanConfig:groupByField", + "ui/KanbanConfig:hideEmptyFields", "ui/KanbanConfig:lanes", + "ui/KanbanConfig:showFieldLabels", "ui/KanbanConfig:summarizeField", + "ui/KanbanConfig:summary", "ui/KanbanConfig:titleField", "ui/ListChartConfig:chartType", "ui/ListChartConfig:dataset", diff --git a/packages/spec/declaration-map/ui.json b/packages/spec/declaration-map/ui.json index 930815ee0f9..bee4d67f93b 100644 --- a/packages/spec/declaration-map/ui.json +++ b/packages/spec/declaration-map/ui.json @@ -171,6 +171,8 @@ "JoinedReportBlockSchema": "ui/JoinedReportBlock", "KanbanConfig": "ui/KanbanConfig", "KanbanConfigSchema": "ui/KanbanConfig", + "KanbanLaneSummary": "ui/KanbanLaneSummary", + "KanbanLaneSummarySchema": "ui/KanbanLaneSummary", "ListChartConfig": "ui/ListChartConfig", "ListChartConfigSchema": "ui/ListChartConfig", "ListColumn": "ui/ListColumn", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 9e99d1d29e7..209f1362aa0 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -266,6 +266,9 @@ "KNOWN_COMPONENT_TYPE_CANDIDATES": "src/ui/component-type-vocabulary.ts#KNOWN_COMPONENT_TYPE_CANDIDATES (const)", "KanbanConfig": "src/ui/view.zod.ts#KanbanConfig (type)", "KanbanConfigSchema": "src/ui/view.zod.ts#KanbanConfigSchema (const)", + "KanbanLaneSummary": "src/ui/view.zod.ts#KanbanLaneSummary (type)", + "KanbanLaneSummaryParsed": "src/ui/view.zod.ts#KanbanLaneSummaryParsed (type)", + "KanbanLaneSummarySchema": "src/ui/view.zod.ts#KanbanLaneSummarySchema (const)", "LIST_VIEW_GROUP_COUNT_ALIAS": "src/ui/view-grouping-query.ts#LIST_VIEW_GROUP_COUNT_ALIAS (const)", "ListChartConfig": "src/ui/view.zod.ts#ListChartConfig (type)", "ListChartConfigParsed": "src/ui/view.zod.ts#ListChartConfigParsed (type)", diff --git a/packages/spec/json-schema.manifest/ui.json b/packages/spec/json-schema.manifest/ui.json index af83edb6c59..49e425745dc 100644 --- a/packages/spec/json-schema.manifest/ui.json +++ b/packages/spec/json-schema.manifest/ui.json @@ -94,6 +94,7 @@ "ui/InterfacePageConfig", "ui/JoinedReportBlock", "ui/KanbanConfig", + "ui/KanbanLaneSummary", "ui/ListChartConfig", "ui/ListColumn", "ui/ListMapConfig", diff --git a/packages/spec/liveness/view.json b/packages/spec/liveness/view.json index b35fe1c3214..3629b6d2a1f 100644 --- a/packages/spec/liveness/view.json +++ b/packages/spec/liveness/view.json @@ -101,7 +101,7 @@ }, "kanban": { "status": "live", - "note": "objectui: KanbanImpl.tsx:682 — field-by-field wired (audit L16). `lanes` (the lanes the board draws, in order, as stored option values of `groupByField`; absent meaning one lane per option) is live: both producers of the `object-kanban` node, ui/packages/plugin-list/src/ListView.tsx (its `case 'kanban'` branch) and ui/packages/plugin-view/src/ObjectView.tsx#generateViewSchema, hand it to the board as the node's `columns` through ui/packages/core/src/utils/kanban-declared-lanes.ts#kanbanDeclaredLanes (the author's order, option labels as titles, a `lost` lane collapsed), and ui/packages/plugin-kanban/src/ObjectKanban.tsx#effectiveColumns draws explicit columns in that order, a record whose value is not listed landing in `Uncategorized` (pinned in ui/packages/plugin-kanban/src/ObjectKanban.declaredLanes-28211.test.tsx). What `groupByField` names, on kanban, gantt and timeline alike (packages/spec/src/ui/view.zod.ts, the padded-spelling refusal; moved out of spec source, #23434): a lookup BY THAT NAME on data the server answers under the unpadded name, at objectui @dda8f3815 packages/plugin-list/src/ListView.tsx#laneField (`groupByField || groupField || detectStatusField(objectDef)`, inside #viewComponentSchema; cards bucketed by `card[laneField]`), objectui @dda8f3815 packages/plugin-gantt/src/ObjectGantt.tsx#groupByAccessor (splits on `.` and walks the record) and objectui @dda8f3815 packages/plugin-timeline/src/ObjectTimeline.tsx#effectiveItems (`item[groupByField]`)." + "note": "objectui: KanbanImpl.tsx:682 — field-by-field wired (audit L16). `lanes` (the lanes the board draws, in order, as stored option values of `groupByField`; absent meaning one lane per option) is live: both producers of the `object-kanban` node, ui/packages/plugin-list/src/ListView.tsx (its `case 'kanban'` branch) and ui/packages/plugin-view/src/ObjectView.tsx#generateViewSchema, hand it to the board as the node's `columns` through ui/packages/core/src/utils/kanban-declared-lanes.ts#kanbanDeclaredLanes (the author's order, option labels as titles, a `lost` lane collapsed), and ui/packages/plugin-kanban/src/ObjectKanban.tsx#effectiveColumns draws explicit columns in that order, a record whose value is not listed landing in `Uncategorized` (pinned in ui/packages/plugin-kanban/src/ObjectKanban.declaredLanes-28211.test.tsx). `summary` (a lane statistic at each lane's foot: `count`, or `sum` of `field`, a sum over a windowed lane worded as the loaded cards'; `{ type: 'none' }` showing nothing, also over `summarizeField`), `showFieldLabels` (absent meaning true: a card names each field beside its value) and `hideEmptyFields` (absent meaning true: a card leaves out an empty field's line) are live (#36370): both producers, ui/packages/plugin-list/src/ListView.tsx (its `case 'kanban'` branch) and ui/packages/plugin-view/src/ObjectView.tsx#generateViewSchema, relay each onto the `object-kanban` node only when declared (the second pinned in ui/packages/plugin-view/src/__tests__/ObjectView.harness.test.tsx), ui/packages/plugin-kanban/src/ObjectKanban.tsx#columnSummary draws `summary` at the foot (ui/packages/plugin-kanban/src/KanbanColumnSummary.ts#laneStatistic) and builds the card rows by `hideEmptyFields`, and ui/packages/plugin-kanban/src/KanbanImpl.tsx#SortableCard reads `showFieldLabels` (pinned in ui/packages/plugin-kanban/src/ObjectKanban.laneStatistic-36370.test.tsx); the Console relays them through ui/packages/app-shell/src/views/objectViewOptions.ts#kanbanViewOptions. What `groupByField` names, on kanban, gantt and timeline alike (packages/spec/src/ui/view.zod.ts, the padded-spelling refusal; moved out of spec source, #23434): a lookup BY THAT NAME on data the server answers under the unpadded name, at objectui @dda8f3815 packages/plugin-list/src/ListView.tsx#laneField (`groupByField || groupField || detectStatusField(objectDef)`, inside #viewComponentSchema; cards bucketed by `card[laneField]`), objectui @dda8f3815 packages/plugin-gantt/src/ObjectGantt.tsx#groupByAccessor (splits on `.` and walks the record) and objectui @dda8f3815 packages/plugin-timeline/src/ObjectTimeline.tsx#effectiveItems (`item[groupByField]`)." }, "calendar": { "status": "live", diff --git a/packages/spec/src/ui/kanban-config-lane-summary.test.ts b/packages/spec/src/ui/kanban-config-lane-summary.test.ts new file mode 100644 index 00000000000..34c6997d800 --- /dev/null +++ b/packages/spec/src/ui/kanban-config-lane-summary.test.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36370 — the board's own view settings: `kanban.summary` (the lane + * foot statistic), `showFieldLabels` and `hideEmptyFields`. + * + * Legs: the three keys are members of the bare block and of a list view's + * `kanban` block; absence writes nothing (no spec default, so a stored view is + * unchanged); `summary` takes only what the board computes, `none`, `count` + * and the `sum` of a named field, and refuses `avg` / `min` / `max` (which wait + * for a server lane read) and a `sum` without its field. Whether the field is a + * number is judged against the object by `@objectstack/lint` + * (`validate-list-view-field-refs`), which pins it. + */ + +import { describe, it, expect } from 'vitest'; +import { KanbanConfigSchema, KanbanLaneSummarySchema, ListViewSchema } from './view.zod'; + +const BOARD = { groupByField: 'stage', columns: ['name'] } as const; + +describe('KanbanConfigSchema: the lane statistic and the two card toggles', () => { + it('accepts the three keys on the bare block and on a list view\'s block', () => { + const block = { ...BOARD, summary: { type: 'sum', field: 'amount' }, showFieldLabels: false, hideEmptyFields: false }; + expect(KanbanConfigSchema.parse(block)).toMatchObject(block); + const view = ListViewSchema.parse({ type: 'kanban', data: { provider: 'object', object: 'deal' }, columns: ['name'], kanban: block }); + expect(view.kanban).toMatchObject(block); + }); + + it('writes nothing when the keys are absent', () => { + const parsed = KanbanConfigSchema.parse(BOARD); + for (const key of ['summary', 'showFieldLabels', 'hideEmptyFields']) expect(parsed).not.toHaveProperty(key); + }); + + it('takes none, count and a field\'s sum', () => { + for (const summary of [{ type: 'none' }, { type: 'count' }, { type: 'sum', field: 'amount' }]) { + expect(KanbanLaneSummarySchema.safeParse(summary).success, JSON.stringify(summary)).toBe(true); + } + }); + + it('refuses what the board does not compute, a sum without its field, and a stray key', () => { + for (const summary of [ + { type: 'avg', field: 'amount' }, + { type: 'min', field: 'amount' }, + { type: 'max', field: 'amount' }, + { type: 'count_unique', field: 'amount' }, + { type: 'sum' }, + { type: 'sum', field: '' }, + { type: 'count', field: 'amount' }, + 'sum', + ]) { + expect(KanbanLaneSummarySchema.safeParse(summary).success, JSON.stringify(summary)).toBe(false); + } + }); +}); diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index 06c984d497c..50b9fa8d292 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -2370,6 +2370,42 @@ export const EmptyStateSchema = lazySchema(() => strictObject({ ), })); +/** + * objectstack#36370 — a board lane's foot statistic (`kanban.summary`). + * + * Its own closed set, not the list footer's `ColumnSummaryConfigSchema`: the + * board computes these in the browser, so the set is exactly what a reader + * computes. `count` counts the lane's records (the lane's own count, the one + * its header shows); `sum` totals a number field (`field` required) over the + * cards the lane has LOADED, not over every record of the lane, and says so + * at the foot when the lane holds more than it drew; `none` shows nothing, + * also over `summarizeField`. A sum over the whole lane, and an average, a + * minimum or a maximum, wait for a lane aggregate the query answers + * (objectstack#36520): over a lane that has loaded only part of its cards none + * of them is even a bound. + */ +export const KanbanLaneSummarySchema = lazySchema(() => z.discriminatedUnion('type', [ + strictObject({ + surface: 'this `none` lane statistic', + history: VIEW_HISTORY, + }, { + type: z.literal('none'), + }), + strictObject({ + surface: 'this `count` lane statistic', + history: VIEW_HISTORY, + }, { + type: z.literal('count'), + }), + strictObject({ + surface: 'this `sum` lane statistic', + history: VIEW_HISTORY, + }, { + type: z.literal('sum'), + field: z.string().min(1).describe('The number field the lane totals over its loaded cards (e.g. amount)'), + }), +]).describe('Lane foot statistic: none, the count of the lane\'s records, or the sum of a number field over the lane\'s loaded cards')); + /** * Kanban Settings */ @@ -2433,6 +2469,41 @@ export const KanbanConfigSchema = lazySchema(() => strictObject({ + 'the view. List each value once.', ), summarizeField: z.string().optional().describe('Field to sum at top of column (e.g. amount)'), + /** + * objectstack#36370 — the statistic each lane shows at its foot + * ({@link KanbanLaneSummarySchema}): `{ type: 'count' }` counts the lane's + * records; `{ type: 'sum', field }` totals a number field over the cards + * the lane has loaded (not the lane's every record: objectstack#36520); + * `{ type: 'none' }` shows nothing, also over a `summarizeField`. Without + * it a lane shows the sum of `summarizeField` where that is set, as before + * this key, and nothing otherwise. + * + * ⛔ No spec-side default: absence keeps a board stored before this key + * exactly as it was. + */ + summary: KanbanLaneSummarySchema.optional().describe( + 'The statistic each lane shows at its foot. `{ type: \'count\' }` counts the lane records; ' + + '`{ type: \'sum\', field: \'amount\' }` totals a number field over the cards the lane has loaded, ' + + 'not every record of the lane (the foot says so when the lane holds more); `{ type: \'none\' }` shows nothing. ' + + 'Takes precedence over summarizeField. Omit to keep summarizeField\'s sum, or no statistic without it.', + ), + /** + * objectstack#36370 — whether a card names each field beside its value. + * Absent means `true`, the card as boards drew it before this key; `false` + * leaves the values alone. + */ + showFieldLabels: z.boolean().optional().describe( + 'Whether each card names its fields beside their values. Omit for true (names shown); false shows the values alone.', + ), + /** + * objectstack#36370 — whether a card leaves out a field that holds nothing. + * Absent means `true`, the card as boards drew it before this key; `false` + * keeps the field's row with an empty value, so every card of the lane + * lines up. + */ + hideEmptyFields: z.boolean().optional().describe( + 'Whether a card leaves out a field that holds no value. Omit for true (left out); false keeps the field with an empty value.', + ), /** * [#16894] The one item-titled view config of the family that omitted this * key. `GalleryConfigSchema`, `TimelineConfigSchema`, `CalendarConfigSchema`, @@ -8333,6 +8404,8 @@ export type CalendarConfig = z.input; export type GanttConfig = z.input; export type GanttQuickFilter = z.input; export type KanbanConfig = z.input; +export type KanbanLaneSummary = z.input; +export type KanbanLaneSummaryParsed = z.infer; export type ListMapConfig = z.input; export type NavigationMode = z.input; export type TreeConfig = z.input; diff --git a/packages/spec/variant-docs.json b/packages/spec/variant-docs.json index 458049ec4e3..f805f45de26 100644 --- a/packages/spec/variant-docs.json +++ b/packages/spec/variant-docs.json @@ -228,6 +228,12 @@ "content/docs/automation/flows.mdx" ], "note": "An api flow start node's `config.signature` (#29983; the trigger verifies it since #30009). automation/flows.mdx teaches both forms beside the `secretRef` paragraph, in its `signs` table." + }, + { + "key": "type:count|none|sum", + "label": "board lane foot statistic (kanban.summary)", + "exempt": "generated-reference-only", + "reason": "Tenant-authored (#36370: the board's 视图设置 writes it, and an author may declare it on a list view's `kanban` block), so this is the weaker class and the gap is stated plainly: when this entry was added no hand-written page named `kanban.summary`. The generated content/docs/references/ui/view.mdx is the reference until the authoring guide is written; that teaching is the skills-docs follow-up #36422, and when a hand-written page teaches the three variants this entry becomes governed." } ] } diff --git a/ui/packages/app-shell/src/views/ListDraftActions.tsx b/ui/packages/app-shell/src/views/ListDraftActions.tsx index 7628bdcfa67..82d9ebbe2cb 100644 --- a/ui/packages/app-shell/src/views/ListDraftActions.tsx +++ b/ui/packages/app-shell/src/views/ListDraftActions.tsx @@ -41,7 +41,9 @@ import { ChevronDown, CopyPlus, RotateCcw, Save } from 'lucide-react'; */ export type ListPersonalizationPart = | Parameters>[0][number] - | 'summaries'; + | 'summaries' + // objectstack#36370 — a board's settings (its lanes, card fields, …). + | 'kanban'; /** The order the menu names the unsaved parts in: the toolbar's, then the Display panel's. */ const LIST_DRAFT_PART_ORDER: readonly ListPersonalizationPart[] = [ @@ -51,6 +53,7 @@ const LIST_DRAFT_PART_ORDER: readonly ListPersonalizationPart[] = [ 'columns', 'hiddenFields', 'summaries', + 'kanban', 'layout', 'rowColor', 'inlineEdit', @@ -84,6 +87,7 @@ export function ListDraftActions({ columns: t('console.objectView.personalizedParts.columns'), hiddenFields: t('console.objectView.personalizedParts.hiddenFields'), summaries: t('console.objectView.personalizedParts.summaries'), + kanban: t('console.objectView.personalizedParts.kanban'), density: t('console.objectView.personalizedParts.density'), layout: t('console.objectView.personalizedParts.layout'), rowColor: t('console.objectView.personalizedParts.rowColor'), diff --git a/ui/packages/app-shell/src/views/ObjectView.kanbanSaveAs-36370.test.tsx b/ui/packages/app-shell/src/views/ObjectView.kanbanSaveAs-36370.test.tsx new file mode 100644 index 00000000000..456e8a3847c --- /dev/null +++ b/ui/packages/app-shell/src/views/ObjectView.kanbanSaveAs-36370.test.tsx @@ -0,0 +1,302 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36370 — a board's changed settings are a part of the list's + * DRAFT (objectstack#35955), and 「Save as my view」 keeps them. + * + * Measured live on the CRM pipeline (a view a read-only package ships): the + * reader hid a lane, turned the field names off and picked a count, saved + * the board as one of their own views, and the new view opened with none of + * it — 「Save as my view」 laid the row colour over the body and never the + * board's part. Pinned here on the real `ObjectView` with the harness of + * `ObjectView.footerCalculationDraft-36194.test.tsx`: the changes go through + * the list's `onKanbanChange` door, write nothing, and the stored row's + * `config.kanban` carries them. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, act, waitFor, screen, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + // Stable identities: `ListView` names `perms` in its fetch dependencies. + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: { id: 'org1', name: 'Acme' } }), + // The shared view's saves are an administrator's. + useWorkspaceAdminStatus: () => ({ isAdmin: reader.admin, isResolved: true }), + createAuthenticatedFetch: () => vi.fn(), +})); + +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRealtimeSubscription: () => ({ lastMessage: null }), + useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }), +})); + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); +vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); + +/** Whether the reader is a workspace administrator. */ +const reader = vi.hoisted(() => ({ admin: true })); + +/** The props the list was last handed. */ +const listProps = vi.hoisted(() => ({ current: null as Record | null })); +vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ + ...(await importOriginal()), + ListView: (props: any) => { + listProps.current = props; + // The condition row's end: Discard and Save while the list holds a draft. + return
{props.conditionRowEnd}
; + }, +})); + +/** The session-held package list, as `GET /api/v1/packages` answers it (parsed). */ +const packageList = vi.hoisted(() => ({ answer: (): Promise => Promise.resolve([]) })); +vi.mock('./studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchSessionPackages: vi.fn(() => packageList.answer()), +})); + +import { ObjectView } from './ObjectView'; +import { ExpressionProvider } from '../providers/ExpressionProvider'; +import { resetListDraftStoreForTests } from './listDraftStore'; + +const OBJECT = 'showcase_task'; +const SHIPPED_PACKAGE = 'com.example.showcase'; +const CUSTOM_PACKAGE = 'com.example.showcase.custom'; + +/** A view the read-only code package ships, as `listViews()` serves it. */ +const SHIPPED = { + name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid', + columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE, +}; +/** A shared view the console saved: dotted the same way, in the customization package. */ +const CUSTOM = { + name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid', + columns: ['name', 'amount'], _packageId: CUSTOM_PACKAGE, +}; +/** A stored view bound to no package. */ +/** A board the read-only package ships. */ +const BOARD = { + name: `${OBJECT}.board`, object: OBJECT, label: 'Board', type: 'kanban', + columns: ['name', 'amount'], kanban: { groupByField: 'status', columns: ['name', 'amount'] }, + _packageId: SHIPPED_PACKAGE, +}; +/** + * A board that declares no `kanban` block: the lane field is the one the + * object's lifecycle picks (`status`), drawn by `kanbanViewOptions`. + */ +const BARE_BOARD = { name: `${OBJECT}.bare_board`, object: OBJECT, label: 'Bare board', type: 'kanban', columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE }; +/** The reader's own board, saved with no `kanban` block either. */ +const PERSONAL_BOARD = { + id: 'pv_board', user_id: 'u1', object_name: OBJECT, label: 'My board', + config: { type: 'kanban', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } }, +}; +const UNBOUND = { name: `${OBJECT}.unbound`, object: OBJECT, label: 'Unbound', type: 'grid', columns: ['name', 'amount'] }; +/** A stored view that declares no columns (the list draws the object's defaults). */ +const BARE = { name: `${OBJECT}.bare`, object: OBJECT, label: 'Bare', type: 'grid' }; +/** The reader's own view (`sys_personal_view`). */ +const PERSONAL = { + id: 'pv_mine', user_id: 'u1', object_name: OBJECT, label: 'My tasks', + config: { type: 'grid', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } }, +}; + +/** The packages row for each id: the server's `writable` verdict. */ +const PACKAGES = [ + { id: SHIPPED_PACKAGE, name: 'Showcase', writable: false, namespace: 'showcase' }, + { id: CUSTOM_PACKAGE, name: 'Showcase (custom)', writable: true, namespace: 'showcase' }, +]; + +function mount(viewId: string) { + const dataSource = { + find: vi.fn(async (resource: string) => + resource === 'sys_personal_view' ? { data: [PERSONAL, PERSONAL_BOARD], total: 2 } : { data: [], total: 0 }), + findOne: vi.fn(async () => null), + create: vi.fn(async (_resource: string, data: Record) => ({ id: 'pv_new', ...data })), + update: vi.fn(async (_resource: string, _id: string, _patch: Record) => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: {} })), + listViews: vi.fn(async () => [SHIPPED, CUSTOM, UNBOUND, BARE, BOARD, BARE_BOARD]), + updateView: vi.fn(async () => ({})), + }; + render( + + + + {}} + /> + } + /> + + + , + ); + return { dataSource }; +} + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 300))); + +/** Whether the list is handed the footer's calculation pick. */ +const offersMenu = () => typeof listProps.current?.onColumnSummaryPick === 'function'; +/** Pick a calculation through the list's door, as the grid's footer menu does. */ +const pick = (field: string, summary: string | null) => + act(async () => { + expect(await listProps.current!.onColumnSummaryPick(field, summary)).toBe(true); + }); +/** The calculation the list draws under `field`, as its schema's columns carry it. */ +const summaryOf = (field: string) => { + const columns = (listProps.current?.schema?.columns ?? []) as Array; + const column = columns.find((c) => (typeof c === 'string' ? c : c.field) === field); + return column && typeof column === 'object' ? column.summary : undefined; +}; +const storedSummaries = (config: any) => + Object.fromEntries( + ((config?.columns ?? []) as Array) + .filter((c): c is { field: string; summary?: unknown } => typeof c === 'object' && c.summary !== undefined) + .map((c) => [c.field, c.summary]), + ); +const openSave = async () => { + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + return screen.findByTestId('list-draft-save-menu'); +}; + +/** Every request the page sends through `fetch` that is not a read. */ +const writes: string[] = []; +vi.stubGlobal('fetch', vi.fn(async (input: unknown, init?: { method?: string }) => { + const method = (init?.method ?? 'GET').toUpperCase(); + if (method !== 'GET') writes.push(`${method} ${String(input)}`); + return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }); +})); + +beforeEach(() => { + listProps.current = null; + reader.admin = true; + writes.length = 0; + packageList.answer = () => Promise.resolve(PACKAGES); + localStorage.clear(); + resetListDraftStoreForTests(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('objectstack#36370 — 「Save as my view」 keeps a board\'s changed settings', () => { + it('the changes write nothing, Save names them, and the new view stores them', async () => { + const page = mount(BOARD.name); + await settle(); + await waitFor(() => expect(typeof listProps.current?.onKanbanChange).toBe('function')); + + act(() => { + listProps.current!.onKanbanChange({ lanes: ['done'] }); + }); + act(() => { + listProps.current!.onKanbanChange({ showFieldLabels: false, summary: { type: 'count' } }); + }); + await settle(); + expect(listProps.current?.schema?.kanban).toMatchObject({ lanes: ['done'], showFieldLabels: false, summary: { type: 'count' } }); + expect(writes).toEqual([]); + expect(page.dataSource.updateView).not.toHaveBeenCalled(); + + await openSave(); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + fireEvent.click(await screen.findByTestId('personal-view-name-submit')); + await waitFor(() => expect(page.dataSource.create).toHaveBeenCalledTimes(1)); + const [resource, row] = page.dataSource.create.mock.calls[0]; + expect(resource).toBe('sys_personal_view'); + expect(row.config.kanban).toMatchObject({ + groupByField: 'status', + lanes: ['done'], + showFieldLabels: false, + summary: { type: 'count' }, + }); + expect(writes).toEqual([]); + }); + + /** + * L2 on #36411: a board whose view declares no `kanban` block draws the lane + * field the object picks. A changed toggle or statistic, saved, must carry + * that lane: `KanbanConfigSchema` requires `groupByField`, and a stored + * `kanban: { showFieldLabels: false }` alone is a block the spec refuses. + */ + it('a board with no kanban block: 「Save as my view」 stores the lane field the board draws', async () => { + const page = mount(BARE_BOARD.name); + await settle(); + await waitFor(() => expect(typeof listProps.current?.onKanbanChange).toBe('function')); + act(() => { + listProps.current!.onKanbanChange({ showFieldLabels: false }); + }); + await settle(); + await openSave(); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + fireEvent.click(await screen.findByTestId('personal-view-name-submit')); + await waitFor(() => expect(page.dataSource.create).toHaveBeenCalledTimes(1)); + const [, row] = page.dataSource.create.mock.calls[0]; + expect(row.config.kanban).toMatchObject({ groupByField: 'status', showFieldLabels: false }); + expect(writes).toEqual([]); + }); + + it('the reader\'s own board with no kanban block: 「Save to this view」 stores the lane field the board draws', async () => { + const page = mount(PERSONAL_BOARD.id); + await settle(); + await waitFor(() => expect(typeof listProps.current?.onKanbanChange).toBe('function')); + act(() => { + listProps.current!.onKanbanChange({ summary: { type: 'count' } }); + }); + await settle(); + await openSave(); + fireEvent.click(await screen.findByTestId('list-draft-save-to-view')); + await waitFor(() => expect(page.dataSource.update).toHaveBeenCalledTimes(1)); + const [resource, id, patch] = page.dataSource.update.mock.calls[0]; + expect([resource, id]).toEqual(['sys_personal_view', PERSONAL_BOARD.id]); + expect(patch.config.kanban).toMatchObject({ groupByField: 'status', summary: { type: 'count' } }); + expect(writes).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 38522595f75..1a597eecb74 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -117,6 +117,7 @@ import { ChangeOwnerDialog } from './ChangeOwnerDialog.js'; import { changeOwnerEligibleRows, changeOwnerObjectOffer, useListChangeOwnerOffered } from './changeOwner.js'; import { parseListStateParams } from './userFilterUrlState.js'; import { FILTER_FOLD_REFUSAL_KEYS } from './viewFilterFold.js'; +import { kanbanDraftToSave } from './objectViewOptions.js'; // objectstack#25992 slice 1: these module-level helpers moved to the sibling // `objectView*.ts` modules above. Every name this file exported stays @@ -770,6 +771,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co const draftDisplay = { ...(listDraft.draft.viewType ? { viewType: listDraft.draft.viewType } : {}), ...(listDraft.draft.rowColor !== undefined ? { rowColor: listDraft.draft.rowColor } : {}), + // objectstack#36370 — and a board's changed settings, with the lane + // field the board draws when the view declares none (`kanbanDraftToSave`). + ...(listDraft.draft.kanban ? { kanban: kanbanDraftToSave(activeView, objectDef, listDraft.draft.kanban) } : {}), }; // objectstack#25992 slice 8: the list's toolbar state in the URL (seed, write-back, // "Reset view") moved to `./objectViewListUrlState.ts`. @@ -1029,7 +1033,12 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co if (!activeView) return false; // objectstack#35955 — the draft's layout is the new view's type (so // the type's own field list is filled as the create card fills it), - // and its row colour is laid over the body. + // and its row colour is laid over the body; objectstack#36370 — so are + // a board's changed settings. + const saveAsDisplay = { + ...(listDraft.draft.rowColor !== undefined ? { rowColor: listDraft.draft.rowColor } : {}), + ...(listDraft.draft.kanban ? { kanban: kanbanDraftToSave(activeView, objectDef, listDraft.draft.kanban) } : {}), + }; const built = buildInPlaceViewConfig( objectDef.name, activeView, @@ -1039,7 +1048,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, summaries: listDraft.draft.summaries, - ...(listDraft.draft.rowColor !== undefined ? { display: { rowColor: listDraft.draft.rowColor } } : {}), + ...(Object.keys(saveAsDisplay).length > 0 ? { display: saveAsDisplay } : {}), }, ); if (!built.ok) { diff --git a/ui/packages/app-shell/src/views/kanbanDraft-36370.test.ts b/ui/packages/app-shell/src/views/kanbanDraft-36370.test.ts new file mode 100644 index 00000000000..11df1732adf --- /dev/null +++ b/ui/packages/app-shell/src/views/kanbanDraft-36370.test.ts @@ -0,0 +1,140 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36370 — a board's 视图设置 under the #35955 draft rules: each + * change applies at once, is held as the list's draft (`ListDraft.kanban`, the + * changed keys only), and is written only by Save. + * + * Rows: + * (a) `nextKanbanDraft` keeps the keys that differ from the view's own block, + * drops a key changed back, and answers `undefined` once nothing differs; + * `null` is "absent" (a key the reader removed); + * (b) `layKanbanDraft` lays the draft over the block, `null` deleting a key; + * (c) Save (`buildPersonalViewConfig` / `layListStateOverView`) writes the + * laid block, which the spec's `ListViewSchema` accepts with the new + * keys; without a kanban draft the view's block is written as it is; + * (d) `kanbanViewOptions` relays `lanes` (objectstack#28211 — the Console + * board drew every option before this) and the three new keys, each only + * when the view declares it. + */ + +import { describe, expect, it } from 'vitest'; +import { ListViewSchema } from '@objectstack/spec/ui'; +import { layKanbanDraft, nextKanbanDraft } from './listDraftStore'; +import { buildPersonalViewConfig, layListStateOverView } from './personalViews'; +import { kanbanViewOptions } from './objectViewOptions'; + +const OWN = { + groupByField: 'stage', + columns: ['amount', 'account'], + lanes: ['new', 'proposal', 'won'], +}; + +describe('the board draft (objectstack#36370)', () => { + it('(a) keeps the changed keys, drops one changed back, and is undefined once nothing differs', () => { + const one = nextKanbanDraft(undefined, { groupByField: 'owner', lanes: null }, OWN); + expect(one).toEqual({ groupByField: 'owner', lanes: null }); + + const two = nextKanbanDraft(one, { showFieldLabels: false }, OWN); + expect(two).toEqual({ groupByField: 'owner', lanes: null, showFieldLabels: false }); + + // Back to the view's own lane field and lanes: only the toggle is left. + const three = nextKanbanDraft(two, { groupByField: 'stage', lanes: ['new', 'proposal', 'won'] }, OWN); + expect(three).toEqual({ showFieldLabels: false }); + + // The toggle on again is the key absent, as the view has it. + expect(nextKanbanDraft(three, { showFieldLabels: null }, OWN)).toBeUndefined(); + }); + + it('(a) a lane order differs from the view\'s even with the same lanes', () => { + expect(nextKanbanDraft(undefined, { lanes: ['won', 'new', 'proposal'] }, OWN)).toEqual({ + lanes: ['won', 'new', 'proposal'], + }); + }); + + it('(b) lays the draft over the block, null deleting a key', () => { + expect(layKanbanDraft(OWN, { lanes: null, summary: { type: 'count' } })).toEqual({ + groupByField: 'stage', + columns: ['amount', 'account'], + summary: { type: 'count' }, + }); + expect(layKanbanDraft(undefined, { showFieldLabels: false })).toEqual({ showFieldLabels: false }); + // CONTROL: no draft is the block as it is. + expect(layKanbanDraft(OWN, undefined)).toEqual(OWN); + }); +}); + +describe('Save writes the board draft (objectstack#36370)', () => { + const VIEW = { + id: 'pipeline', + name: 'pipeline', + label: 'Pipeline', + type: 'kanban', + columns: ['name', 'stage', 'amount'], + kanban: OWN, + }; + + it('(c) lays the changed keys over the view\'s block, in a body the spec accepts', () => { + const draft = nextKanbanDraft(undefined, { + lanes: ['proposal', 'new'], + hideEmptyFields: false, + summary: { type: 'sum', field: 'amount' }, + }, OWN); + const laid = layListStateOverView(VIEW, { url: {}, display: { kanban: draft } }); + expect(laid.ok).toBe(true); + if (!laid.ok) return; + expect(laid.view.kanban).toEqual({ + groupByField: 'stage', + columns: ['amount', 'account'], + lanes: ['proposal', 'new'], + hideEmptyFields: false, + summary: { type: 'sum', field: 'amount' }, + }); + + const built = buildPersonalViewConfig('deal', VIEW, { url: {}, display: { kanban: draft } }); + expect(built.ok).toBe(true); + if (!built.ok) return; + expect(ListViewSchema.safeParse(built.config).success).toBe(true); + expect(built.config.kanban).toMatchObject({ hideEmptyFields: false, summary: { type: 'sum', field: 'amount' } }); + }); + + it('(c) CONTROL: without a board draft the view\'s block is written as it is', () => { + const laid = layListStateOverView(VIEW, { url: {} }); + expect(laid.ok && laid.view.kanban).toEqual(OWN); + }); +}); + +describe('the Console relays the board block (objectstack#36370)', () => { + const OBJECT = { name: 'deal', fields: { name: { type: 'text' }, stage: { type: 'select' } } }; + + it('(d) carries lanes and the new keys when the view declares them', () => { + const out = kanbanViewOptions({ + kanban: { + groupByField: 'stage', + lanes: ['won', 'new'], + summary: { type: 'count' }, + showFieldLabels: false, + hideEmptyFields: false, + }, + }, OBJECT); + expect(out.lanes).toEqual(['won', 'new']); + expect(out.summary).toEqual({ type: 'count' }); + expect(out.showFieldLabels).toBe(false); + expect(out.hideEmptyFields).toBe(false); + }); + + it('(d) omits each key the view does not declare, and an empty lane list', () => { + const out = kanbanViewOptions({ kanban: { groupByField: 'stage', lanes: [] } }, OBJECT); + for (const key of ['lanes', 'summary', 'showFieldLabels', 'hideEmptyFields']) { + expect(out).not.toHaveProperty(key); + } + // CONTROL: the bag is not empty. + expect(out.groupByField).toBe('stage'); + }); +}); diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index de62f063d66..7c93fb14dc7 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -8,8 +8,9 @@ * * What a draft holds: the sort, the Filter panel's group, the grouping, the * search term, the columns shown (hidden ones, added ones), the column order, - * the footer's calculations (objectstack#36194) and the Display panel's layout - * and row colour. What it never holds: the column widths, the row height and + * the footer's calculations (objectstack#36194), the Display panel's layout + * and row colour, and a board's settings (objectstack#36370: its lane field, + * lanes, card fields, card toggles and lane statistic). What it never holds: the column widths, the row height and * the view tab order, which are the reader's layout in this browser * (`./listLayoutStore.ts`). * @@ -107,6 +108,51 @@ export interface ListDraft { * from the view are held; picking the view's own again drops the column. */ summaries?: DraftColumnSummaries; + /** + * objectstack#36370 — the keys of the view's `kanban` block the reader + * changed, each differing from the view's own; `null` = the key leaves the + * block (a lane field picked anew draws every lane: `lanes: null`). Laid + * over a block by {@link layKanbanDraft}. + */ + kanban?: KanbanDraft; +} + +/** objectstack#36370 — a board's changed `kanban` keys (`null` = the key is dropped). */ +export type KanbanDraft = Readonly>; + +/** A `kanban` block with the draft's changed keys laid over it (`null` drops a key). */ +export function layKanbanDraft( + block: Readonly> | undefined, + draft: KanbanDraft | undefined, +): Record { + const out: Record = { ...(block ?? {}) }; + for (const [key, value] of Object.entries(draft ?? {})) { + if (value === null || value === undefined) delete out[key]; + else out[key] = value; + } + return out; +} + +/** + * The board's draft after `patch` (objectstack#36370): the keys changed so + * far with `patch` laid on, each key that is the view's own again (`own`, the + * view's block as the board draws it, `kanbanViewOptions`) left out. + * `undefined` once nothing differs. + */ +export function nextKanbanDraft( + current: KanbanDraft | undefined, + patch: Readonly>, + own: Readonly> | undefined, +): KanbanDraft | undefined { + const merged: Record = { ...(current ?? {}), ...patch }; + for (const [key, value] of Object.entries(merged)) { + const ownValue = own?.[key]; + const sameAsOwn = value === null || value === undefined + ? ownValue === undefined + : JSON.stringify(value) === JSON.stringify(ownValue); + if (sameAsOwn) delete merged[key]; + } + return Object.keys(merged).length > 0 ? merged : undefined; } /** A patch: a part set to `undefined` is dropped back to the view's own. */ @@ -164,7 +210,7 @@ function normalizePart(key: string, value: unknown): unknown { const conditions = (value as { conditions?: unknown } | null | undefined)?.conditions; return Array.isArray(conditions) && conditions.length > 0 ? value : undefined; } - if (key === 'summaries') { + if (key === 'summaries' || key === 'kanban') { return value && typeof value === 'object' && Object.keys(value).length > 0 ? value : undefined; } return value; diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index b59f7a49230..c0d09e9b66a 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -11,7 +11,7 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, lazy, Suspense, type ReactNode } from 'react'; import { DENSITY_MODE_TO_ROW_HEIGHT, columnIdentity, normalizeListViewSchema, servedPackageId, type FilterTokenScope } from '@object-ui/core'; -import { listDraftPreference, type useListDraft } from './listDraftStore.js'; +import { layKanbanDraft, listDraftPreference, nextKanbanDraft, type useListDraft } from './listDraftStore.js'; import { columnSummaryOf, columnsWithSummaries, declaredColumnFields } from './columnSummaryWrite.js'; import type { useObjectListLayout } from './listLayoutStore.js'; import type { ListViewPreference } from './listDraftStore.js'; @@ -1010,7 +1010,11 @@ export function useObjectViewListRenderer({ // outranks what this page relays (it never did through the bag). // The lane key is the spec's `groupByField`, not the legacy // `groupField` this used to write. See `kanbanViewOptions`. - kanban: holdBlock('kanban', kanbanViewOptions(viewDef, objectDef)), + // + // objectstack#36370 — with the board's settings the list's draft + // holds laid over it (`layKanbanDraft`): a change in 视图设置 or in + // a lane's menu draws at once and is kept by Save alone. + kanban: holdBlock('kanban', layKanbanDraft(kanbanViewOptions(viewDef, objectDef), listDraft.draft.kanban)), // The calendar config the view DECLARED, or `undefined` — never // an invented field name (objectui#7029). With no block, // ListView's capability gate stops offering the @@ -1133,6 +1137,14 @@ export function useObjectViewListRenderer({ // picks are the list's draft; picking the view's own again // drops that part. onViewChange={(view: string) => listDraft.patch({ viewType: view === listSchema.viewType ? undefined : view })} + // objectstack#36370 — a board's settings are the list's draft + // too: each changed key of the view's kanban block, dropped + // again once it is the view's own as the board draws it (an + // auto-detected lane field picked back is no change). + laneCollapseKey={activeView.id} + onKanbanChange={(patch: Record) => listDraft.patch({ + kanban: nextKanbanDraft(listDraft.draft.kanban, patch, kanbanViewOptions(viewDef, objectDef)), + })} onRowColorChange={(rowColor: { field: string; colors?: Record } | null) => listDraft.patch({ rowColor: (rowColor?.field ?? '') === (viewOwnRowColor?.field ?? '') ? undefined : rowColor, })} diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index 99d1380cf17..e10a30dfac7 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -381,6 +381,10 @@ export function useObjectViewListUrlState({ if (listDraft.summaries && Object.keys(listDraft.summaries).length > 0) { listDraftParts.push('summaries'); } + // objectstack#36370 — and a board's settings: one part, however many keys. + if (listDraft.kanban && Object.keys(listDraft.kanban).length > 0) { + listDraftParts.push('kanban'); + } /** * objectstack#35955 — Discard (objectstack#28950's "Reset to view" before diff --git a/ui/packages/app-shell/src/views/objectViewOptions.ts b/ui/packages/app-shell/src/views/objectViewOptions.ts index db758479a44..02255733762 100644 --- a/ui/packages/app-shell/src/views/objectViewOptions.ts +++ b/ui/packages/app-shell/src/views/objectViewOptions.ts @@ -341,6 +341,12 @@ export function kanbanViewOptions(viewDef: any, objectDef: any): Record 0 + ? viewDef.kanban.lanes + : undefined; return { ...(lane ? { groupByField: lane } : {}), titleField: viewDef?.kanban?.titleField || 'name', @@ -348,10 +354,37 @@ export function kanbanViewOptions(viewDef: any, objectDef: any): Record> | undefined, +): Record | undefined { + if (!draft) return undefined; + const ownLane = viewDef?.kanban?.groupByField; + if ((typeof ownLane === 'string' && ownLane !== '') || 'groupByField' in draft) return { ...draft }; + const lane = kanbanViewOptions(viewDef, objectDef).groupByField; + return typeof lane === 'string' && lane !== '' ? { groupByField: lane, ...draft } : { ...draft }; +} + /** * objectui#10046 — is `a` the same set of per-kind blocks as `b` (the `options` * bag until #25923), compared by VALUE? (objectui#7237 holds the resolved diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index d775ec26953..958b4427833 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -39,7 +39,7 @@ import { foldFilterGroupToSpecRules, type FilterFoldRefusal } from './viewFilter import { buildViewConfigSaveBody } from './objectViewTabs.js'; import { columnsWithSummaries, type DraftColumnSummaries } from './columnSummaryWrite.js'; import type { ListSortRule, ListUrlState } from './userFilterUrlState.js'; -import type { ListViewPreference } from './listDraftStore.js'; +import { layKanbanDraft, type KanbanDraft, type ListViewPreference } from './listDraftStore.js'; /** The object a personal view is a row of. */ export const PERSONAL_VIEW_OBJECT = 'sys_personal_view'; @@ -182,8 +182,15 @@ export interface PersonalViewListState { * draft holds (`ListDraft.viewType` / `rowColor`). `viewType` retypes the * body; `rowColor: null` is "none" over a view that colours its rows. An * absent part is the view's own. + * + * objectstack#36370 — and a board's changed `kanban` keys + * (`ListDraft.kanban`), laid over the view's block. */ - display?: { viewType?: string; rowColor?: { field: string; colors?: Record } | null }; + display?: { + viewType?: string; + rowColor?: { field: string; colors?: Record } | null; + kanban?: KanbanDraft; + }; } /** The column a `columns` entry names: a bare name, or an entry's `field`. */ @@ -302,6 +309,10 @@ export function layListStateOverView( if (names.length > 0) draft[display.viewType] = { ...block, [mirrorKey]: names }; } } + if (display?.kanban) { + const base = isRecord(draft.kanban) ? (draft.kanban as Record) : undefined; + draft.kanban = layKanbanDraft(base, display.kanban); + } return { ok: true, view: draft }; } diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 8abffe74835..4beb0ed04c4 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -465,7 +465,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 125 once objectstack-ai/objectstack#36363 added `designMode.menu.iconHint`, // the menu editor's icon field naming an example icon („briefcase“) — one // literal span. - expect(okSpans, 'correctly paired spans').toBe(125); + // 127 once objectstack-ai/objectstack#36370 added `kanban.laneMenu.hideHint` + // and `list.optionsMenu.kanbanHiddenLanesHint`, the board's two lines naming + // the lane hidden cards land in („Nicht kategorisiert“) — two literal spans. + expect(okSpans, 'correctly paired spans').toBe(127); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -591,7 +594,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `console.commandPalette.createAs`, one more matched pair. // 125 / 125 / 0 after objectstack-ai/objectstack#36363 added // `designMode.menu.iconHint`, one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 125, close: 125, rdq: 0 }); + // 127 / 127 / 0 after objectstack-ai/objectstack#36370 added + // `kanban.laneMenu.hideHint` and `list.optionsMenu.kanbanHiddenLanesHint`, + // two more matched pairs. + expect({ open, close, rdq }).toEqual({ open: 127, close: 127, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ac43f404220..7e116670ffe 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1132,6 +1132,16 @@ const ar = { inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "الأعمدة حسب", + kanbanLanes: "الأعمدة الظاهرة", + kanbanCardFields: "حقول البطاقة", + kanbanAddCardField: "إضافة حقل", + kanbanShowFieldLabels: "إظهار أسماء الحقول", + kanbanHideEmptyFields: "إخفاء الحقول الفارغة", + kanbanSummary: "ملخص العمود", + kanbanHiddenLanes: "الأعمدة المخفية", + kanbanHiddenLanesHint: "تظهر بطاقات العمود المخفي ضمن «غير مصنّف».", viewName: 'اسم العرض', fields: 'الحقول', fieldsShown: 'الحقول المعروضة: {{count}}', @@ -1179,6 +1189,19 @@ const ar = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "إجراءات العمود {{column}}", + collapse: "طي العمود", + expand: "توسيع العمود", + hide: "إخفاء العمود", + hideHint: "تنتقل بطاقاته إلى «غير مصنّف»", + createIn: "سجل جديد في {{column}}", + create: "جديد", + }, + laneStatistic: { + loadedOnly: "البطاقات المحمّلة", + }, uncategorized: "غير مصنّف", loadMore: "تحميل المزيد", columns: "أعمدة", @@ -3097,6 +3120,7 @@ const ar = { }, linkFilterRefused: 'لم يُطبَّق عامل التصفية في هذا الرابط، لأنه يذكر حقلًا لا يمكنك التصفية حسبه هنا، لذا تعرض القائمة طريقة العرض دونه.', personalizedParts: { + kanban: "إعدادات اللوحة", filters: "عوامل التصفية", search: "البحث", sort: "الترتيب", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 8084ec8f42f..99a04f8246c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1011,6 +1011,16 @@ const de = { inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Spalten nach", + kanbanLanes: "Sichtbare Spalten", + kanbanCardFields: "Kartenfelder", + kanbanAddCardField: "Feld hinzufügen", + kanbanShowFieldLabels: "Feldnamen anzeigen", + kanbanHideEmptyFields: "Leere Felder ausblenden", + kanbanSummary: "Spaltenauswertung", + kanbanHiddenLanes: "Ausgeblendete Spalten", + kanbanHiddenLanesHint: "Karten einer ausgeblendeten Spalte erscheinen unter „Nicht kategorisiert“.", viewName: 'Ansichtsname', fields: 'Felder', fieldsShown: '{{count}} angezeigt', @@ -1054,6 +1064,19 @@ const de = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "Aktionen für Spalte {{column}}", + collapse: "Spalte einklappen", + expand: "Spalte ausklappen", + hide: "Spalte ausblenden", + hideHint: "Die Karten wandern nach „Nicht kategorisiert“", + createIn: "Neuer Datensatz in {{column}}", + create: "Neu", + }, + laneStatistic: { + loadedOnly: "geladene Karten", + }, uncategorized: "Nicht kategorisiert", loadMore: "Mehr laden", columns: "Spalten", @@ -2801,6 +2824,7 @@ const de = { }, linkFilterRefused: 'Der Filter dieses Links wurde nicht angewendet. Er nennt ein Feld, nach dem Sie hier nicht filtern können, daher zeigt die Liste die Ansicht ohne ihn.', personalizedParts: { + kanban: "Board-Einstellungen", filters: "Filter", search: "Suche", sort: "Sortierung", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3684e31dafe..6e0203855d0 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1313,6 +1313,16 @@ const en = { inlineEditLabel: 'Edit records inline (click a cell to edit)', // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Columns by", + kanbanLanes: "Visible columns", + kanbanCardFields: "Card fields", + kanbanAddCardField: "Add field", + kanbanShowFieldLabels: "Show field names", + kanbanHideEmptyFields: "Hide empty fields", + kanbanSummary: "Column summary", + kanbanHiddenLanes: "Hidden columns", + kanbanHiddenLanesHint: "Cards of a hidden column show under Uncategorized.", viewName: 'View name', fields: 'Fields', fieldsShown: '{{count}} shown', @@ -1356,6 +1366,19 @@ const en = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "{{column}} column actions", + collapse: "Collapse column", + expand: "Expand column", + hide: "Hide column", + hideHint: "Its cards move to Uncategorized", + createIn: "New record in {{column}}", + create: "New", + }, + laneStatistic: { + loadedOnly: "loaded cards", + }, addCard: 'Add card', addColumn: 'Add column', moveCard: 'Move card', @@ -3405,6 +3428,7 @@ const en = { }, linkFilterRefused: 'This link’s filter was not applied. It names a field you can’t filter on here, so the list shows the view without it.', personalizedParts: { + kanban: "Board settings", filters: 'Filters', search: 'Search', sort: 'Sort', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 10d50139536..14d1435d08b 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1044,6 +1044,16 @@ const es = { inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Columnas por", + kanbanLanes: "Columnas visibles", + kanbanCardFields: "Campos de la tarjeta", + kanbanAddCardField: "Añadir campo", + kanbanShowFieldLabels: "Mostrar nombres de campo", + kanbanHideEmptyFields: "Ocultar campos vacíos", + kanbanSummary: "Resumen de columna", + kanbanHiddenLanes: "Columnas ocultas", + kanbanHiddenLanesHint: "Las tarjetas de una columna oculta aparecen en Sin categoría.", viewName: 'Nombre de la vista', fields: 'Campos', fieldsShown: 'Visibles: {{count}}', @@ -1088,6 +1098,19 @@ const es = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "Acciones de la columna {{column}}", + collapse: "Contraer columna", + expand: "Expandir columna", + hide: "Ocultar columna", + hideHint: "Sus tarjetas pasan a Sin categoría", + createIn: "Nuevo registro en {{column}}", + create: "Nuevo", + }, + laneStatistic: { + loadedOnly: "tarjetas cargadas", + }, uncategorized: "Sin categoría", loadMore: "Cargar más", columns: "columnas", @@ -2877,6 +2900,7 @@ const es = { }, linkFilterRefused: 'No se aplicó el filtro de este enlace. Incluye un campo por el que no puede filtrar aquí, así que la lista muestra la vista sin él.', personalizedParts: { + kanban: "Ajustes del tablero", filters: "Filtros", search: "Búsqueda", sort: "Ordenación", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 6a9fb41ee93..ae5ec6e7760 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1039,6 +1039,16 @@ const fr = { inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Colonnes par", + kanbanLanes: "Colonnes visibles", + kanbanCardFields: "Champs de la carte", + kanbanAddCardField: "Ajouter un champ", + kanbanShowFieldLabels: "Afficher les noms des champs", + kanbanHideEmptyFields: "Masquer les champs vides", + kanbanSummary: "Synthèse de colonne", + kanbanHiddenLanes: "Colonnes masquées", + kanbanHiddenLanesHint: "Les cartes d’une colonne masquée apparaissent dans Non catégorisé.", viewName: 'Nom de la vue', fields: 'Champs', fieldsShown: 'Affichés : {{count}}', @@ -1083,6 +1093,19 @@ const fr = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "Actions de la colonne {{column}}", + collapse: "Réduire la colonne", + expand: "Développer la colonne", + hide: "Masquer la colonne", + hideHint: "Ses cartes passent dans Non catégorisé", + createIn: "Nouvel enregistrement dans {{column}}", + create: "Nouveau", + }, + laneStatistic: { + loadedOnly: "cartes chargées", + }, uncategorized: "Non catégorisé", loadMore: "Charger plus", columns: "colonnes", @@ -2873,6 +2896,7 @@ const fr = { }, linkFilterRefused: 'Le filtre de ce lien n’a pas été appliqué. Il cite un champ sur lequel vous ne pouvez pas filtrer ici, la liste affiche donc la vue sans ce filtre.', personalizedParts: { + kanban: "Réglages du tableau", filters: "Filtres", search: "Recherche", sort: "Tri", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 61180baad15..e1659e47807 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1011,6 +1011,16 @@ const ja = { inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "列の分け方", + kanbanLanes: "表示する列", + kanbanCardFields: "カードの項目", + kanbanAddCardField: "項目を追加", + kanbanShowFieldLabels: "項目名を表示", + kanbanHideEmptyFields: "空の項目を隠す", + kanbanSummary: "列の集計", + kanbanHiddenLanes: "非表示の列", + kanbanHiddenLanesHint: "非表示の列のカードは「未分類」に表示されます。", viewName: 'ビュー名', fields: 'フィールド', fieldsShown: '{{count}} 件表示中', @@ -1054,6 +1064,19 @@ const ja = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "{{column}} 列の操作", + collapse: "列を折りたたむ", + expand: "列を展開", + hide: "列を非表示", + hideHint: "カードは「未分類」に移ります", + createIn: "{{column}} に新規作成", + create: "新規", + }, + laneStatistic: { + loadedOnly: "読み込み済みのカード", + }, uncategorized: "未分類", loadMore: "さらに読み込む", columns: "カラム", @@ -2803,6 +2826,7 @@ const ja = { }, linkFilterRefused: 'このリンクのフィルターは適用されませんでした。ここでは絞り込めないフィールドが含まれているため、ビュー本来の内容を表示しています。', personalizedParts: { + kanban: "ボードの設定", filters: "フィルター", search: "検索", sort: "並べ替え", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5c13dde9655..0dca5d4ab09 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1011,6 +1011,16 @@ const ko = { inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "열 기준", + kanbanLanes: "표시할 열", + kanbanCardFields: "카드 필드", + kanbanAddCardField: "필드 추가", + kanbanShowFieldLabels: "필드 이름 표시", + kanbanHideEmptyFields: "빈 필드 숨기기", + kanbanSummary: "열 요약", + kanbanHiddenLanes: "숨긴 열", + kanbanHiddenLanesHint: "숨긴 열의 카드는 「미분류」에 표시됩니다.", viewName: '보기 이름', fields: '필드', fieldsShown: '{{count}}개 표시됨', @@ -1054,6 +1064,19 @@ const ko = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "{{column}} 열 작업", + collapse: "열 접기", + expand: "열 펼치기", + hide: "열 숨기기", + hideHint: "카드는 「미분류」로 이동합니다", + createIn: "{{column}}에 새로 만들기", + create: "새로 만들기", + }, + laneStatistic: { + loadedOnly: "불러온 카드", + }, uncategorized: "미분류", loadMore: "더 보기", columns: "열", @@ -2801,6 +2824,7 @@ const ko = { }, linkFilterRefused: '이 링크의 필터가 적용되지 않았습니다. 여기서 필터링할 수 없는 필드가 포함되어 있어 뷰를 그대로 표시합니다.', personalizedParts: { + kanban: "보드 설정", filters: "필터", search: "검색", sort: "정렬", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0391db19ef5..a6e96fc7d35 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1039,6 +1039,16 @@ const pt = { inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Colunas por", + kanbanLanes: "Colunas visíveis", + kanbanCardFields: "Campos do cartão", + kanbanAddCardField: "Adicionar campo", + kanbanShowFieldLabels: "Mostrar nomes dos campos", + kanbanHideEmptyFields: "Ocultar campos vazios", + kanbanSummary: "Resumo da coluna", + kanbanHiddenLanes: "Colunas ocultas", + kanbanHiddenLanesHint: "Os cartões de uma coluna oculta aparecem em Sem categoria.", viewName: 'Nome da visualização', fields: 'Campos', fieldsShown: 'Exibidos: {{count}}', @@ -1083,6 +1093,19 @@ const pt = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "Ações da coluna {{column}}", + collapse: "Recolher coluna", + expand: "Expandir coluna", + hide: "Ocultar coluna", + hideHint: "Os cartões vão para Sem categoria", + createIn: "Novo registro em {{column}}", + create: "Novo", + }, + laneStatistic: { + loadedOnly: "cartões carregados", + }, uncategorized: "Sem categoria", loadMore: "Carregar mais", columns: "colunas", @@ -2872,6 +2895,7 @@ const pt = { }, linkFilterRefused: 'O filtro deste link não foi aplicado. Ele cita um campo pelo qual você não pode filtrar aqui, então a lista mostra a visualização sem ele.', personalizedParts: { + kanban: "Configurações do quadro", filters: "Filtros", search: "Pesquisa", sort: "Ordenação", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 3b814bcf631..d55af6d586b 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1073,6 +1073,16 @@ const ru = { inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "Столбцы по", + kanbanLanes: "Видимые столбцы", + kanbanCardFields: "Поля карточки", + kanbanAddCardField: "Добавить поле", + kanbanShowFieldLabels: "Показывать названия полей", + kanbanHideEmptyFields: "Скрывать пустые поля", + kanbanSummary: "Итог по столбцу", + kanbanHiddenLanes: "Скрытые столбцы", + kanbanHiddenLanesHint: "Карточки скрытого столбца показываются в «Без категории».", viewName: 'Название представления', fields: 'Поля', fieldsShown: 'Показано: {{count}}', @@ -1118,6 +1128,19 @@ const ru = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "Действия со столбцом {{column}}", + collapse: "Свернуть столбец", + expand: "Развернуть столбец", + hide: "Скрыть столбец", + hideHint: "Карточки переместятся в «Без категории»", + createIn: "Новая запись в {{column}}", + create: "Создать", + }, + laneStatistic: { + loadedOnly: "загруженные карточки", + }, uncategorized: "Без категории", loadMore: "Загрузить ещё", columns: "колонок", @@ -2955,6 +2978,7 @@ const ru = { }, linkFilterRefused: 'Фильтр из этой ссылки не применён: в нём есть поле, по которому здесь нельзя фильтровать, поэтому список показан по представлению без него.', personalizedParts: { + kanban: "Настройки доски", filters: "Фильтры", search: "Поиск", sort: "Сортировка", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4c4e8822b9e..223c008a9d5 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1038,6 +1038,16 @@ const zh = { inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "分列字段", + kanbanLanes: "显示哪几列", + kanbanCardFields: "卡片上显示的字段", + kanbanAddCardField: "添加字段", + kanbanShowFieldLabels: "显示字段名", + kanbanHideEmptyFields: "隐藏空字段", + kanbanSummary: "列底统计", + kanbanHiddenLanes: "隐藏的列", + kanbanHiddenLanesHint: "隐藏的列里的卡片会显示在「未分类」。", viewName: '视图名称', fields: '字段', fieldsShown: '已显示 {{count}} 个', @@ -1081,6 +1091,19 @@ const zh = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "{{column}} 列的操作", + collapse: "折叠这一列", + expand: "展开这一列", + hide: "隐藏这一列", + hideHint: "这一列的卡片会移到「未分类」", + createIn: "在「{{column}}」新建", + create: "新建", + }, + laneStatistic: { + loadedOnly: "仅已加载的卡片", + }, addCard: '添加卡片', addColumn: '添加列', moveCard: '移动卡片', @@ -2888,6 +2911,7 @@ const zh = { }, linkFilterRefused: '此链接的筛选条件未应用:其中包含你在此处无法筛选的字段,因此列表按视图本身显示。', personalizedParts: { + kanban: "看板设置", filters: '筛选', search: '搜索', sort: '排序', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index a064abb5cca..e73353699ec 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1038,6 +1038,16 @@ const zhHant = { inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', // The list's Options menu. optionsMenu: { + // objectstack#36370 — a board's own settings. + kanbanLaneField: "分列欄位", + kanbanLanes: "顯示哪幾列", + kanbanCardFields: "卡片上顯示的欄位", + kanbanAddCardField: "新增欄位", + kanbanShowFieldLabels: "顯示欄位名", + kanbanHideEmptyFields: "隱藏空欄位", + kanbanSummary: "列底統計", + kanbanHiddenLanes: "隱藏的列", + kanbanHiddenLanesHint: "隱藏的列裡的卡片會顯示在「未分類」。", viewName: '檢視名稱', fields: '欄位', fieldsShown: '已顯示 {{count}} 個', @@ -1081,6 +1091,19 @@ const zhHant = { }, }, kanban: { + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and an empty lane's create row. + laneMenu: { + actions: "{{column}} 列的操作", + collapse: "摺疊這一列", + expand: "展開這一列", + hide: "隱藏這一列", + hideHint: "這一列的卡片會移到「未分類」", + createIn: "在「{{column}}」新建", + create: "新建", + }, + laneStatistic: { + loadedOnly: "僅已載入的卡片", + }, addCard: '新增卡片', addColumn: '新增列', moveCard: '移動卡片', @@ -2888,6 +2911,7 @@ const zhHant = { }, linkFilterRefused: '此連結的篩選條件未應用:其中包含你在此處無法篩選的欄位,因此列表按檢視本身顯示。', personalizedParts: { + kanban: "看板設定", filters: '篩選', search: '搜尋', sort: '排序', diff --git a/ui/packages/plugin-kanban/src/KanbanCardDisplay.ts b/ui/packages/plugin-kanban/src/KanbanCardDisplay.ts new file mode 100644 index 00000000000..1061ff1c924 --- /dev/null +++ b/ui/packages/plugin-kanban/src/KanbanCardDisplay.ts @@ -0,0 +1,33 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36370 — how a card draws its fields, as the view's kanban block + * says (`kanban.showFieldLabels`): with each field's name beside its value + * (the default, what every board drew before the key), or the values alone. + * + * A package-private channel, as `KanbanColumnSummary` is: `ObjectKanban` + * provides it from the node `ListView` builds, and a board without a provider + * draws the names, as before. (`kanban.hideEmptyFields` needs no channel: + * `ObjectKanban` builds the cards' field rows itself.) + * + * @module + */ + +import { createContext, useContext } from 'react'; + +export interface KanbanCardDisplay { + /** Whether a card names each field beside its value. */ + showFieldLabels: boolean; +} + +export const KanbanCardDisplayContext = createContext({ showFieldLabels: true }); + +export function useKanbanCardDisplay(): KanbanCardDisplay { + return useContext(KanbanCardDisplayContext); +} diff --git a/ui/packages/plugin-kanban/src/KanbanColumnSummary.ts b/ui/packages/plugin-kanban/src/KanbanColumnSummary.ts index 3705aa2bf06..dcd7a188ded 100644 --- a/ui/packages/plugin-kanban/src/KanbanColumnSummary.ts +++ b/ui/packages/plugin-kanban/src/KanbanColumnSummary.ts @@ -36,8 +36,16 @@ import { isEmptyValue } from '@object-ui/core'; * and every board whose node carries no `summarizeField` render the header * exactly as they did before. */ +/** + * objectstack#36370 — the lane statistics the board computes, the closed set + * the spec's `KanbanLaneSummarySchema` publishes (with `none`). An average, a + * minimum or a maximum over a lane that has loaded part of its cards is not + * even a bound, so those wait for a server-side lane read. + */ +export type KanbanLaneStatisticType = 'count' | 'sum'; + export interface KanbanColumnSummary { - /** The record field each lane totals — the view's `summarizeField`. */ + /** The record field each lane totals — the view's `summarizeField`. Empty for a count. */ field: string; /** The field's display label: the tooltip and the screen-reader name of the total. */ label: string; @@ -47,6 +55,16 @@ export interface KanbanColumnSummary { * field keeps its declared `scale`. No format code of its own. */ renderTotal: (total: number) => ReactNode; + /** + * objectstack#36370 — what the lane computes (absent ⇒ `sum`, the + * `summarizeField` total) and where it is drawn: `header`, beside the count + * (absent; the `summarizeField` total, as before), or `foot`, under the + * lane's cards (the view's `kanban.summary`). + */ + type?: KanbanLaneStatisticType; + placement?: 'header' | 'foot'; + /** The calculation's name at the foot (「Sum」, 「Count」), beside `label`. */ + typeLabel?: string; } export const KanbanColumnSummaryContext = createContext(null); @@ -102,3 +120,16 @@ export function sumLaneField( } return widest === 0 ? total : Number(total.toFixed(widest)); } + +/** + * objectstack#36370 — a lane's statistic over its cards: the count of cards, + * or the sum of `field` as {@link sumLaneField} reads it (`null` when a value + * is not a number). + */ +export function laneStatistic( + cards: ReadonlyArray>, + field: string, + type: KanbanLaneStatisticType, +): number | null { + return type === 'count' ? cards.length : sumLaneField(cards, field); +} diff --git a/ui/packages/plugin-kanban/src/KanbanImpl.tsx b/ui/packages/plugin-kanban/src/KanbanImpl.tsx index a89170ac2fb..97b579ce6c5 100644 --- a/ui/packages/plugin-kanban/src/KanbanImpl.tsx +++ b/ui/packages/plugin-kanban/src/KanbanImpl.tsx @@ -24,16 +24,18 @@ import { verticalListSortingStrategy, } from "@dnd-kit/sortable" import { CSS } from "@dnd-kit/utilities" -import { Avatar, AvatarFallback, AvatarImage, Badge, Card, CardHeader, CardTitle, CardDescription, CardContent, ScrollArea, Button, Input, useResizeObserver, DataEmptyState } from "@object-ui/components" +import { Avatar, AvatarFallback, AvatarImage, Badge, Card, CardHeader, CardTitle, CardDescription, CardContent, ScrollArea, Button, Input, useResizeObserver, DataEmptyState, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@object-ui/components" import { useHasDndProvider, useDnd, usePredicateScope } from "@object-ui/react" import { resolveConditionalFormatting } from "@object-ui/core" import type { KanbanConditionalFormattingRule } from "@object-ui/types" import type { KanbanCard, KanbanColumn } from './types' import { createSafeTranslation } from "@object-ui/i18n" -import { Plus, Sigma } from "lucide-react" +import { EyeOff, FoldHorizontal, MoreHorizontal, Plus, Sigma, UnfoldHorizontal } from "lucide-react" import { useKanbanRecordsSettled } from './KanbanRecordsSettled' -import { useKanbanColumnSummary, sumLaneField } from './KanbanColumnSummary' +import { useKanbanColumnSummary, sumLaneField, laneStatistic } from './KanbanColumnSummary' +import { useKanbanCardDisplay } from './KanbanCardDisplay' import { laneCount, useKanbanLanePaging } from './KanbanLanePaging' +import { readCollapsedLanes, useKanbanLaneMenu, writeCollapsedLanes } from './KanbanLaneMenu' import { ownerInitials, type KanbanCardOwner } from './KanbanCardOwner' import { createKanbanDndAnnouncer } from './kanbanDndAnnouncements' @@ -75,6 +77,16 @@ const useKanbanT = createSafeTranslation( // Why a lane refuses the dragged card (#27099), when the board's // `dropBlockedReason` gives no sentence of its own. 'kanban.dropBlocked': 'A card in {{from}} cannot be moved to {{to}}.', + // objectstack#36370 — the lane header's 「+」 and 「⋯」 menu, and the empty + // lane's create row, when the host asks for them (`KanbanLaneMenu.ts`). + 'kanban.laneMenu.actions': '{{column}} column actions', + 'kanban.laneMenu.collapse': 'Collapse column', + 'kanban.laneMenu.expand': 'Expand column', + 'kanban.laneMenu.hide': 'Hide column', + 'kanban.laneMenu.hideHint': 'Its cards move to Uncategorized', + 'kanban.laneMenu.createIn': 'New record in {{column}}', + 'kanban.laneMenu.create': 'New', + 'kanban.laneStatistic.loadedOnly': 'loaded cards', }, 'kanban.noCards', ) @@ -328,6 +340,8 @@ function SortableCard({ card, onCardClick, conditionalFormatting, objectFields } // `aria-disabled` (objectui#12082). const movable = React.useContext(KanbanCardsMovable) const opens = React.useContext(KanbanCardsOpenRecord) + // objectstack#36370 — `kanban.showFieldLabels: false` draws the values alone. + const { showFieldLabels } = useKanbanCardDisplay() // A card that neither drags nor opens (objectstack#33548) is no control: no // `button` role, no tab stop, no key activation and no hover-as-link face. // Its click still reaches `onCardClick`, which the host routes to nothing. @@ -449,7 +463,7 @@ function SortableCard({ card, onCardClick, conditionalFormatting, objectFields } className="flex min-w-0 items-baseline gap-1.5 text-foreground/85" title={cell.label || cell.field} > -
{cell.label || cell.field}
+ {showFieldLabels &&
{cell.label || cell.field}
}
{cell.node}
))} @@ -749,7 +763,8 @@ function LaneTotal({ className?: string }) { const summary = useKanbanColumnSummary() - if (!summary) return null + // objectstack#36370 — the view's lane statistic is drawn at the foot. + if (!summary || summary.placement === 'foot') return null const total = sumLaneField(cards, summary.field) if (total === null) return null return ( @@ -766,6 +781,156 @@ function LaneTotal({ ) } +/** + * objectstack#36370 — the view's lane statistic (`kanban.summary`), at the + * lane's foot: its calculation's name and its figure, 「Sum · Amount + * ¥1,200」. A count over a lane the board pages for itself is the server's + * count of the lane, and carries the windowed `+` where that is a floor. A sum + * covers the cards the lane holds: over a lane that holds more than it drew it + * is no bound (a value may be negative), so it says so in words, 「Sum · + * Amount · loaded cards」, rather than with a `+`. Renders nothing without + * the statistic, or while the figure is unknowable. + */ +function LaneFootStatistic({ + cards, + count, + partial, +}: { + cards: KanbanCard[] + /** The lane's count as its header writes it, for a `count`. */ + count: { count: number; atLeast: boolean } + partial: boolean +}) { + const { t } = useKanbanT() + const summary = useKanbanColumnSummary() + if (!summary || summary.placement !== 'foot' || !summary.type) return null + const isCount = summary.type === 'count' + const value = isCount ? count.count : laneStatistic(cards, summary.field, summary.type) + if (value === null) return null + const partialSum = !isCount && partial + const name = isCount + ? summary.typeLabel + : `${summary.typeLabel} · ${summary.label}${partialSum ? ` · ${t('kanban.laneStatistic.loadedOnly')}` : ''}` + return ( +
+ {name} + + {summary.renderTotal(value)} + {isCount && count.atLeast ? '+' : null} + +
+ ) +} + +/** + * objectstack#36370 — the lane header's 「+」 and 「⋯」, drawn only where the + * host asked for the lane menu (`KanbanLaneMenu.ts`). 「+」 opens the host's + * create form with this lane's value filled in; 「⋯」 collapses the lane (the + * reader's own, in this browser) or hides it (the view's lanes, in the list's + * draft). The `Uncategorized` lane has no value to fill in or to hide, so it + * offers the collapse alone. + */ +function LaneHeaderActions({ + column, + collapsed, + onToggleCollapse, +}: { + column: KanbanColumn + collapsed: boolean + onToggleCollapse?: () => void +}) { + const { t } = useKanbanT() + const laneMenu = useKanbanLaneMenu() + if (!laneMenu) return null + const laneId = String(column.id) + const takesActions = laneMenu.laneTakesActions(laneId) + const create = takesActions ? laneMenu.onCreateInLane : undefined + const hide = takesActions ? laneMenu.onHideLane : undefined + return ( +
+ {create && ( + + )} + + + + + + {onToggleCollapse && ( + onToggleCollapse()} data-kanban-lane-menu-collapse=""> + {collapsed + ? + )} + {hide && ( + hide(laneId)} data-kanban-lane-menu-hide="" className="items-start"> + + )} + + +
+ ) +} + +/** + * objectstack#36370 — the 「+ New」 row of an empty lane, under the same + * conditions as the header's 「+」. + */ +function LaneCreateRow({ column }: { column: KanbanColumn }) { + const { t } = useKanbanT() + const laneMenu = useKanbanLaneMenu() + const laneId = String(column.id) + const create = laneMenu && laneMenu.laneTakesActions(laneId) ? laneMenu.onCreateInLane : undefined + if (!create) return null + return ( + + ) +} + function KanbanColumnView({ column, cards, @@ -902,7 +1067,11 @@ function KanbanColumnView({ onToggleCollapse?.()} /> @@ -925,6 +1094,7 @@ function KanbanColumnView({ )} {/* A total over cards that have not arrived is the same false `0`. */} {!isCollapsed && !countPending && } + {!isCollapsed && } @@ -961,6 +1131,7 @@ function KanbanColumnView({ ))} + {safeCards.length === 0 && !countPending && } {/* objectui#12619 — the next page of this lane, at its foot. */} {lanePaging && lanePage?.hasMore && ( )) : null; + // objectstack#36370 — a board's own settings for 视图设置 and its lanes' + // 「⋯」 and 「+」: what the view's kanban block holds now (the host lays the + // list's draft over it), and the whole next block a change writes. Plain + // per-render values, not memos (AGENTS.md #10). + const kanbanBlock = currentView === 'kanban' ? kanbanBlockOf(schema) : undefined; + const boardLaneField = kanbanBlock ? kanbanLaneFieldOf(schema, objectDef) : undefined; + const writeKanban = kanbanBlock && onKanbanChange + ? (patch: Record) => { + // `undefined` here is "the block without this key": `null` on the wire. + onKanbanChange!(Object.fromEntries(Object.entries(patch).map(([key, value]) => [key, value === undefined ? null : value]))); + } + : undefined; + const boardLaneDef = boardLaneField + ? (objectDef?.fields as Record | undefined)?.[boardLaneField] + : undefined; + // The lanes the lane field offers: its options, in their own order, under + // the labels the board draws. A field with no options (a person, a linked + // record) has its lanes from the data, and the panel lists none. + const boardLaneOptions: Array<{ value: string; label: string }> = (() => { + const raw = Array.isArray(boardLaneDef?.options) ? (boardLaneDef!.options as unknown[]) : []; + const translated = schema.objectName && boardLaneField ? translateOptions(schema.objectName, boardLaneField, raw as any[]) : raw; + return (translated as Array<{ value?: unknown; label?: unknown } | string>).flatMap((option) => { + const value = typeof option === 'string' ? option : option?.value; + if (typeof value !== 'string' || value === '') return []; + const label = typeof option === 'object' && typeof option?.label === 'string' && option.label ? option.label : value; + return [{ value, label }]; + }); + })(); + const boardShownLanes: string[] = Array.isArray(kanbanBlock?.lanes) && kanbanBlock!.lanes.length > 0 + ? (kanbanBlock!.lanes as unknown[]).filter((v): v is string => typeof v === 'string') + : boardLaneOptions.map((o) => o.value); + // `lanes` is written only while it differs from every option in its own + // order: the view with no `lanes` draws exactly that. + const writeShownLanes = writeKanban + ? (lanes: string[]) => { + if (lanes.length === 0) return; + const all = boardLaneOptions.map((o) => o.value); + writeKanban({ lanes: lanes.length === all.length && lanes.every((v, i) => v === all[i]) ? undefined : lanes }); + } + : undefined; + const boardCardFields: string[] = Array.isArray(kanbanBlock?.columns) && kanbanBlock!.columns.length > 0 + ? (kanbanBlock!.columns as unknown[]).filter((v): v is string => typeof v === 'string') + : kanbanBlock + ? kanbanCardFieldsFromView(effectiveFields, [ + kanbanBlock.titleField, + resolveNameField(objectDef), + boardLaneField, + kanbanOwnerFieldOf(objectDef), + ]) + : []; + // The fields a card may show: the object's fields the caller may read and + // the definition does not hide, business ones first, then the system ones. + const boardCardFieldCandidates: ViewSettingsField[] = (() => { + if (!kanbanBlock) return []; + const defs = objectDef?.fields as Record | undefined; + if (!defs) return boardCardFields.map((name) => ({ name, label: tFieldLabel(name, name) })); + const candidates = Object.entries(defs).filter(([name]) => + !isDeclaredHidden(defs, name) && canReadField(perms, schema.objectName, name)); + const out: ViewSettingsField[] = []; + for (const tier of [false, true]) { + for (const [name, def] of candidates) { + if (isSystemManagedField(name, def) !== tier) continue; + out.push({ name, label: tFieldLabel(name, def?.label || name) }); + } + } + return out; + })(); + // The lane statistic the board draws: the view's `summary`, else the sum + // of its `summarizeField` (objectui#11629), else none. + const boardLaneStatistic: { type: string; field?: string } | null = (() => { + const own = kanbanBlock?.summary as { type?: unknown; field?: unknown } | undefined; + if (own && typeof own.type === 'string') { + return own.type === 'none' ? null : { type: own.type, ...(typeof own.field === 'string' ? { field: own.field } : {}) }; + } + return typeof kanbanBlock?.summarizeField === 'string' && kanbanBlock.summarizeField + ? { type: 'sum', field: kanbanBlock.summarizeField } + : null; + })(); + // The fields a lane may total: the object's number fields the + // caller may read. + const boardNumberFields: Array<{ value: string; label: string }> = kanbanBlock + ? Object.entries((objectDef?.fields ?? {}) as Record) + .filter(([name, def]) => + !!def && laneStatisticSums(def.type) && def.multiple !== true && def.hidden !== true + && canReadField(perms, schema.objectName, name)) + .map(([name, def]) => ({ value: name, label: tFieldLabel(name, def?.label || name) })) + : []; + const kanbanSettings: ViewSettingsKanban | undefined = kanbanBlock + ? { + laneField: boardLaneField, + // objectstack#36370 — the fields the board can lane on: a select or a + // radio, whose options are the lanes. A lookup, user, master-detail or + // tree field draws no sensible lanes yet (the board keys a lane on the + // stored value, and an expanded reference is an object), and a boolean + // has no options to title its lanes, so the picker leaves them out. + laneFieldOptions: groupOptions.filter((option) => { + const type = (objectDef?.fields as Record | undefined)?.[option.value]?.type; + return type === 'select' || type === 'radio'; + }), + // A new lane field draws every lane it offers: the lanes chosen on the + // old field name none of its values. + onLaneFieldChange: writeKanban ? (field) => writeKanban({ groupByField: field, lanes: undefined }) : undefined, + lanes: boardLaneOptions, + shownLanes: boardShownLanes, + onShownLanesChange: writeShownLanes, + cardFields: boardCardFields, + cardFieldCandidates: boardCardFieldCandidates, + onCardFieldsChange: writeKanban ? (fields) => writeKanban({ columns: fields }) : undefined, + // Both default to on: what every board drew before the keys. Turning + // one back on writes no key (the view's absence is "on"). + ...(writeKanban + ? { + showFieldLabels: { + value: kanbanBlock.showFieldLabels !== false, + onChange: (next: boolean) => writeKanban({ showFieldLabels: next ? undefined : false }), + }, + hideEmptyFields: { + value: kanbanBlock.hideEmptyFields !== false, + onChange: (next: boolean) => writeKanban({ hideEmptyFields: next ? undefined : false }), + }, + } + : {}), + summary: writeKanban + ? { + value: boardLaneStatistic, + numberFields: boardNumberFields, + // 「None」 over a view that sums `summarizeField` says so + // (`{ type: 'none' }`); over one that shows nothing, the key goes. + onChange: (next) => writeKanban({ + summary: next ?? (kanbanBlock.summarizeField ? { type: 'none' } : undefined), + }), + } + : undefined, + } + : undefined; + // The lane header's 「⋯」 and 「+」 (objectstack#36370, `KanbanLaneMenu.ts` in + // plugin-kanban): hiding a lane is unticking it here; 「+」 opens the host's + // create form on a new record carrying the lane's value, as the calendar's + // empty-day hand-off does (`onEdit` with a record that has no id). + const boardLaneValue = (laneId: string): unknown => { + const type = typeof boardLaneDef?.type === 'string' ? boardLaneDef.type : undefined; + if (type === 'boolean' || type === 'toggle') return laneId === 'true' ? true : laneId === 'false' ? false : laneId; + return laneId; + }; + const boardLaneMenu = kanbanBlock + ? { + // objectstack#36370 — each reader's own, per object and view. + collapseKey: schema.objectName + ? [filterScope.currentUserId || '-', schema.objectName, props.laneCollapseKey || schema.id || '-'].join(':') + : undefined, + onHideLane: writeShownLanes && boardLaneOptions.length > 0 + ? (laneId: string) => { + if (!boardShownLanes.includes(laneId) || boardShownLanes.length <= 1) return; + writeShownLanes(boardShownLanes.filter((v) => v !== laneId)); + } + : undefined, + onCreateInLane: props.onAddRecord && props.onEdit && boardLaneField + ? (laneId: string) => props.onEdit!({ [boardLaneField]: boardLaneValue(laneId) }) + : undefined, + } + : undefined; + // 视图设置's props, once: the desktop draws them as the popover beside the // view's name, the phone as the content of its bottom sheet // (objectstack#35883: a row of the view panel opens it there). @@ -7309,6 +7507,7 @@ export const ListView = React.forwardRef(({ { const type = (objectDef?.fields as Record | undefined)?.[name]?.type; return typeof type === 'string' ? type : undefined; @@ -8495,6 +8694,11 @@ export const ListView = React.forwardRef(({ // the board's host channel (a React prop, never a node key). ? { onRowGroupsChange: handleBoardRowGroups } : {})} + {...(viewComponentSchema.type === 'object-kanban' && boardLaneMenu + // objectstack#36370 — the lane header's 「⋯」 and 「+」, on the + // board's host channel (a React prop, never a node key). + ? { laneMenu: boardLaneMenu } + : {})} {...(viewComponentSchema.type === 'object-grid' && rowAdornment // objectui#13330 — the host's node beside each row's title, on // the grid's host channel (a React prop, never a node key). diff --git a/ui/packages/plugin-list/src/__tests__/ListView.kanbanSettings-36370.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.kanbanSettings-36370.test.tsx new file mode 100644 index 00000000000..4a074f72fcc --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.kanbanSettings-36370.test.tsx @@ -0,0 +1,145 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36370 — what `ListView` hands the board's 视图设置 and the lane + * header menu. + * + * Pinned here: + * - the lane field picker offers the option-backed fields only (a select or + * a radio): a lookup, a user or a boolean draws no sensible lanes yet; + * - the lane statistic sums what the aggregate table's `sum` row accepts + * (a number, a currency), never a percent, a formula or a boolean — the + * verdict `@objectstack/lint` gives `kanban.summary`; + * - the lane collapse key is the reader's own: `::`, the + * view named by the host's `laneCollapseKey`, else the schema's id, else + * its name; without a signed-in user it reads `-`. + */ + +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, waitFor, cleanup, fireEvent, screen } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { SchemaRendererProvider, FilterScopeProvider } from '@object-ui/react'; +import { ListView } from '../ListView'; + +const OBJECT = 'settings_deal'; + +const objectDef = { + name: OBJECT, + label: 'Deal', + fields: { + id: { name: 'id', type: 'text', label: 'Id' }, + name: { name: 'name', type: 'text', label: 'Name' }, + stage: { name: 'stage', type: 'select', label: 'Stage', options: [{ label: 'New', value: 'new' }, { label: 'Won', value: 'won' }] }, + tier: { name: 'tier', type: 'radio', label: 'Tier', options: [{ label: 'Gold', value: 'gold' }] }, + account: { name: 'account', type: 'lookup', label: 'Account', reference: 'account' }, + owner: { name: 'owner', type: 'user', label: 'Owner' }, + closed: { name: 'closed', type: 'boolean', label: 'Closed' }, + amount: { name: 'amount', type: 'currency', label: 'Amount' }, + seats: { name: 'seats', type: 'number', label: 'Seats' }, + rate: { name: 'rate', type: 'percent', label: 'Rate' }, + score: { name: 'score', type: 'formula', label: 'Score' }, + }, +}; + +const rows = [{ id: 'd1', name: 'Alpha', stage: 'new' }]; + +let laneMenus: Array | undefined> = []; + +ComponentRegistry.register( + 'object-kanban', + (props: Record) => { + laneMenus.push(props.laneMenu); + return
; + }, + { namespace: 'test', label: 'object-kanban spy', category: 'view' }, +); + +const makeDataSource = () => + ({ + find: vi.fn(async () => rows), + findOne: vi.fn(async () => null), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + count: vi.fn(async () => rows.length), + getObjectSchema: vi.fn(async () => objectDef), + getObjects: vi.fn(async () => []), + onMutation: () => () => {}, + }) as any; + +function mount(opts: { userId?: string; laneCollapseKey?: string; schemaExtras?: Record } = {}) { + laneMenus = []; + const list = ( + + {}} + /> + + ); + return render(opts.userId ? {list} : list); +} + +async function collapseKey(): Promise { + await waitFor(() => expect(laneMenus[laneMenus.length - 1]?.collapseKey).toBeDefined()); + return laneMenus[laneMenus.length - 1]?.collapseKey; +} + +afterEach(cleanup); + +describe('ListView on a board: the settings it offers (objectstack#36370)', () => { + it('offers only option-backed lane fields: a select and a radio', async () => { + mount(); + await waitFor(() => expect(screen.getByTestId('object-kanban-spy')).toBeTruthy()); + fireEvent.click(await screen.findByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-lane-field')); + expect(screen.getByTestId('options-lane-field-stage')).toBeTruthy(); + expect(screen.getByTestId('options-lane-field-tier')).toBeTruthy(); + for (const out of ['account', 'owner', 'closed', 'name', 'amount']) { + expect(screen.queryByTestId(`options-lane-field-${out}`)).toBeNull(); + } + }); + + it('offers a sum over the fields the aggregate table adds, and no percent, formula or boolean', async () => { + mount(); + await waitFor(() => expect(screen.getByTestId('object-kanban-spy')).toBeTruthy()); + fireEvent.click(await screen.findByTestId('toolbar-display-trigger')); + fireEvent.click(await screen.findByTestId('options-row-lane-summary')); + expect(screen.getByTestId('options-lane-summary-sum:amount')).toBeTruthy(); + expect(screen.getByTestId('options-lane-summary-sum:seats')).toBeTruthy(); + for (const out of ['rate', 'score', 'closed', 'name']) { + expect(screen.queryByTestId(`options-lane-summary-sum:${out}`)).toBeNull(); + } + }); + + it('keys lane collapse by the reader, the object and the view', async () => { + mount({ userId: 'u1', laneCollapseKey: 'pipeline' }); + expect(await collapseKey()).toBe(`u1:${OBJECT}:pipeline`); + cleanup(); + + // Another reader of the same board keeps their own. + mount({ userId: 'u2', laneCollapseKey: 'pipeline' }); + expect(await collapseKey()).toBe(`u2:${OBJECT}:pipeline`); + cleanup(); + + // Without the host's key the schema's own id names the view; signed out reads `-`. + mount({ schemaExtras: { id: 'board_view' } }); + expect(await collapseKey()).toBe(`-:${OBJECT}:board_view`); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.kanban-36370.test.tsx b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.kanban-36370.test.tsx new file mode 100644 index 00000000000..f55dbc5f781 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ViewSettingsPopover.kanban-36370.test.tsx @@ -0,0 +1,187 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36370 — 视图设置 on a board: the board's own settings in place + * of the table's. + * + * Pinned here: + * - the first level shows the lane field, 「5 / 7」 shown lanes, the card + * fields in place, the two card toggles and the lane statistic, and none + * of the table's 「Shown columns」, Group, Row height or Row colour; + * - the lane field level lists the fields offered and writes a pick; + * - the lanes level hides a lane, shows a hidden one at the end, and keeps + * the last lane (no eye on it); + * - the card fields hide in place, and 「+ Add field」 adds one at the end; + * - each toggle writes its next value; the statistic level offers none, + * count and a number field's sum (no average) and writes the pick (`null` + * for None); + * - the zh pack names every row. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import { I18nProvider, useObjectTranslation } from '@object-ui/i18n'; +import { + ViewSettingsPopover, + type ViewSettingsKanban, + type ViewSettingsPopoverProps, +} from '../components/ViewSettingsPopover'; + +afterEach(cleanup); + +const FIELDS = [ + { name: 'name', label: 'Name' }, + { name: 'stage', label: 'Stage' }, +]; + +function kanbanOf(overrides: Partial = {}): ViewSettingsKanban { + return { + laneField: 'stage', + laneFieldOptions: [{ value: 'stage', label: 'Stage' }, { value: 'owner', label: 'Owner' }], + onLaneFieldChange: vi.fn(), + lanes: [ + { value: 'new', label: 'New' }, + { value: 'proposal', label: 'Proposal' }, + { value: 'won', label: 'Won' }, + ], + shownLanes: ['new', 'proposal'], + onShownLanesChange: vi.fn(), + cardFields: ['amount', 'account'], + cardFieldCandidates: [ + { name: 'amount', label: 'Amount' }, + { name: 'account', label: 'Account' }, + { name: 'close_date', label: 'Close date' }, + ], + onCardFieldsChange: vi.fn(), + showFieldLabels: { value: true, onChange: vi.fn() }, + hideEmptyFields: { value: true, onChange: vi.fn() }, + summary: { + value: { type: 'sum', field: 'amount' }, + numberFields: [{ value: 'amount', label: 'Amount' }], + onChange: vi.fn(), + }, + ...overrides, + }; +} + +type Overrides = Partial>; + +function Harness(props: Overrides) { + const { t } = useObjectTranslation(); + return ( + string} + allFields={FIELDS} + showHideFields + hiddenFields={new Set()} + updateHiddenFields={() => {}} + showGroup + setGroupingConfig={() => {}} + showDensity + density={{ mode: 'comfortable', cycle: () => {}, setMode: () => {} }} + showColor + setRowColorConfig={() => {}} + {...props} + /> + ); +} + +function openMenu(props: Overrides, language = 'en') { + const view = render( + + + , + ); + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + return view; +} + +const value = (testId: string) => screen.getByTestId(`${testId}-value`).textContent; + +describe('视图设置 on a board (objectstack#36370)', () => { + it('shows the board settings and none of the table ones', () => { + openMenu({ kanban: kanbanOf() }); + expect(value('options-row-lane-field')).toBe('Stage'); + expect(value('options-row-lanes')).toBe('2 / 3'); + expect(screen.getByTestId('options-card-fields-list-row-amount')).toBeTruthy(); + expect(screen.getByTestId('options-toggle-field-labels')).toBeTruthy(); + expect(screen.getByTestId('options-toggle-hide-empty')).toBeTruthy(); + expect(value('options-row-lane-summary')).toBe('Sum · Amount'); + for (const gone of ['options-columns', 'options-row-group', 'options-row-row-height', 'options-row-color']) { + expect(screen.queryByTestId(gone)).toBeNull(); + } + }); + + it('picks another lane field', () => { + const kanban = kanbanOf(); + openMenu({ kanban }); + fireEvent.click(screen.getByTestId('options-row-lane-field')); + fireEvent.click(screen.getByTestId('options-lane-field-owner')); + expect(kanban.onLaneFieldChange).toHaveBeenCalledWith('owner'); + }); + + it('hides a lane, shows a hidden one at the end, and keeps the last lane', () => { + const kanban = kanbanOf(); + openMenu({ kanban }); + fireEvent.click(screen.getByTestId('options-row-lanes')); + // Lanes are no fields: their own heading over the hidden ones, no type icon. + expect(screen.getByTestId('options-page-lanes').textContent).toContain('Hidden columns'); + expect(screen.queryByTestId('options-lanes-icon')).toBeNull(); + fireEvent.click(screen.getByTestId('options-lanes-hide-new')); + expect(kanban.onShownLanesChange).toHaveBeenLastCalledWith(['proposal']); + fireEvent.click(screen.getByTestId('options-lanes-item-won')); + expect(kanban.onShownLanesChange).toHaveBeenLastCalledWith(['new', 'proposal', 'won']); + cleanup(); + + openMenu({ kanban: kanbanOf({ shownLanes: ['won'] }) }); + fireEvent.click(screen.getByTestId('options-row-lanes')); + expect(screen.queryByTestId('options-lanes-hide-won')).toBeNull(); + }); + + it('hides a card field in place and adds one at the end', () => { + const kanban = kanbanOf(); + openMenu({ kanban }); + fireEvent.click(screen.getByTestId('options-card-fields-list-hide-amount')); + expect(kanban.onCardFieldsChange).toHaveBeenLastCalledWith(['account']); + fireEvent.click(screen.getByTestId('options-add-card-field')); + fireEvent.click(screen.getByTestId('options-card-field-candidates-item-close_date')); + expect(kanban.onCardFieldsChange).toHaveBeenLastCalledWith(['amount', 'account', 'close_date']); + }); + + it('writes each toggle and the statistic', () => { + // The board counts today, so each pick below is a change (picking the + // current statistic writes nothing). + const kanban = kanbanOf({ + summary: { value: { type: 'count' }, numberFields: [{ value: 'amount', label: 'Amount' }], onChange: vi.fn() }, + }); + openMenu({ kanban }); + fireEvent.click(screen.getByTestId('options-toggle-field-labels-switch')); + expect(kanban.showFieldLabels!.onChange).toHaveBeenCalledWith(false); + fireEvent.click(screen.getByTestId('options-toggle-hide-empty-switch')); + expect(kanban.hideEmptyFields!.onChange).toHaveBeenCalledWith(false); + fireEvent.click(screen.getByTestId('options-row-lane-summary')); + fireEvent.click(screen.getByTestId('options-lane-summary-count')); + expect(kanban.summary!.onChange).not.toHaveBeenCalled(); + fireEvent.click(screen.getByTestId('options-row-lane-summary')); + // The board computes a count or a sum (`KanbanLaneSummarySchema`): no average. + expect(screen.queryByTestId('options-lane-summary-avg:amount')).toBeNull(); + fireEvent.click(screen.getByTestId('options-lane-summary-sum:amount')); + expect(kanban.summary!.onChange).toHaveBeenLastCalledWith({ type: 'sum', field: 'amount' }); + fireEvent.click(screen.getByTestId('options-row-lane-summary')); + fireEvent.click(screen.getByTestId('options-lane-summary-none')); + expect(kanban.summary!.onChange).toHaveBeenLastCalledWith(null); + }); + + it('names every board row in the zh pack', () => { + openMenu({ kanban: kanbanOf() }, 'zh'); + const text = screen.getByTestId('options-menu').textContent ?? ''; + for (const words of ['分列字段', '显示哪几列', '卡片上显示的字段', '添加字段', '显示字段名', '隐藏空字段', '列底统计']) { + expect(text).toContain(words); + } + }); +}); diff --git a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx index 1fa63db96c7..a460c6130f1 100644 --- a/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx +++ b/ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx @@ -37,6 +37,7 @@ import { SelectItem, SelectTrigger, SelectValue, + Switch, } from '@object-ui/components'; import { SlidersHorizontal, @@ -172,10 +173,66 @@ export interface ViewSettingsViewName { onRename?: (next: string) => boolean | Promise; } +/** One on/off setting of the panel: its value, and the writer of a change. */ +export interface ViewSettingsToggle { + value: boolean; + onChange: (next: boolean) => void; +} + +/** + * objectstack#36370 — a lane statistic as the board's `kanban.summary` holds + * it: one of the list footer's calculations (`ColumnSummary`), over `field` + * where the calculation reads one. `null` = none. + */ +export interface ViewSettingsKanbanSummaryValue { + type: string; + field?: string; +} + +/** + * objectstack#36370 — the board's own settings, which the panel shows IN + * PLACE OF the table's columns, grouping, row height and row colour while the + * view is a kanban. Every part is the view's (the host holds a change in the + * list's draft); the panel writes nothing itself. A part whose writer is + * absent is shown and not changed; a part that is absent is not shown. + */ +export interface ViewSettingsKanban { + /** The field the lanes come from, and the fields that may be it (objectstack#36204's range). */ + laneField?: string; + laneFieldOptions: ReadonlyArray<{ value: string; label: string }>; + onLaneFieldChange?: (field: string) => void; + /** Every lane the lane field offers, in its own order. */ + lanes: ReadonlyArray<{ value: string; label: string }>; + /** The lanes the board draws, in board order. */ + shownLanes: readonly string[]; + onShownLanesChange?: (lanes: string[]) => void; + /** The fields each card shows, in order, and the fields that may be added. */ + cardFields: readonly string[]; + cardFieldCandidates: readonly ViewSettingsField[]; + onCardFieldsChange?: (fields: string[]) => void; + /** Whether a card names each field beside its value. */ + showFieldLabels?: ViewSettingsToggle; + /** Whether a card leaves out a field that holds nothing. */ + hideEmptyFields?: ViewSettingsToggle; + /** The statistic each lane shows at its foot: none, a count, or a number field's sum or average. */ + summary?: { + value: ViewSettingsKanbanSummaryValue | null; + numberFields: ReadonlyArray<{ value: string; label: string }>; + onChange: (next: ViewSettingsKanbanSummaryValue | null) => void; + }; +} + export interface ViewSettingsPopoverProps { t: (key: string, opts?: any) => string; allFields: ViewSettingsField[]; + /** + * objectstack#36370 — the board's own settings. Present ⇒ the panel shows + * them instead of the table's 「Shown columns」, Group, Row height and Row + * colour; Layout, the name and the footer stay. + */ + kanban?: ViewSettingsKanban; + /** The view's name, at the top of the menu. Absent ⇒ no name row. */ viewName?: ViewSettingsViewName; @@ -276,7 +333,10 @@ export interface ViewSettingsPopoverProps { } /** The second levels of the menu; `root` is the menu itself. */ -type MenuPage = 'root' | 'layout' | 'fields' | 'group' | 'color' | 'rowHeight'; +type MenuPage = + | 'root' | 'layout' | 'fields' | 'group' | 'color' | 'rowHeight' + // objectstack#36370 — a board's second levels. + | 'laneField' | 'lanes' | 'cardFields' | 'laneSummary'; /** * One row of the menu: the setting's name on the left, its current value on @@ -579,6 +639,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen onExport, exportBusy, exportError, + kanban, } = props; // The panel opens on its first level every time: the content unmounts @@ -599,7 +660,7 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen const DensityIcon = density?.mode === 'compact' ? Rows4 : density?.mode === 'comfortable' ? Rows3 : Rows2; - const titles: Record, string> = { + const titles: Record<'layout' | 'fields' | 'group' | 'color' | 'rowHeight', string> = { layout: t('list.layout', { defaultValue: 'Layout' }), fields: t('list.optionsMenu.addColumn', { defaultValue: 'Add column' }), group: t('list.group', { defaultValue: 'Group' }), @@ -619,7 +680,161 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen ? orderFields(allFields, fieldOrder).filter((f) => !hiddenFields!.has(f.name)) : []; - const rootMenu = ( + // objectstack#36370 — a board's first level: its lane field, the lanes it + // shows, the card fields in place (drag to reorder, the eye to hide) with + // 「+ Add field」 one step away, the card toggles and the lane statistic. + // The table's columns, Group, Row height and Row colour are not offered. + const kanbanTitles = { + laneField: t('list.optionsMenu.kanbanLaneField', { defaultValue: 'Columns by' }), + lanes: t('list.optionsMenu.kanbanLanes', { defaultValue: 'Visible columns' }), + cardFields: t('list.optionsMenu.kanbanCardFields', { defaultValue: 'Card fields' }), + addCardField: t('list.optionsMenu.kanbanAddCardField', { defaultValue: 'Add field' }), + showFieldLabels: t('list.optionsMenu.kanbanShowFieldLabels', { defaultValue: 'Show field names' }), + hideEmptyFields: t('list.optionsMenu.kanbanHideEmptyFields', { defaultValue: 'Hide empty fields' }), + summary: t('list.optionsMenu.kanbanSummary', { defaultValue: 'Column summary' }), + }; + const kanbanFieldLabel = (name: string) => + kanban?.cardFieldCandidates.find((f) => f.name === name)?.label || fieldLabel(name); + const summaryWord = (type: string) => + type === 'count' + ? t('grid.summary.count', { defaultValue: 'Count' }) + : type === 'sum' + ? t('grid.summary.sum', { defaultValue: 'Sum' }) + : type; + const summaryText = (value: ViewSettingsKanbanSummaryValue | null): string => { + if (!value || value.type === 'none') return none; + if (!value.field || value.type === 'count') return summaryWord(value.type); + const label = kanban?.summary?.numberFields.find((f) => f.value === value.field)?.label || kanbanFieldLabel(value.field); + return `${summaryWord(value.type)} · ${label}`; + }; + const toggleRow = (label: string, toggle: ViewSettingsToggle, testId: string) => ( + + ); + const kanbanRootMenu = kanban ? ( +
+ {viewName && } +
+ o.value === kanban.laneField)?.label || fieldLabel(kanban.laneField) + : none} + onOpen={() => setPage('laneField')} + testId="options-row-lane-field" + /> + {kanban.lanes.length > 0 && ( + setPage('lanes')} + testId="options-row-lanes" + /> + )} +
+
+

{kanbanTitles.cardFields}

+ ({ value: name, label: kanbanFieldLabel(name), type: fieldType?.(name) }))} + shownFields={kanban.cardFields} + order={kanban.cardFields} + onOrderChange={kanban.onCardFieldsChange + ? (order) => kanban.onCardFieldsChange!(order.filter((name) => kanban.cardFields.includes(name))) + : undefined} + onHide={kanban.onCardFieldsChange + ? (name) => kanban.onCardFieldsChange!(kanban.cardFields.filter((n) => n !== name)) + : undefined} + searchable={false} + testId="options-card-fields-list" + className="w-full" + /> + {kanban.onCardFieldsChange && ( + + )} +
+ {(kanban.showFieldLabels || kanban.hideEmptyFields) && ( +
+ {kanban.showFieldLabels && toggleRow(kanbanTitles.showFieldLabels, kanban.showFieldLabels, 'options-toggle-field-labels')} + {kanban.hideEmptyFields && toggleRow(kanbanTitles.hideEmptyFields, kanban.hideEmptyFields, 'options-toggle-hide-empty')} +
+ )} +
+ {layout && ( + {layout(closeMenu)}} + onOpen={() => setPage('layout')} + testId="options-row-layout" + /> + )} + {kanban.summary && ( + setPage('laneSummary')} + testId="options-row-lane-summary" + /> + )} +
+
+ ) : null; + + /** A one-of-many level: each option a radio row, the current one ticked. */ + const radioLevel = ( + label: string, + options: ReadonlyArray<{ value: string; label: string }>, + current: string | undefined, + onPick: (value: string) => void, + testId: string, + ) => ( +
+ {options.map((option) => { + const active = option.value === current; + return ( + + ); + })} +
+ ); + + const rootMenu = kanbanRootMenu ?? (
{viewName && } {fieldsOffered && ( @@ -707,7 +922,109 @@ export function ViewSettingsContent(props: ViewSettingsPopoverProps & { closeMen ); let body: React.ReactNode = rootMenu; - if (page === 'layout' && layout) { + if (kanban && page === 'laneField') { + body = ( + + {kanban.laneFieldOptions.length > 0 + ? radioLevel(kanbanTitles.laneField, kanban.laneFieldOptions, kanban.laneField, (field) => { + if (field !== kanban.laneField) kanban.onLaneFieldChange?.(field); + back(); + }, 'options-lane-field') + : ( +

+ {t('list.noGroupableFields', { defaultValue: 'No field here can group the list' })} +

+ )} +
+ ); + } else if (kanban && page === 'lanes') { + const shown = kanban.shownLanes; + const write = kanban.onShownLanesChange; + body = ( + write([...shown, ...kanban.lanes.map((l) => l.value).filter((v) => !shown.includes(v))])} + data-testid="options-lanes-show-all" + > + {t('list.showAll', { defaultValue: 'Show all' })} + + ) + : undefined} + > + ({ value: lane.value, label: lane.label }))} + shownFields={shown} + order={shown} + onOrderChange={write ? (order) => write(order.filter((v) => shown.includes(v))) : undefined} + // The board keeps at least one lane: the last one shown has no eye. + onHide={write && shown.length > 1 ? (value) => write(shown.filter((v) => v !== value)) : undefined} + onShow={write ? (value) => write([...shown.filter((v) => v !== value), value]) : undefined} + searchable={kanban.lanes.length > 8} + hiddenTitle={t('list.optionsMenu.kanbanHiddenLanes', { defaultValue: 'Hidden columns' })} + // The view's lanes pick lanes, not records (#28211): say where a + // hidden lane's cards go. + footer={( +

+ {t('list.optionsMenu.kanbanHiddenLanesHint', { defaultValue: 'Cards of a hidden column show under Uncategorized.' })} +

+ )} + typeIcons={false} + testId="options-lanes" + className="w-full" + /> +
+ ); + } else if (kanban && page === 'cardFields' && kanban.onCardFieldsChange) { + const write = kanban.onCardFieldsChange; + const shown = kanban.cardFields; + body = ( + + ({ value: f.name, label: f.label || f.name, type: fieldType?.(f.name) }))} + shownFields={shown} + order={shown} + onOrderChange={(order) => write(order.filter((name) => shown.includes(name)))} + onHide={(name) => write(shown.filter((n) => n !== name))} + onShow={(name) => write([...shown.filter((n) => n !== name), name])} + testId="options-card-field-candidates" + className="w-full" + /> + + ); + } else if (kanban?.summary && page === 'laneSummary') { + const summary = kanban.summary; + const options: Array<{ value: string; label: string; pick: ViewSettingsKanbanSummaryValue | null }> = [ + { value: 'none', label: none, pick: null }, + { value: 'count', label: summaryWord('count'), pick: { type: 'count' } }, + // objectstack#36370 — what the board computes (`KanbanLaneSummarySchema`): + // a count, or a number field's sum. + ...summary.numberFields.map((f) => ({ + value: `sum:${f.value}`, + label: `${summaryWord('sum')} · ${f.label}`, + pick: { type: 'sum', field: f.value }, + })), + ]; + const current = !summary.value || summary.value.type === 'none' + ? 'none' + : summary.value.type === 'count' ? 'count' : `${summary.value.type}:${summary.value.field ?? ''}`; + body = ( + + {radioLevel(kanbanTitles.summary, options, current, (value) => { + const picked = options.find((o) => o.value === value); + if (picked && value !== current) summary.onChange(picked.pick); + back(); + }, 'options-lane-summary')} + + ); + } else if (page === 'layout' && layout) { body = ( {layout(closeMenu)} diff --git a/ui/packages/plugin-list/src/conditions/FieldList.tsx b/ui/packages/plugin-list/src/conditions/FieldList.tsx index 7ba19c00314..17f42b467ed 100644 --- a/ui/packages/plugin-list/src/conditions/FieldList.tsx +++ b/ui/packages/plugin-list/src/conditions/FieldList.tsx @@ -103,6 +103,12 @@ export interface FieldListProps { testId?: string; className?: string; autoFocus?: boolean; + /** + * objectstack#36370 — a list of things that are not fields (a board's + * lanes): its own heading over the hidden rows, and no field-type icon. + */ + hiddenTitle?: string; + typeIcons?: boolean; } const TYPE_ICONS: Readonly> = { @@ -213,6 +219,8 @@ export function FieldList({ testId = 'field-list', className, autoFocus = true, + hiddenTitle, + typeIcons = true, }: FieldListProps) { const { t } = useListConditionTranslation(); const [query, setQuery] = React.useState(''); @@ -296,7 +304,7 @@ export function FieldList({ const neighbour = (step: -1 | 1) => sections.shown[sections.shown.findIndex((f) => f.value === field.value) + step]; const body = ( <> -