@panneau/core 5.0.0-alpha.12 → 5.0.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,7 +79,9 @@ The form's methods that read the state (`form.getValue()`, `form.getErrors()`, `
79
79
  `createList(options)`, or `useList(options)`, manages:
80
80
 
81
81
  - **The query**: page, page size, sort, filters and search, with the list's defaults. Changing filters, search, sort or page size goes back to the first page.
82
+ - **The view**: the layout (`setLayout()`), the columns shown, in their order (`setColumns()`, `resetColumns()`), and the month of a calendar (`setMonth()`). It isn't sent to the backend. In the `calendar` layout of a list with a calendar, the query is the month's: its `date-range` filter set to the days around the month (`getCalendarRange()`), without a page ([0044](../../docs/decisions/0044-gallery-and-calendar.md)).
82
83
  - **The selection**: some ids, kept across pages, or every item matching the query except some (`selectAllMatching()`). `getSelection()` returns the protocol's `Selection` for an action. Changing filters or search clears it.
83
- - **URL sync** through a `Router`: `getSearch()`, `setSearch()` and `subscribe()`. Only values that differ from the defaults are written, next to the other parameters. `createHistoryRouter()` uses `window.history`; `createMemoryRouter()` keeps it in memory. `useList()` uses the provider's router unless given one, or `router: null`.
84
+ - **URL sync** through a `Router`: `getSearch()`, `setSearch()` and `subscribe()`. Only values that differ from the defaults are written, next to the other parameters. `createHistoryRouter()` uses `window.history`; `createMemoryRouter()` keeps it in memory. `useList()` uses the provider's router unless given one, or `router: null`. The view is in the URL too (`layout`, `columns`).
85
+ - **The remembered view**, with `remember: { key }`: the filters, sort, page size, layout and columns the user last chose, in `localStorage` (`createStorageViewStore()`) or another `ListViewStore`. A list that opens without any of its parameters in the URL shows it, and writes it to the URL; a URL with some opens as it is ([0042](../../docs/decisions/0042-list-view-columns-and-remembered-view.md)).
84
86
 
85
87
  The package layout, scripts and API reports are explained in [`docs/packages.md`](../../docs/packages.md).
@@ -1,9 +1,26 @@
1
- import type { Abilities, Action, ActionPlacement, Item } from '@panneau/protocol';
1
+ import type { Abilities, Action, ActionPlacement, Field, Item, Page } from '@panneau/protocol';
2
2
  /**
3
3
  * Whether a set of abilities allows something. Without abilities (a backend that sends none),
4
4
  * everything is allowed and the backend decides. With abilities, only what is `true` is allowed.
5
5
  */
6
6
  export declare function can(abilities: Abilities | undefined, ability: string): boolean;
7
+ /**
8
+ * Whether the current user can see a field (decision 0046): unless its `abilities.view` is
9
+ * `false`. A hidden field is left out of forms, details and lists.
10
+ */
11
+ export declare function canViewField(field: Pick<Field, 'abilities'>): boolean;
12
+ /**
13
+ * Whether the current user can edit a field (decision 0046): they can see it, and its
14
+ * `abilities.update` isn't `false`. A field they can't edit is read-only.
15
+ */
16
+ export declare function canUpdateField(field: Pick<Field, 'abilities'>): boolean;
17
+ /** The fields the current user can see, in their order. */
18
+ export declare function getVisibleFields<T extends Pick<Field, 'abilities'>>(fields: readonly T[]): T[];
19
+ /**
20
+ * Whether the current user can open a page of the definition (decision 0046): unless its
21
+ * `abilities.view` is `false`.
22
+ */
23
+ export declare function canViewPage(page: Pick<Page, 'abilities'>): boolean;
7
24
  /** Whether the current user can run an action on the resource (`abilities.run`). */
8
25
  export declare function canRunAction(action: Action): boolean;
9
26
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"abilities.d.ts","sourceRoot":"","sources":["../../src/definition/abilities.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAGlF;;;GAGG;AACH,wBAAgB,GAAG,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9E;AAED,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC7B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE;IAAE,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,GAAG,S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,IAAI,EAAE;IAAE,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,GAAG,SAAS,CAAA;CAAE,GACrD,OAAO,CAiBT;AAED,+EAA+E;AAC/E,wBAAgB,iBAAiB,CAC7B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,IAAI,EAAE,GACvB;IAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAAC,OAAO,EAAE,IAAI,EAAE,CAAA;CAAE,CAKtC;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,EAAE,CAcrE"}
@@ -7,6 +7,31 @@ import { ITEM_ACTION_ABILITIES, isBuiltInItemAction } from "@panneau/protocol/ru
7
7
  function can(abilities, ability) {
8
8
  return abilities === void 0 || abilities[ability] === true;
9
9
  }
10
+ /**
11
+ * Whether the current user can see a field (decision 0046): unless its `abilities.view` is
12
+ * `false`. A hidden field is left out of forms, details and lists.
13
+ */
14
+ function canViewField(field) {
15
+ return field.abilities?.view !== false;
16
+ }
17
+ /**
18
+ * Whether the current user can edit a field (decision 0046): they can see it, and its
19
+ * `abilities.update` isn't `false`. A field they can't edit is read-only.
20
+ */
21
+ function canUpdateField(field) {
22
+ return canViewField(field) && field.abilities?.update !== false;
23
+ }
24
+ /** The fields the current user can see, in their order. */
25
+ function getVisibleFields(fields) {
26
+ return fields.filter(canViewField);
27
+ }
28
+ /**
29
+ * Whether the current user can open a page of the definition (decision 0046): unless its
30
+ * `abilities.view` is `false`.
31
+ */
32
+ function canViewPage(page) {
33
+ return page.abilities?.view !== false;
34
+ }
10
35
  /** Whether the current user can run an action on the resource (`abilities.run`). */
11
36
  function canRunAction(action) {
12
37
  return action.abilities?.run !== false;
@@ -55,6 +80,6 @@ function getActionPlacements(action) {
55
80
  return [...placements];
56
81
  }
57
82
  //#endregion
58
- export { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction };
83
+ export { can, canRunAction, canUpdateField, canViewField, canViewPage, getActionPlacements, getVisibleFields, isActionAllowedOn, partitionByAction };
59
84
 
60
85
  //# sourceMappingURL=abilities.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"abilities.js","names":["Abilities","Action","ActionPlacement","Item","ITEM_ACTION_ABILITIES","isBuiltInItemAction","can","abilities","ability","undefined","canRunAction","action","run","isActionAllowedOn","item","id","kind","partitionByAction","items","allowed","skipped","forEach","push","getActionPlacements","placement","placements","Set","scope","add"],"sources":["../../src/definition/abilities.ts"],"sourcesContent":["import type { Abilities, Action, ActionPlacement, Item } from '@panneau/protocol';\nimport { ITEM_ACTION_ABILITIES, isBuiltInItemAction } from '@panneau/protocol/runtime';\n\n/**\n * Whether a set of abilities allows something. Without abilities (a backend that sends none),\n * everything is allowed and the backend decides. With abilities, only what is `true` is allowed.\n */\nexport function can(abilities: Abilities | undefined, ability: string): boolean {\n return abilities === undefined || abilities[ability] === true;\n}\n\n/** Whether the current user can run an action on the resource (`abilities.run`). */\nexport function canRunAction(action: Action): boolean {\n return action.abilities?.run !== false;\n}\n\n/**\n * Whether an action is available on an item: the user can run it, and the item allows it.\n * - The built-in item actions need their ability (decision 0040): `view` for `show`, `update` for\n * `edit`, `duplicate` and `delete`. A missing or false ability hides them, and so does their\n * own id set to `false` (`\"edit\": false`). An item without abilities shows none of them.\n * - Other links are allowed unless the item says otherwise (`\"site\": false`).\n * - Other actions need their id in the abilities of the item (`\"publish\": true`).\n * - On an item without abilities (a product's own records), other actions are allowed: the\n * backend decides.\n */\nexport function isActionAllowedOn(\n action: Action,\n item: { readonly abilities?: Abilities | undefined },\n): boolean {\n if (!canRunAction(action)) {\n return false;\n }\n const { abilities } = item;\n if (isBuiltInItemAction(action.id)) {\n return (\n abilities?.[ITEM_ACTION_ABILITIES[action.id]] === true && abilities[action.id] !== false\n );\n }\n if (abilities === undefined) {\n return true;\n }\n if (action.kind === 'link') {\n return abilities[action.id] !== false;\n }\n return abilities[action.id] === true;\n}\n\n/** Splits the items of a selection by whether an action is allowed on them. */\nexport function partitionByAction(\n action: Action,\n items: readonly Item[],\n): { allowed: Item[]; skipped: Item[] } {\n const allowed: Item[] = [];\n const skipped: Item[] = [];\n items.forEach((item) => (isActionAllowedOn(action, item) ? allowed : skipped).push(item));\n return { allowed, skipped };\n}\n\n/**\n * Where an action appears when it doesn't say: rows and forms (the header of an item, in its\n * panel and its form) for items, the toolbar otherwise.\n */\nexport function getActionPlacements(action: Action): ActionPlacement[] {\n if (action.placement !== undefined) {\n return action.placement;\n }\n const placements = new Set<ActionPlacement>();\n action.scope.forEach((scope) => {\n if (scope === 'item') {\n placements.add('row');\n placements.add('form');\n } else {\n placements.add('toolbar');\n }\n });\n return [...placements];\n}\n"],"mappings":";;;;;;AAOA,SAAgBM,IAAIC,WAAkCC,SAA0B;CAC5E,OAAOD,cAAcE,KAAAA,KAAaF,UAAUC,aAAa;AAC7D;;AAGA,SAAgBE,aAAaC,QAAyB;CAClD,OAAOA,OAAOJ,WAAWK,QAAQ;AACrC;;;;;;;;;;;AAYA,SAAgBC,kBACZF,QACAG,MACO;CACP,IAAI,CAACJ,aAAaC,MAAM,GACpB,OAAO;CAEX,MAAM,EAAEJ,cAAcO;CACtB,IAAIT,oBAAoBM,OAAOI,EAAE,GAC7B,OACIR,YAAYH,sBAAsBO,OAAOI,SAAS,QAAQR,UAAUI,OAAOI,QAAQ;CAG3F,IAAIR,cAAcE,KAAAA,GACd,OAAO;CAEX,IAAIE,OAAOK,SAAS,QAChB,OAAOT,UAAUI,OAAOI,QAAQ;CAEpC,OAAOR,UAAUI,OAAOI,QAAQ;AACpC;;AAGA,SAAgBE,kBACZN,QACAO,OACoC;CACpC,MAAMC,UAAkB,CAAA;CACxB,MAAMC,UAAkB,CAAA;CACxBF,MAAMG,SAASP,UAAUD,kBAAkBF,QAAQG,IAAI,IAAIK,UAAUC,QAAAA,CAASE,KAAKR,IAAI,CAAC;CACxF,OAAO;EAAEK;EAASC;CAAQ;AAC9B;;;;;AAMA,SAAgBG,oBAAoBZ,QAAmC;CACnE,IAAIA,OAAOa,cAAcf,KAAAA,GACrB,OAAOE,OAAOa;CAElB,MAAMC,6BAAa,IAAIC,IAAqB;CAC5Cf,OAAOgB,MAAMN,SAASM,UAAU;EAC5B,IAAIA,UAAU,QAAQ;GAClBF,WAAWG,IAAI,KAAK;GACpBH,WAAWG,IAAI,MAAM;EACzB,OACIH,WAAWG,IAAI,SAAS;CAEhC,CAAC;CACD,OAAO,CAAC,GAAGH,UAAU;AACzB"}
1
+ {"version":3,"file":"abilities.js","names":["Abilities","Action","ActionPlacement","Field","Item","Page","ITEM_ACTION_ABILITIES","isBuiltInItemAction","can","abilities","ability","undefined","canViewField","field","Pick","view","canUpdateField","update","getVisibleFields","fields","T","filter","canViewPage","page","canRunAction","action","run","isActionAllowedOn","item","id","kind","partitionByAction","items","allowed","skipped","forEach","push","getActionPlacements","placement","placements","Set","scope","add"],"sources":["../../src/definition/abilities.ts"],"sourcesContent":["import type { Abilities, Action, ActionPlacement, Field, Item, Page } from '@panneau/protocol';\nimport { ITEM_ACTION_ABILITIES, isBuiltInItemAction } from '@panneau/protocol/runtime';\n\n/**\n * Whether a set of abilities allows something. Without abilities (a backend that sends none),\n * everything is allowed and the backend decides. With abilities, only what is `true` is allowed.\n */\nexport function can(abilities: Abilities | undefined, ability: string): boolean {\n return abilities === undefined || abilities[ability] === true;\n}\n\n/**\n * Whether the current user can see a field (decision 0046): unless its `abilities.view` is\n * `false`. A hidden field is left out of forms, details and lists.\n */\nexport function canViewField(field: Pick<Field, 'abilities'>): boolean {\n return field.abilities?.view !== false;\n}\n\n/**\n * Whether the current user can edit a field (decision 0046): they can see it, and its\n * `abilities.update` isn't `false`. A field they can't edit is read-only.\n */\nexport function canUpdateField(field: Pick<Field, 'abilities'>): boolean {\n return canViewField(field) && field.abilities?.update !== false;\n}\n\n/** The fields the current user can see, in their order. */\nexport function getVisibleFields<T extends Pick<Field, 'abilities'>>(fields: readonly T[]): T[] {\n return fields.filter(canViewField);\n}\n\n/**\n * Whether the current user can open a page of the definition (decision 0046): unless its\n * `abilities.view` is `false`.\n */\nexport function canViewPage(page: Pick<Page, 'abilities'>): boolean {\n return page.abilities?.view !== false;\n}\n\n/** Whether the current user can run an action on the resource (`abilities.run`). */\nexport function canRunAction(action: Action): boolean {\n return action.abilities?.run !== false;\n}\n\n/**\n * Whether an action is available on an item: the user can run it, and the item allows it.\n * - The built-in item actions need their ability (decision 0040): `view` for `show`, `update` for\n * `edit`, `duplicate` and `delete`. A missing or false ability hides them, and so does their\n * own id set to `false` (`\"edit\": false`). An item without abilities shows none of them.\n * - Other links are allowed unless the item says otherwise (`\"site\": false`).\n * - Other actions need their id in the abilities of the item (`\"publish\": true`).\n * - On an item without abilities (a product's own records), other actions are allowed: the\n * backend decides.\n */\nexport function isActionAllowedOn(\n action: Action,\n item: { readonly abilities?: Abilities | undefined },\n): boolean {\n if (!canRunAction(action)) {\n return false;\n }\n const { abilities } = item;\n if (isBuiltInItemAction(action.id)) {\n return (\n abilities?.[ITEM_ACTION_ABILITIES[action.id]] === true && abilities[action.id] !== false\n );\n }\n if (abilities === undefined) {\n return true;\n }\n if (action.kind === 'link') {\n return abilities[action.id] !== false;\n }\n return abilities[action.id] === true;\n}\n\n/** Splits the items of a selection by whether an action is allowed on them. */\nexport function partitionByAction(\n action: Action,\n items: readonly Item[],\n): { allowed: Item[]; skipped: Item[] } {\n const allowed: Item[] = [];\n const skipped: Item[] = [];\n items.forEach((item) => (isActionAllowedOn(action, item) ? allowed : skipped).push(item));\n return { allowed, skipped };\n}\n\n/**\n * Where an action appears when it doesn't say: rows and forms (the header of an item, in its\n * panel and its form) for items, the toolbar otherwise.\n */\nexport function getActionPlacements(action: Action): ActionPlacement[] {\n if (action.placement !== undefined) {\n return action.placement;\n }\n const placements = new Set<ActionPlacement>();\n action.scope.forEach((scope) => {\n if (scope === 'item') {\n placements.add('row');\n placements.add('form');\n } else {\n placements.add('toolbar');\n }\n });\n return [...placements];\n}\n"],"mappings":";;;;;;AAOA,SAAgBQ,IA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ASM,UAAU;EAC5B,IAAIA,UAAU,QAAQ;GAClBF,WAAWG,IAAI,KAAK;GACpBH,WAAWG,IAAI,MAAM;EACzB,OACIH,WAAWG,IAAI,SAAS;CAEhC,CAAC;CACD,OAAO,CAAC,GAAGH,UAAU;AACzB"}
@@ -23,7 +23,11 @@ export interface ResolveFormOptions {
23
23
  /** The type of the item, among the resource's `types`: its fields are added. */
24
24
  type?: string;
25
25
  }
26
- /** Resolves fields and a layout into a form. */
26
+ /**
27
+ * Resolves fields and a layout into a form. Fields the current user can't see
28
+ * (`abilities.view: false`) are left out, and those they can't edit (`abilities.update: false`)
29
+ * are read-only (decision 0046).
30
+ */
27
31
  export declare function resolveFields(fields: readonly Field[], layout?: readonly LayoutNode[], { mode }?: Pick<ResolveFormOptions, 'mode'>): ResolvedForm;
28
32
  /** Resolves the form of a resource: its fields (plus those of the item's type) and its layout. */
29
33
  export declare function resolveForm(resource: Resource, options?: ResolveFormOptions): ResolvedForm;
@@ -1 +1 @@
1
- {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/definition/form.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAQ,MAAM,mBAAmB,CAAC;AAE3E,qDAAqD;AACrD,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE3C,yFAAyF;AACzF,MAAM,WAAW,YAAY;IACzB,mDAAmD;IACnD,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,2BAA2B;IAC3B,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACzC;;;OAGG;IACH,MAAM,EAAE,UAAU,EAAE,CAAC;CACxB;AAED,MAAM,WAAW,kBAAkB;IAC/B;;;;OAIG;IACH,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AA2DD,gDAAgD;AAChD,wBAAgB,aAAa,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AAG,YAAY,CAM9F;AAED,qDAAqD;AACrD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,GAAG,MAAM,EAAE,CAE3E"}
@@ -1,3 +1,4 @@
1
+ import { canUpdateField, canViewField } from "./abilities.js";
1
2
  //#region src/definition/form.ts
2
3
  function referencedNames(nodes, names = /* @__PURE__ */ new Set()) {
3
4
  nodes.forEach((node) => {
@@ -36,9 +37,18 @@ function resolveFieldRules(field, mode) {
36
37
  }));
37
38
  return resolved;
38
39
  }
39
- /** Resolves fields and a layout into a form. */
40
+ /**
41
+ * Resolves fields and a layout into a form. Fields the current user can't see
42
+ * (`abilities.view: false`) are left out, and those they can't edit (`abilities.update: false`)
43
+ * are read-only (decision 0046).
44
+ */
40
45
  function resolveFields(fields, layout = [], { mode } = {}) {
41
- const resolved = fields.flatMap((field) => {
46
+ const resolved = fields.flatMap((declared) => {
47
+ if (!canViewField(declared)) return [];
48
+ const field = canUpdateField(declared) ? declared : {
49
+ ...declared,
50
+ readOnly: true
51
+ };
42
52
  if (mode === void 0) return [field];
43
53
  if (mode === "create" && field.updateOnly === true) return [];
44
54
  const withRules = resolveFieldRules(field, mode);
@@ -1 +1 @@
1
- {"version":3,"file":"form.js","names":["Field","LayoutNode","Resource","Rule","FormMode","ResolvedForm","fields","fieldsByName","ReadonlyMap","layout","ResolveFormOptions","mode","type","referencedNames","nodes","names","Set","forEach","node","name","undefined","add","children","pruneLayout","flatMap","has","resolveRules","rules","rule","_mode","resolved","resolveFieldRules","field","map","nested","types","resolveFields","Pick","updateOnly","withRules","createOnly","readOnly","Map","pruned","referenced","appended","filter","resolveForm","resource","options","typeFields","find","id","form","getLayoutFieldNames"],"sources":["../../src/definition/form.ts"],"sourcesContent":["import type { Field, LayoutNode, Resource, Rule } from '@panneau/protocol';\n\n/** Whether a form creates an item or updates one. */\nexport type FormMode = 'create' | 'update';\n\n/** A form ready to render: its fields and a layout that references every one of them. */\nexport interface ResolvedForm {\n /** The fields of the form, in definition order. */\n fields: Field[];\n /** The fields, by name. */\n fieldsByName: ReadonlyMap<string, Field>;\n /**\n * The layout tree. Field nodes that name an unknown field are removed, and fields that no\n * node references are appended at the end, as `field` nodes.\n */\n layout: LayoutNode[];\n}\n\nexport interface ResolveFormOptions {\n /**\n * `create` removes `updateOnly` fields; `update` makes `createOnly` fields read-only. Rules\n * limited to a mode (`{ \"rule\": \"required\", \"mode\": \"create\" }`) are kept, without their\n * `mode`, in that mode only, in nested fields too. Without a mode, every field is kept as is.\n */\n mode?: FormMode;\n /** The type of the item, among the resource's `types`: its fields are added. */\n type?: string;\n}\n\nfunction referencedNames(nodes: readonly LayoutNode[], names = new Set<string>()): Set<string> {\n nodes.forEach((node) => {\n if (node.type === 'field' && node.name !== undefined) {\n names.add(node.name);\n }\n referencedNames(node.children ?? [], names);\n });\n return names;\n}\n\nfunction pruneLayout(\n nodes: readonly LayoutNode[],\n fields: ReadonlyMap<string, Field>,\n): LayoutNode[] {\n return nodes.flatMap((node) => {\n if (node.type === 'field' && (node.name === undefined || !fields.has(node.name))) {\n return [];\n }\n if (node.children === undefined) {\n return [node];\n }\n return [{ ...node, children: pruneLayout(node.children, fields) }];\n });\n}\n\n/** The rules that apply in the mode, without their `mode`. */\nfunction resolveRules(rules: readonly Rule[], mode: FormMode): Rule[] {\n return rules.flatMap((rule) => {\n if (rule.mode === undefined) {\n return [rule];\n }\n if (rule.mode !== mode) {\n return [];\n }\n const { mode: _mode, ...resolved } = rule;\n return [resolved as Rule];\n });\n}\n\n/** A field with the rules of the mode, and those of its nested fields and block types. */\nfunction resolveFieldRules(field: Field, mode: FormMode): Field {\n const resolved: Field = { ...field };\n if (field.rules !== undefined) {\n resolved.rules = resolveRules(field.rules, mode);\n }\n if (field.fields !== undefined) {\n resolved.fields = field.fields.map((nested) => resolveFieldRules(nested, mode));\n }\n if (field.types !== undefined) {\n resolved.types = field.types.map((type) => ({\n ...type,\n fields: type.fields.map((nested) => resolveFieldRules(nested, mode)),\n }));\n }\n return resolved;\n}\n\n/** Resolves fields and a layout into a form. */\nexport function resolveFields(\n fields: readonly Field[],\n layout: readonly LayoutNode[] = [],\n { mode }: Pick<ResolveFormOptions, 'mode'> = {},\n): ResolvedForm {\n const resolved = fields.flatMap((field) => {\n if (mode === undefined) {\n return [field];\n }\n if (mode === 'create' && field.updateOnly === true) {\n return [];\n }\n const withRules = resolveFieldRules(field, mode);\n if (mode === 'update' && field.createOnly === true) {\n return [{ ...withRules, readOnly: true }];\n }\n return [withRules];\n });\n const fieldsByName = new Map(resolved.map((field) => [field.name, field]));\n const pruned = pruneLayout(layout, fieldsByName);\n const referenced = referencedNames(pruned);\n const appended: LayoutNode[] = resolved\n .filter((field) => !referenced.has(field.name))\n .map((field) => ({ type: 'field', name: field.name }));\n return { fields: resolved, fieldsByName, layout: [...pruned, ...appended] };\n}\n\n/** Resolves the form of a resource: its fields (plus those of the item's type) and its layout. */\nexport function resolveForm(resource: Resource, options: ResolveFormOptions = {}): ResolvedForm {\n const typeFields =\n options.type !== undefined\n ? (resource.types?.find((type) => type.id === options.type)?.fields ?? [])\n : [];\n return resolveFields([...resource.fields, ...typeFields], resource.form?.layout ?? [], options);\n}\n\n/** The field names a layout references, in order. */\nexport function getLayoutFieldNames(layout: readonly LayoutNode[]): string[] {\n return [...referencedNames(layout)];\n}\n"],"mappings":";AA6BA,SAASa,gBAAgBC,OAA8BC,wBAAQ,IAAIC,IAAY,GAAgB;CAC3FF,MAAMG,SAASC,SAAS;EACpB,IAAIA,KAAKN,SAAS,WAAWM,KAAKC,SAASC,KAAAA,GACvCL,MAAMM,IAAIH,KAAKC,IAAI;EAEvBN,gBAAgBK,KAAKI,YAAY,CAAA,GAAIP,KAAK;CAC9C,CAAC;CACD,OAAOA;AACX;AAEA,SAASQ,YACLT,OACAR,QACY;CACZ,OAAOQ,MAAMU,SAASN,SAAS;EAC3B,IAAIA,KAAKN,SAAS,YAAYM,KAAKC,SAASC,KAAAA,KAAa,CAACd,OAAOmB,IAAIP,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AC/C,IAAIA,SAAS,YAAYqB,MAAMQ,eAAe,MAC1C,OAAO,CAAC;GAAE,GAAGD;GAAWE,UAAU;EAAK,CAAC;EAE5C,OAAO,CAACF,SAAS;CACrB,CAAC;CACD,MAAMhC,eAAe,IAAImC,IAAIZ,SAASG,KAAKD,UAAU,CAACA,MAAMb,MAAMa,KAAK,CAAC,CAAC;CACzE,MAAMW,SAASpB,YAAYd,QAAQF,YAAY;CAC/C,MAAMqC,aAAa/B,gBAAgB8B,MAAM;CACzC,MAAME,WAAyBf,SAC1BgB,QAAQd,UAAU,CAACY,WAAWnB,IAAIO,MAAMb,IAAI,CAAC,CAAC,CAC9Cc,KAAKD,WAAW;EAAEpB,MAAM;EAASO,MAAMa,MAAMb;CAAK,EAAE;CACzD,OAAO;EAAEb,QAAQwB;EAAUvB;EAAcE,QAAQ,CAAC,GAAGkC,QAAQ,GAAGE,QAAQ;CAAE;AAC9E;;AAGA,SAAgBE,YAAYC,UAAoBC,UAA8B,CAAC,GAAiB;CAC5F,MAAMC,aACFD,QAAQrC,SAASQ,KAAAA,IACV4B,SAASb,OAAOgB,MAAMvC,SAASA,KAAKwC,OAAOH,QAAQrC,IAAI,CAAC,EAAEN,UAAU,CAAA,IACrE,CAAA;CACV,OAAO8B,cAAc,CAAC,GAAGY,SAAS1C,QAAQ,GAAG4C,UAAU,GAAGF,SAASK,MAAM5C,UAAU,CAAA,GAAIwC,OAAO;AAClG;;AAGA,SAAgBK,oBAAoB7C,QAAyC;CACzE,OAAO,CAAC,GAAGI,gBAAgBJ,MAAM,CAAC;AACtC"}
1
+ {"version":3,"file":"form.js","names":["Field","LayoutNode","Resource","Rule","canUpdateField","canViewField","FormMode","ResolvedForm","fields","fieldsByName","ReadonlyMap","layout","ResolveFormOptions","mode","type","referencedNames","nodes","names","Set","forEach","node","name","undefined","add","children","pruneLayout","flatMap","has","resolveRules","rules","rule","_mode","resolved","resolveFieldRules","field","map","nested","types","resolveFields","Pick","declared","readOnly","updateOnly","withRules","createOnly","Map","pruned","referenced","appended","filter","resolveForm","resource","options","typeFields","find","id","form","getLayoutFieldNames"],"sources":["../../src/definition/form.ts"],"sourcesContent":["import type { Field, LayoutNode, Resource, Rule } from '@panneau/protocol';\n\nimport { canUpdateField, canViewField } from './abilities';\n\n/** Whether a form creates an item or updates one. */\nexport type FormMode = 'create' | 'update';\n\n/** A form ready to render: its fields and a layout that references every one of them. */\nexport interface ResolvedForm {\n /** The fields of the form, in definition order. */\n fields: Field[];\n /** The fields, by name. */\n fieldsByName: ReadonlyMap<string, Field>;\n /**\n * The layout tree. Field nodes that name an unknown field are removed, and fields that no\n * node references are appended at the end, as `field` nodes.\n */\n layout: LayoutNode[];\n}\n\nexport interface ResolveFormOptions {\n /**\n * `create` removes `updateOnly` fields; `update` makes `createOnly` fields read-only. Rules\n * limited to a mode (`{ \"rule\": \"required\", \"mode\": \"create\" }`) are kept, without their\n * `mode`, in that mode only, in nested fields too. Without a mode, every field is kept as is.\n */\n mode?: FormMode;\n /** The type of the item, among the resource's `types`: its fields are added. */\n type?: string;\n}\n\nfunction referencedNames(nodes: readonly LayoutNode[], names = new Set<string>()): Set<string> {\n nodes.forEach((node) => {\n if (node.type === 'field' && node.name !== undefined) {\n names.add(node.name);\n }\n referencedNames(node.children ?? [], names);\n });\n return names;\n}\n\nfunction pruneLayout(\n nodes: readonly LayoutNode[],\n fields: ReadonlyMap<string, Field>,\n): LayoutNode[] {\n return nodes.flatMap((node) => {\n if (node.type === 'field' && (node.name === undefined || !fields.has(node.name))) {\n return [];\n }\n if (node.children === undefined) {\n return [node];\n }\n return [{ ...node, children: pruneLayout(node.children, fields) }];\n });\n}\n\n/** The rules that apply in the mode, without their `mode`. */\nfunction resolveRules(rules: readonly Rule[], mode: FormMode): Rule[] {\n return rules.flatMap((rule) => {\n if (rule.mode === undefined) {\n return [rule];\n }\n if (rule.mode !== mode) {\n return [];\n }\n const { mode: _mode, ...resolved } = rule;\n return [resolved as Rule];\n });\n}\n\n/** A field with the rules of the mode, and those of its nested fields and block types. */\nfunction resolveFieldRules(field: Field, mode: FormMode): Field {\n const resolved: Field = { ...field };\n if (field.rules !== undefined) {\n resolved.rules = resolveRules(field.rules, mode);\n }\n if (field.fields !== undefined) {\n resolved.fields = field.fields.map((nested) => resolveFieldRules(nested, mode));\n }\n if (field.types !== undefined) {\n resolved.types = field.types.map((type) => ({\n ...type,\n fields: type.fields.map((nested) => resolveFieldRules(nested, mode)),\n }));\n }\n return resolved;\n}\n\n/**\n * Resolves fields and a layout into a form. Fields the current user can't see\n * (`abilities.view: false`) are left out, and those they can't edit (`abilities.update: false`)\n * are read-only (decision 0046).\n */\nexport function resolveFields(\n fields: readonly Field[],\n layout: readonly LayoutNode[] = [],\n { mode }: Pick<ResolveFormOptions, 'mode'> = {},\n): ResolvedForm {\n const resolved = fields.flatMap((declared): Field[] => {\n if (!canViewField(declared)) {\n return [];\n }\n const field = canUpdateField(declared) ? declared : { ...declared, readOnly: true };\n if (mode === undefined) {\n return [field];\n }\n if (mode === 'create' && field.updateOnly === true) {\n return [];\n }\n const withRules = resolveFieldRules(field, mode);\n if (mode === 'update' && field.createOnly === true) {\n return [{ ...withRules, readOnly: true }];\n }\n return [withRules];\n });\n const fieldsByName = new Map(resolved.map((field) => [field.name, field]));\n const pruned = pruneLayout(layout, fieldsByName);\n const referenced = referencedNames(pruned);\n const appended: LayoutNode[] = resolved\n .filter((field) => !referenced.has(field.name))\n .map((field) => ({ type: 'field', name: field.name }));\n return { fields: resolved, fieldsByName, layout: [...pruned, ...appended] };\n}\n\n/** Resolves the form of a resource: its fields (plus those of the item's type) and its layout. */\nexport function resolveForm(resource: Resource, options: ResolveFormOptions = {}): ResolvedForm {\n const typeFields =\n options.type !== undefined\n ? (resource.types?.find((type) => type.id === options.type)?.fields ?? [])\n : [];\n return resolveFields([...resource.fields, ...typeFields], resource.form?.layout ?? [], options);\n}\n\n/** The field names a layout references, in order. */\nexport function getLayoutFieldNames(layout: readonly LayoutNode[]): string[] {\n return [...referenc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AAAA,IACV6B,SAASd,OAAOiB,MAAMxC,SAASA,KAAKyC,OAAOH,QAAQtC,IAAI,CAAC,EAAEN,UAAU,CAAA,IACrE,CAAA;CACV,OAAO8B,cAAc,CAAC,GAAGa,SAAS3C,QAAQ,GAAG6C,UAAU,GAAGF,SAASK,MAAM7C,UAAU,CAAA,GAAIyC,OAAO;AAClG;;AAGA,SAAgBK,oBAAoB9C,QAAyC;CACzE,OAAO,CAAC,GAAGI,gBAAgBJ,MAAM,CAAC;AACtC"}
@@ -11,6 +11,19 @@ export interface ResolvedColumn {
11
11
  sortable: boolean;
12
12
  width?: number | string;
13
13
  align?: 'start' | 'center' | 'end';
14
+ /** Not shown until the user shows it (decision 0042). */
15
+ hidden: boolean;
16
+ /** Whether the user can hide it. */
17
+ hideable: boolean;
18
+ }
19
+ /** The calendar of a list (decision 0044). */
20
+ export interface ResolvedCalendar {
21
+ /** The `date` or `datetime` field each item is shown on the day of. */
22
+ field: string;
23
+ /** The id of the `date-range` filter the calendar asks for a month through. */
24
+ filter: string;
25
+ /** How many items the calendar asks for a month. */
26
+ perPage: number;
14
27
  }
15
28
  /** A list ready to render. */
16
29
  export interface ResolvedList {
@@ -34,8 +47,12 @@ export interface ResolvedList {
34
47
  selectable: boolean;
35
48
  /** Actions the user can run, by placement. */
36
49
  actions: Record<ActionPlacement, Action[]>;
50
+ /** The calendar of the list, for its `calendar` layout, or `null`. */
51
+ calendar: ResolvedCalendar | null;
37
52
  }
38
53
  export declare const DEFAULT_PER_PAGE = 20;
54
+ /** How many items a calendar asks for a month, without its own `perPage`. */
55
+ export declare const DEFAULT_CALENDAR_PER_PAGE = 100;
39
56
  /** Groups the actions the user can run by placement. */
40
57
  export declare function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]>;
41
58
  /**
@@ -54,7 +71,9 @@ export declare function getResourceActions(resource: Resource): Action[];
54
71
  export declare function getOpenMode(resource: Resource): 'panel' | 'edit';
55
72
  /**
56
73
  * Resolves the list of a resource. Without columns, it shows the item title and the next fields
57
- * (up to four, skipping groups, repeaters and rich text).
74
+ * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see
75
+ * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit
76
+ * aren't edited inline (decision 0046).
58
77
  */
59
78
  export declare function resolveList(resource: Resource): ResolvedList;
60
79
  //# sourceMappingURL=list.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/definition/list.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAU,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AASlG,gCAAgC;AAChC,MAAM,WAAW,cAAc;IAC3B,yDAAyD;IACzD,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,wFAAwF;IACxF,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,KAAK,CAAC;CACtC;AAED,8BAA8B;AAC9B,MAAM,WAAW,YAAY;IACzB,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,wCAAwC;IACxC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,+EAA+E;IAC/E,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,8CAA8C;IAC9C,MAAM,EAAE,OAAO,CAAC;IAChB,qDAAqD;IACrD,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,gGAAgG;IAChG,UAAU,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC/B,mCA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Q,EAAE,QAAQ,GAAG,OAAO,GAAG,MAAM,CAEhE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,YAAY,CA4D5D"}
@@ -1,4 +1,4 @@
1
- import { canRunAction, getActionPlacements } from "./abilities.js";
1
+ import { canRunAction, canUpdateField, canViewField, getActionPlacements } from "./abilities.js";
2
2
  import { BUILT_IN_ITEM_ACTIONS, isBuiltInItemAction } from "@panneau/protocol/runtime";
3
3
  //#region src/definition/list.ts
4
4
  /** Fields shown when the list declares no columns. */
@@ -9,9 +9,11 @@ var NON_COLUMN_TYPES = /* @__PURE__ */ new Set([
9
9
  "richtext"
10
10
  ]);
11
11
  var DEFAULT_PER_PAGE = 20;
12
+ /** How many items a calendar asks for a month, without its own `perPage`. */
13
+ var DEFAULT_CALENDAR_PER_PAGE = 100;
12
14
  function columnsFromFields(resource) {
13
15
  const title = resource.itemTitle;
14
- const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type));
16
+ const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type) && canViewField(field));
15
17
  return (title !== void 0 ? [...fields.filter((field) => field.name === title), ...fields.filter((field) => field.name !== title)] : fields).slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));
16
18
  }
17
19
  /** Groups the actions the user can run by placement. */
@@ -88,13 +90,16 @@ function getOpenMode(resource) {
88
90
  }
89
91
  /**
90
92
  * Resolves the list of a resource. Without columns, it shows the item title and the next fields
91
- * (up to four, skipping groups, repeaters and rich text).
93
+ * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see
94
+ * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit
95
+ * aren't edited inline (decision 0046).
92
96
  */
93
97
  function resolveList(resource) {
94
98
  const list = resource.list ?? {};
95
99
  const fields = new Map(resource.fields.map((field) => [field.name, field]));
96
- const sorts = list.sorts ?? [];
97
- const columns = (list.columns ?? columnsFromFields(resource)).map((column) => {
100
+ const hidden = new Set(resource.fields.filter((field) => !canViewField(field)).map((field) => field.name));
101
+ const sorts = (list.sorts ?? []).filter((sort) => !hidden.has(sort));
102
+ const columns = (list.columns ?? columnsFromFields(resource)).filter((column) => column.field === void 0 || !hidden.has(column.field)).map((column) => {
98
103
  const field = column.field !== void 0 ? fields.get(column.field) ?? null : null;
99
104
  const id = column.id ?? column.field ?? "";
100
105
  const resolved = {
@@ -102,7 +107,9 @@ function resolveList(resource) {
102
107
  field,
103
108
  label: column.label ?? field?.label ?? id,
104
109
  display: column.display ?? field?.display ?? field?.type ?? null,
105
- sortable: column.sortable ?? (column.field !== void 0 && sorts.includes(column.field))
110
+ sortable: column.sortable ?? (column.field !== void 0 && sorts.includes(column.field)),
111
+ hidden: column.hidden === true && column.hideable !== false,
112
+ hideable: column.hideable !== false
106
113
  };
107
114
  if (column.width !== void 0) resolved.width = column.width;
108
115
  if (column.align !== void 0) resolved.align = column.align;
@@ -120,12 +127,20 @@ function resolveList(resource) {
120
127
  perPage: list.perPage ?? 20,
121
128
  perPageOptions: list.perPageOptions ?? [],
122
129
  pagination: list.pagination ?? "pages",
123
- inlineEdit: list.inlineEdit ?? [],
130
+ inlineEdit: (list.inlineEdit ?? []).filter((name) => {
131
+ const field = fields.get(name);
132
+ return field === void 0 || canUpdateField(field);
133
+ }),
124
134
  selectable: (list.selectable ?? true) && hasSelectionAction,
125
- actions
135
+ actions,
136
+ calendar: list.calendar !== void 0 ? {
137
+ field: list.calendar.field,
138
+ filter: list.calendar.filter ?? list.calendar.field,
139
+ perPage: list.calendar.perPage ?? 100
140
+ } : null
126
141
  };
127
142
  }
128
143
  //#endregion
129
- export { DEFAULT_PER_PAGE, getOpenMode, getResourceActions, groupActions, resolveList };
144
+ export { DEFAULT_CALENDAR_PER_PAGE, DEFAULT_PER_PAGE, getOpenMode, getResourceActions, groupActions, resolveList };
130
145
 
131
146
  //# sourceMappingURL=list.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":["Action","ActionPlacement","Column","Field","Filter","Resource","BUILT_IN_ITEM_ACTIONS","BuiltInItemAction","isBuiltInItemAction","canRunAction","getActionPlacements","ResolvedColumn","id","field","label","display","sortable","width","align","ResolvedList","columns","filters","sorts","defaultSort","search","layouts","perPage","perPageOptions","pagination","inlineEdit","selectable","actions","Record","DEFAULT_COLUMN_COUNT","NON_COLUMN_TYPES","Set","DEFAULT_PER_PAGE","columnsFromFields","resource","title","itemTitle","fields","filter","has","type","ordered","undefined","name","slice","map","groupActions","groups","row","toolbar","form","menu","forEach","action","placement","push","BUILT_IN_ITEM_ACTION_DEFINITIONS","Readonly","show","kind","scope","edit","duplicate","delete","destructive","confirm","dryRun","getResourceActions","declared","ids","itemActions","index","all","indexOf","getOpenMode","replacement","find","open","resolveList","list","Map","column","get","resolved","includes","hasSelectionAction","some","split","part"],"sources":["../../src/definition/list.ts"],"sourcesContent":["import type { Action, ActionPlacement, Column, Field, Filter, Resource } from '@panneau/protocol';\nimport {\n BUILT_IN_ITEM_ACTIONS,\n type BuiltInItemAction,\n isBuiltInItemAction,\n} from '@panneau/protocol/runtime';\n\nimport { canRunAction, getActionPlacements } from './abilities';\n\n/** A column ready to render. */\nexport interface ResolvedColumn {\n /** The column id: its `id`, or the name of its field. */\n id: string;\n /** The field shown, when the column shows one. */\n field: Field | null;\n label: string;\n /** How the value is displayed: the column's display, the field's, or the field type. */\n display: string | null;\n sortable: boolean;\n width?: number | string;\n align?: 'start' | 'center' | 'end';\n}\n\n/** A list ready to render. */\nexport interface ResolvedList {\n columns: ResolvedColumn[];\n filters: Filter[];\n /** Fields the list can be sorted by. */\n sorts: string[];\n /** The default sort, as `sort` query values (`['-published_at', 'title']`). */\n defaultSort: string[];\n /** Whether the list can be searched (`q`). */\n search: boolean;\n /** List layouts, the first one being the default. */\n layouts: string[];\n perPage: number;\n perPageOptions: number[];\n /** `pages` (numbered, with a total), or `cursor`: the list follows the cursors of its pages. */\n pagination: 'pages' | 'cursor';\n /** Fields editable in the list. */\n inlineEdit: string[];\n /** Whether items can be selected: the list allows it and a selection action exists. */\n selectable: boolean;\n /** Actions the user can run, by placement. */\n actions: Record<ActionPlacement, Action[]>;\n}\n\n/** Fields shown when the list declares no columns. */\nconst DEFAULT_COLUMN_COUNT = 4;\nconst NON_COLUMN_TYPES = new Set(['group', 'repeater', 'richtext']);\n\nexport const DEFAULT_PER_PAGE = 20;\n\nfunction columnsFromFields(resource: Resource): Column[] {\n const title = resource.itemTitle;\n const fields = resource.fields.filter((field) => !NON_COLUMN_TYPES.has(field.type));\n const ordered =\n title !== undefined\n ? [\n ...fields.filter((field) => field.name === title),\n ...fields.filter((field) => field.name !== title),\n ]\n : fields;\n return ordered.slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));\n}\n\n/** Groups the actions the user can run by placement. */\nexport function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]> {\n const groups: Record<ActionPlacement, Action[]> = { row: [], toolbar: [], form: [], menu: [] };\n actions.filter(canRunAction).forEach((action) => {\n getActionPlacements(action).forEach((placement) => groups[placement].push(action));\n });\n return groups;\n}\n\n/** The built-in item actions, as the client shows them when a resource doesn't replace them. */\nconst BUILT_IN_ITEM_ACTION_DEFINITIONS: Readonly<Record<BuiltInItemAction, Action>> = {\n show: { id: 'show', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n edit: { id: 'edit', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n duplicate: { id: 'duplicate', kind: 'server', scope: ['item'], placement: ['menu', 'form'] },\n delete: {\n id: 'delete',\n kind: 'server',\n scope: ['item', 'selection'],\n placement: ['menu', 'toolbar', 'form'],\n destructive: true,\n confirm: true,\n dryRun: true,\n },\n};\n\n/**\n * The actions of a resource (decision 0040): its built-in item actions (`show`, `edit`,\n * `duplicate`, `delete`, or those of its `itemActions`, in their order), then the actions it\n * declares. A declared action with the id of a built-in one replaces it, at its place, with the\n * built-in one's placement, confirmation, `destructive` and `dryRun` when it doesn't set them, and\n * is left out with it when `itemActions` doesn't list it. With `\"open\": \"edit\"`, `show` is left out: it\n * would go to the edit form too. Abilities of the items then hide what they don't allow.\n */\nexport function getResourceActions(resource: Resource): Action[] {\n const declared = resource.actions ?? [];\n const ids = (resource.itemActions ?? BUILT_IN_ITEM_ACTIONS).filter(\n (id, index, all): id is BuiltInItemAction =>\n isBuiltInItemAction(id) &&\n all.indexOf(id) === index &&\n !(id === 'show' && getOpenMode(resource) === 'edit'),\n );\n return [\n ...ids.map((id): Action => {\n const replacement = declared.find((action) => action.id === id);\n // What the declared action doesn't set (placement, confirmation, dry runs) is the\n // built-in one's.\n return replacement !== undefined\n ? { ...BUILT_IN_ITEM_ACTION_DEFINITIONS[id], ...replacement }\n : BUILT_IN_ITEM_ACTION_DEFINITIONS[id];\n }),\n ...declared.filter((action) => !isBuiltInItemAction(action.id)),\n ];\n}\n\n/**\n * Where the title of an item goes (`open` of the resource, decision 0040): `panel`, the show route\n * with the item's details next to the list, or `edit`, its form. A value it doesn't know is `panel`.\n */\nexport function getOpenMode(resource: Resource): 'panel' | 'edit' {\n return resource.open === 'edit' ? 'edit' : 'panel';\n}\n\n/**\n * Resolves the list of a resource. Without columns, it shows the item title and the next fields\n * (up to four, skipping groups, repeaters and rich text).\n */\nexport function resolveList(resource: Resource): ResolvedList {\n const list = resource.list ?? {};\n const fields = new Map(resource.fields.map((field) => [field.name, field]));\n const sorts = list.sorts ?? [];\n const columns = (list.columns ?? columnsFromFields(resource)).map((column): ResolvedColumn => {\n const field = column.field !== undefined ? (fields.get(column.field) ?? null) : null;\n const id = column.id ?? column.field ?? '';\n const resolved: ResolvedColumn = {\n id,\n field,\n label: column.label ?? field?.label ?? id,\n display: column.display ?? field?.display ?? field?.type ?? null,\n sortable:\n column.sortable ?? (column.field !== undefined && sorts.includes(column.field)),\n };\n if (column.width !== undefined) {\n resolved.width = column.width;\n }\n if (column.align !== undefined) {\n resolved.align = column.align;\n }\n return resolved;\n });\n const actions = groupActions(getResourceActions(resource));\n const hasSelectionAction = getResourceActions(resource).some(\n (action) => action.scope.includes('selection') && canRunAction(action),\n );\n return {\n columns,\n filters: list.filters ?? [],\n sorts,\n defaultSort: (list.defaultSort ?? '').split(',').filter((part) => part !== ''),\n search: list.search ?? false,\n layouts: list.layouts ?? ['table'],\n perPage: list.perPage ?? DEFAULT_PER_PAGE,\n perPageOptions: list.perPageOptions ?? [],\n pagination: list.pagination ?? 'pages',\n inlineEdit: list.inlineEdit ?? [],\n selectable: (list.selectable ?? true) && hasSelectionAction,\n actions,\n };\n}\n"],"mappings":";;;;AAgDA,IAAMiC,uBAAuB;AAC7B,IAAMC,mCAAmB,IAAIC,IAAI;CAAC;CAAS;CAAY;AAAU,CAAC;AAElE,IAAaC,mBAAmB;AAEhC,SAASC,kBAAkBC,UAA8B;CACrD,MAAMC,QAAQD,SAASE;CACvB,MAAMC,SAASH,SAASG,OAAOC,QAAQ7B,UAAU,CAACqB,iBAAiBS,IAAI9B,MAAM+B,IAAI,CAAC;CAQlF,QANIL,UAAUO,KAAAA,IACJ,CACI,GAAGL,OAAOC,QAAQ7B,UAAUA,MAAMkC,SAASR,KAAK,GAChD,GAAGE,OAAOC,QAAQ7B,UAAUA,MAAMkC,SAASR,KAAK,CAAC,IAErDE,OAAAA,CACKO,MAAM,GAAGf,oBAAoB,CAAC,CAACgB,KAAKpC,WAAW,EAAEA,OAAOA,MAAMkC,KAAK,EAAE;AACxF;;AAGA,SAAgBG,aAAanB,SAA+D;CACxF,MAAMoB,SAA4C;EAAEC,KAAK,CAAA;EAAIC,SAAS,CAAA;EAAIC,MAAM,CAAA;EAAIC,MAAM,CAAA;CAAG;CAC7FxB,QAAQW,OAAOjC,YAAY,CAAC,CAAC+C,SAASC,WAAW;EAC7C/C,oBAAoB+C,MAAM,CAAC,CAACD,SAASE,cAAcP,OAAOO,UAAU,CAACC,KAAKF,MAAM,CAAC;CACrF,CAAC;CACD,OAAON;AACX;;AAGA,IAAMS,mCAAgF;CAClFE,MAAM;EAAElD,IAAI;EAAQmD,MAAM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AA;EACvCC,YAAYuD,KAAKvD,cAAc;EAC/BC,YAAYsD,KAAKtD,cAAc,CAAA;EAC/BC,aAAaqD,KAAKrD,cAAc,SAAS2D;EACzC1D;CACJ;AACJ"}
1
+ {"version":3,"file":"list.js","names":["Action","ActionPlacement","Column","Field","Filter","Resource","BUILT_IN_ITEM_ACTIONS","BuiltInItemAction","isBuiltInItemAction","canRunAction","canUpdateField","canViewField","getActionPlacements","ResolvedColumn","id","field","label","display","sortable","width","align","hidden","hideable","ResolvedCalendar","filter","perPage","ResolvedList","columns","filters","sorts","defaultSort","search","layouts","perPageOptions","pagination","inlineEdit","selectable","actions","Record","calendar","DEFAULT_COLUMN_COUNT","NON_COLUMN_TYPES","Set","DEFAULT_PER_PAGE","DEFAULT_CALENDAR_PER_PAGE","columnsFromFields","resource","title","itemTitle","fields","has","type","ordered","undefined","name","slice","map","groupActions","groups","row","toolbar","form","menu","forEach","action","placement","push","BUILT_IN_ITEM_ACTION_DEFINITIONS","Readonly","show","kind","scope","edit","duplicate","delete","destructive","confirm","dryRun","getResourceActions","declared","ids","itemActions","index","all","indexOf","getOpenMode","replacement","find","open","resolveList","list","Map","sort","declaredColumns","column","get","resolved","includes","hasSelectionAction","some","split","part"],"sources":["../../src/definition/list.ts"],"sourcesContent":["import type { Action, ActionPlacement, Column, Field, Filter, Resource } from '@panneau/protocol';\nimport {\n BUILT_IN_ITEM_ACTIONS,\n type BuiltInItemAction,\n isBuiltInItemAction,\n} from '@panneau/protocol/runtime';\n\nimport { canRunAction, canUpdateField, canViewField, getActionPlacements } from './abilities';\n\n/** A column ready to render. */\nexport interface ResolvedColumn {\n /** The column id: its `id`, or the name of its field. */\n id: string;\n /** The field shown, when the column shows one. */\n field: Field | null;\n label: string;\n /** How the value is displayed: the column's display, the field's, or the field type. */\n display: string | null;\n sortable: boolean;\n width?: number | string;\n align?: 'start' | 'center' | 'end';\n /** Not shown until the user shows it (decision 0042). */\n hidden: boolean;\n /** Whether the user can hide it. */\n hideable: boolean;\n}\n\n/** The calendar of a list (decision 0044). */\nexport interface ResolvedCalendar {\n /** The `date` or `datetime` field each item is shown on the day of. */\n field: string;\n /** The id of the `date-range` filter the calendar asks for a month through. */\n filter: string;\n /** How many items the calendar asks for a month. */\n perPage: number;\n}\n\n/** A list ready to render. */\nexport interface ResolvedList {\n columns: ResolvedColumn[];\n filters: Filter[];\n /** Fields the list can be sorted by. */\n sorts: string[];\n /** The default sort, as `sort` query values (`['-published_at', 'title']`). */\n defaultSort: string[];\n /** Whether the list can be searched (`q`). */\n search: boolean;\n /** List layouts, the first one being the default. */\n layouts: string[];\n perPage: number;\n perPageOptions: number[];\n /** `pages` (numbered, with a total), or `cursor`: the list follows the cursors of its pages. */\n pagination: 'pages' | 'cursor';\n /** Fields editable in the list. */\n inlineEdit: string[];\n /** Whether items can be selected: the list allows it and a selection action exists. */\n selectable: boolean;\n /** Actions the user can run, by placement. */\n actions: Record<ActionPlacement, Action[]>;\n /** The calendar of the list, for its `calendar` layout, or `null`. */\n calendar: ResolvedCalendar | null;\n}\n\n/** Fields shown when the list declares no columns. */\nconst DEFAULT_COLUMN_COUNT = 4;\nconst NON_COLUMN_TYPES = new Set(['group', 'repeater', 'richtext']);\n\nexport const DEFAULT_PER_PAGE = 20;\n\n/** How many items a calendar asks for a month, without its own `perPage`. */\nexport const DEFAULT_CALENDAR_PER_PAGE = 100;\n\nfunction columnsFromFields(resource: Resource): Column[] {\n const title = resource.itemTitle;\n const fields = resource.fields.filter(\n (field) => !NON_COLUMN_TYPES.has(field.type) && canViewField(field),\n );\n const ordered =\n title !== undefined\n ? [\n ...fields.filter((field) => field.name === title),\n ...fields.filter((field) => field.name !== title),\n ]\n : fields;\n return ordered.slice(0, DEFAULT_COLUMN_COUNT).map((field) => ({ field: field.name }));\n}\n\n/** Groups the actions the user can run by placement. */\nexport function groupActions(actions: readonly Action[]): Record<ActionPlacement, Action[]> {\n const groups: Record<ActionPlacement, Action[]> = { row: [], toolbar: [], form: [], menu: [] };\n actions.filter(canRunAction).forEach((action) => {\n getActionPlacements(action).forEach((placement) => groups[placement].push(action));\n });\n return groups;\n}\n\n/** The built-in item actions, as the client shows them when a resource doesn't replace them. */\nconst BUILT_IN_ITEM_ACTION_DEFINITIONS: Readonly<Record<BuiltInItemAction, Action>> = {\n show: { id: 'show', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n edit: { id: 'edit', kind: 'link', scope: ['item'], placement: ['row', 'form'] },\n duplicate: { id: 'duplicate', kind: 'server', scope: ['item'], placement: ['menu', 'form'] },\n delete: {\n id: 'delete',\n kind: 'server',\n scope: ['item', 'selection'],\n placement: ['menu', 'toolbar', 'form'],\n destructive: true,\n confirm: true,\n dryRun: true,\n },\n};\n\n/**\n * The actions of a resource (decision 0040): its built-in item actions (`show`, `edit`,\n * `duplicate`, `delete`, or those of its `itemActions`, in their order), then the actions it\n * declares. A declared action with the id of a built-in one replaces it, at its place, with the\n * built-in one's placement, confirmation, `destructive` and `dryRun` when it doesn't set them, and\n * is left out with it when `itemActions` doesn't list it. With `\"open\": \"edit\"`, `show` is left out: it\n * would go to the edit form too. Abilities of the items then hide what they don't allow.\n */\nexport function getResourceActions(resource: Resource): Action[] {\n const declared = resource.actions ?? [];\n const ids = (resource.itemActions ?? BUILT_IN_ITEM_ACTIONS).filter(\n (id, index, all): id is BuiltInItemAction =>\n isBuiltInItemAction(id) &&\n all.indexOf(id) === index &&\n !(id === 'show' && getOpenMode(resource) === 'edit'),\n );\n return [\n ...ids.map((id): Action => {\n const replacement = declared.find((action) => action.id === id);\n // What the declared action doesn't set (placement, confirmation, dry runs) is the\n // built-in one's.\n return replacement !== undefined\n ? { ...BUILT_IN_ITEM_ACTION_DEFINITIONS[id], ...replacement }\n : BUILT_IN_ITEM_ACTION_DEFINITIONS[id];\n }),\n ...declared.filter((action) => !isBuiltInItemAction(action.id)),\n ];\n}\n\n/**\n * Where the title of an item goes (`open` of the resource, decision 0040): `panel`, the show route\n * with the item's details next to the list, or `edit`, its form. A value it doesn't know is `panel`.\n */\nexport function getOpenMode(resource: Resource): 'panel' | 'edit' {\n return resource.open === 'edit' ? 'edit' : 'panel';\n}\n\n/**\n * Resolves the list of a resource. Without columns, it shows the item title and the next fields\n * (up to four, skipping groups, repeaters and rich text). Fields the current user can't see\n * (`abilities.view: false`) have no column, sort or inline editing, and those they can't edit\n * aren't edited inline (decision 0046).\n */\nexport function resolveList(resource: Resource): ResolvedList {\n const list = resource.list ?? {};\n const fields = new Map(resource.fields.map((field) => [field.name, field]));\n const hidden = new Set(\n resource.fields.filter((field) => !canViewField(field)).map((field) => field.name),\n );\n const sorts = (list.sorts ?? []).filter((sort) => !hidden.has(sort));\n const declaredColumns = (list.columns ?? columnsFromFields(resource)).filter(\n (column) => column.field === undefined || !hidden.has(column.field),\n );\n const columns = declaredColumns.map((column): ResolvedColumn => {\n const field = column.field !== undefined ? (fields.get(column.field) ?? null) : null;\n const id = column.id ?? column.field ?? '';\n const resolved: ResolvedColumn = {\n id,\n field,\n label: column.label ?? field?.label ?? id,\n display: column.display ?? field?.display ?? field?.type ?? null,\n sortable:\n column.sortable ?? (column.field !== undefined && sorts.includes(column.field)),\n hidden: column.hidden === true && column.hideable !== false,\n hideable: column.hideable !== false,\n };\n if (column.width !== undefined) {\n resolved.width = column.width;\n }\n if (column.align !== undefined) {\n resolved.align = column.align;\n }\n return resolved;\n });\n const actions = groupActions(getResourceActions(resource));\n const hasSelectionAction = getResourceActions(resource).some(\n (action) => action.scope.includes('selection') && canRunAction(action),\n );\n return {\n columns,\n filters: list.filters ?? [],\n sorts,\n defaultSort: (list.defaultSort ?? '').split(',').filter((part) => part !== ''),\n search: list.search ?? false,\n layouts: list.layouts ?? ['table'],\n perPage: list.perPage ?? DEFAULT_PER_PAGE,\n perPageOptions: list.perPageOptions ?? [],\n pagination: list.pagination ?? 'pages',\n inlineEdit: (list.inlineEdit ?? []).filter((name) => {\n const field = fields.get(name);\n return field === undefined || canUpdateField(field);\n }),\n selectable: (list.selectable ?? true) && hasSelectionAction,\n actions,\n calendar:\n list.calendar !== undefined\n ? {\n field: list.calendar.field,\n filter: list.calendar.filter ?? list.calendar.field,\n perPage: list.calendar.perPage ?? DEFAULT_CALENDAR_PER_PAGE,\n }\n : null,\n };\n}\n"],"mappings":";;;;AAgEA,IAAMwC,uBAAuB;AAC7B,IAAMC,mCAAmB,IAAIC,IAAI;CAAC;CAAS;CAAY;AAAU,CAAC;AAElE,IAAaC,mBAAmB;;AAGhC,IAAaC,4BAA4B;AAEzC,SAASC,kBAAkBC,UAA8B;CACrD,MAAMC,QAAQD,SAASE;CACvB,MAAMC,SAASH,SAASG,OAAOzB,QAC1BT,UAAU,CAAC0B,iBAAiBS,IAAInC,MAAMoC,IAAI,KAAKxC,aAAaI,KAAK,CACtE;CAQA,QANIgC,UAAUM,KAAAA,IACJ,CACI,GAAGJ,OAAOzB,QAAQT,UAAUA,MAAMuC,SAASP,KAAK,GAChD,GAAGE,OAAOzB,QAAQT,UAAUA,MAAMuC,SAASP,KAAK,CAAC,IAErDE,OAAAA,CACKM,MAAM,GAAGf,oBAAoB,CAAC,CAACgB,KAAKzC,WAAW,EAAEA,OAAOA,MAAMuC,KAAK,EAAE;AACxF;;AAGA,SAAgBG,aAAapB,SAA+D;CACxF,MAAMqB,SAA4C;EAAEC,KAAK,CAAA;EAAIC,SAAS,CAAA;EAAIC,MAAM,CAAA;EAAIC,MAAM,CAAA;CAAG;CAC7FzB,QAAQb,OAAOf,YAAY,CAAC,CAACsD,SAASC,WAAW;EAC7CpD,oBAAoBoD,MAAM,CAAC,CAACD,SAASE,cAAcP,OAAOO,UAAU,CAACC,KAAKF,MAAM,CAAC;CACrF,CAAC;CACD,OAAON;AACX;;AAGA,IAAMS,mCAAgF;CAClFE,MAAM;EAAEvD,IAAI;EAAQwD,MAAM;EAAQC,OAAO,CAAC,MAAM;EAAGN,WAAW,CAAC,OAAO,MAAM;CAAE;CAC9EO,MAAM;EAAE1D,IAAI;EAAQwD,MAAM;EAAQC,OAAO,CAAC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;EACHrC;EACAC,SAAS8D,KAAK9D,WAAW,CAAA;EACzBC;EACAC,cAAc4D,KAAK5D,eAAe,GAAA,CAAIsE,MAAM,GAAG,CAAC,CAAC5E,QAAQ6E,SAASA,SAAS,EAAE;EAC7EtE,QAAQ2D,KAAK3D,UAAU;EACvBC,SAAS0D,KAAK1D,WAAW,CAAC,OAAO;EACjCP,SAASiE,KAAKjE,WAAAA;EACdQ,gBAAgByD,KAAKzD,kBAAkB,CAAA;EACvCC,YAAYwD,KAAKxD,cAAc;EAC/BC,aAAauD,KAAKvD,cAAc,CAAA,EAAA,CAAIX,QAAQ8B,SAAS;GACjD,MAAMvC,QAAQkC,OAAO8C,IAAIzC,IAAI;GAC7B,OAAOvC,UAAUsC,KAAAA,KAAa3C,eAAeK,KAAK;EACtD,CAAC;EACDqB,aAAasD,KAAKtD,cAAc,SAAS8D;EACzC7D;EACAE,UACImD,KAAKnD,aAAac,KAAAA,IACZ;GACItC,OAAO2E,KAAKnD,SAASxB;GACrBS,QAAQkE,KAAKnD,SAASf,UAAUkE,KAAKnD,SAASxB;GAC9CU,SAASiE,KAAKnD,SAASd,WAAAA;EAC3B,IACA;CACd;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/form/messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAiBrD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE9D"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/form/messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAkBrD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE9D"}
@@ -7,6 +7,7 @@ var MESSAGES = {
7
7
  email: () => "This value must be an email address.",
8
8
  url: () => "This value must be a URL.",
9
9
  json: () => "This value must be valid JSON: an object or an array.",
10
+ tel: () => "This value must be a complete phone number.",
10
11
  in: () => "This value is not one of the choices.",
11
12
  accept: () => "This file type is not accepted.",
12
13
  maxSize: () => "This file is too large.",
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","names":["RuleFailure","MESSAGES","Record","failure","required","min","String","value","max","pattern","email","url","json","in","accept","maxSize","before","after","formatRuleFailure","message","rule"],"sources":["../../src/form/messages.ts"],"sourcesContent":["import type { RuleFailure } from '@panneau/protocol';\n\nconst MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n json: () => 'This value must be valid JSON: an object or an array.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n};\n\n/**\n * The message of a failed rule: the rule's own `message`, or a default English message. Forms\n * take a `formatError` option to translate them.\n */\nexport function formatRuleFailure(failure: RuleFailure): string {\n return failure.message ?? MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n"],"mappings":";AAEA,IAAMC,WAA6D;CAC/DG,gBAAgB;CAChBC,MAAMF,YAAY,+BAA+BG,OAAOH,QAAQI,KAAK,EAAC;CACtEC,MAAML,YAAY,8BAA8BG,OAAOH,QAAQI,KAAK,EAAC;CACrEE,eAAe;CACfC,aAAa;CACbC,WAAW;CACXC,YAAY;CACZC,UAAU;CACVC,cAAc;CACdC,eAAe;CACfC,cAAc;CACdC,aAAa;AACjB;;;;;AAMA,SAAgBC,kBAAkBf,SAA8B;CAC5D,OAAOA,QAAQgB,WAAWlB,SAASE,QAAQiB,KAAK,GAAGjB,OAAO,KAAK;AACnE"}
1
+ {"version":3,"file":"messages.js","names":["RuleFailure","MESSAGES","Record","failure","required","min","String","value","max","pattern","email","url","json","tel","in","accept","maxSize","before","after","formatRuleFailure","message","rule"],"sources":["../../src/form/messages.ts"],"sourcesContent":["import type { RuleFailure } from '@panneau/protocol';\n\nconst MESSAGES: Record<string, (failure: RuleFailure) => string> = {\n required: () => 'This field is required.',\n min: (failure) => `This value must be at least ${String(failure.value)}.`,\n max: (failure) => `This value must be at most ${String(failure.value)}.`,\n pattern: () => 'This value has an invalid format.',\n email: () => 'This value must be an email address.',\n url: () => 'This value must be a URL.',\n json: () => 'This value must be valid JSON: an object or an array.',\n tel: () => 'This value must be a complete phone number.',\n in: () => 'This value is not one of the choices.',\n accept: () => 'This file type is not accepted.',\n maxSize: () => 'This file is too large.',\n before: () => 'This date is too late.',\n after: () => 'This date is too early.',\n};\n\n/**\n * The message of a failed rule: the rule's own `message`, or a default English message. Forms\n * take a `formatError` option to translate them.\n */\nexport function formatRuleFailure(failure: RuleFailure): string {\n return failure.message ?? MESSAGES[failure.rule]?.(failure) ?? 'This value is invalid.';\n}\n"],"mappings":";AAEA,IAAMC,WAA6D;CAC/DG,gBAAgB;CAChBC,MAAMF,YAAY,+BAA+BG,OAAOH,QAAQI,KAAK,EAAC;CACtEC,MAAML,YAAY,8BAA8BG,OAAOH,QAAQI,KAAK,EAAC;CACrEE,eAAe;CACfC,aAAa;CACbC,WAAW;CACXC,YAAY;CACZC,WAAW;CACXC,UAAU;CACVC,cAAc;CACdC,eAAe;CACfC,cAAc;CACdC,aAAa;AACjB;;;;;AAMA,SAAgBC,kBAAkBhB,SAA8B;CAC5D,OAAOA,QAAQiB,WAAWnB,SAASE,QAAQkB,KAAK,GAAGlB,OAAO,KAAK;AACnE"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction, } from './definition/abilities.js';
1
+ export { can, canRunAction, canUpdateField, canViewField, canViewPage, getActionPlacements, getVisibleFields, isActionAllowedOn, partitionByAction, } from './definition/abilities.js';
2
2
  export { type ActionItem, type ItemAction, type ItemActionsOptions, type ItemSurface, fillActionUrl, getItemActions, selectItemActions, } from './definition/itemActions.js';
3
3
  export { type FormMode, type ResolveFormOptions, type ResolvedForm, getLayoutFieldNames, resolveFields, resolveForm, } from './definition/form.js';
4
- export { DEFAULT_PER_PAGE, type ResolvedColumn, type ResolvedList, getOpenMode, getResourceActions, groupActions, resolveList, } from './definition/list.js';
4
+ export { DEFAULT_CALENDAR_PER_PAGE, DEFAULT_PER_PAGE, type ResolvedCalendar, type ResolvedColumn, type ResolvedList, getOpenMode, getResourceActions, groupActions, resolveList, } from './definition/list.js';
5
5
  export { type ResolvedResource, type ResourceAbilities, findResource, resolveResource, } from './definition/resource.js';
6
6
  export { type Form, type FormConflict, type FormOptions, type FormState, type FormStatus, type GetErrorsOptions, type SubmitContext, type SubmitResult, type UpdatableFormOptions, createForm, getDefaultValues, } from './form/form.js';
7
7
  export { formatRuleFailure } from './form/messages.js';
@@ -9,6 +9,8 @@ export { getItemValues, getProblem, isItem } from './form/problem.js';
9
9
  export { selectErrorCount, selectErrors, selectValue, selectVisible } from './form/selectors.js';
10
10
  export { type FormStore, createLocalStore } from './form/store.js';
11
11
  export { type List, type ListDefaults, type ListOptions, type ListSelection, type ListState, createList, } from './list/list.js';
12
+ export { currentMonth, getCalendarRange, isMonth, shiftMonth } from './list/calendar.js';
13
+ export { type ListViewState, type ListViewStore, type RememberedView, createStorageViewStore, } from './list/viewStore.js';
12
14
  export { type MemoryRouter, type Router, createHistoryRouter, createMemoryRouter, } from './list/router.js';
13
15
  export { type Messages, type MessagesLoader, type PanneauPlugin, type PluginComponent, type PluginComponentKind, type PluginRegistry, type Theme, createPluginRegistry, definePlugin, loadMessages, resolveTheme, } from './plugins.js';
14
16
  export { type Command, type CommandContext, type CommandSource, getCommands, getSearchableResources, isSearchable, } from './commands.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index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EAClB,KAAK,SAAS,EACd,UAAU,GACb,MAAM,aAAa,CAAC;AACrB,OAAO,EACH,KAAK,YAAY,EACjB,KAAK,MAAM,EACX,mBAAmB,EACnB,kBAAkB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACH,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,oBAAoB,EACpB,YAAY,EACZ,YAAY,EACZ,YAAY,GACf,MAAM,WAAW,CAAC;AACnB,OAAO,EACH,KAAK,OAAO,EACZ,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,WAAW,EACX,sBAAsB,EACtB,YAAY,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EACH,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,mBAAmB,EACnB,KAAK,wBAAwB,EAC7B,iBAAiB,EACjB,aAAa,EACb,cAAc,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACH,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,UAAU,EACV,UAAU,EACV,WAAW,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,OAAO,EACP,YAAY,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,KAAK,aAAa,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,KAAK,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,GAAG,EACH,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,WAAW,EACX,mBAAmB,EACnB,gBAAgB,EAChB,iBA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@@ -1,5 +1,5 @@
1
- import { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction } from "./definition/abilities.js";
2
- import { DEFAULT_PER_PAGE, getOpenMode, getResourceActions, groupActions, resolveList } from "./definition/list.js";
1
+ import { can, canRunAction, canUpdateField, canViewField, canViewPage, getActionPlacements, getVisibleFields, isActionAllowedOn, partitionByAction } from "./definition/abilities.js";
2
+ import { DEFAULT_CALENDAR_PER_PAGE, DEFAULT_PER_PAGE, getOpenMode, getResourceActions, groupActions, resolveList } from "./definition/list.js";
3
3
  import { fillActionUrl, getItemActions, selectItemActions } from "./definition/itemActions.js";
4
4
  import { getLayoutFieldNames, resolveFields, resolveForm } from "./definition/form.js";
5
5
  import { findResource, resolveResource } from "./definition/resource.js";
@@ -9,6 +9,8 @@ import { getItemValues, getProblem, isItem } from "./form/problem.js";
9
9
  import { selectErrorCount, selectErrors, selectValue, selectVisible } from "./form/selectors.js";
10
10
  import { createLocalStore } from "./form/store.js";
11
11
  import { createForm, getDefaultValues } from "./form/form.js";
12
+ import { currentMonth, getCalendarRange, isMonth, shiftMonth } from "./list/calendar.js";
13
+ import { createStorageViewStore } from "./list/viewStore.js";
12
14
  import { createList } from "./list/list.js";
13
15
  import { createHistoryRouter, createMemoryRouter } from "./list/router.js";
14
16
  import { createPluginRegistry, definePlugin, loadMessages, resolveTheme } from "./plugins.js";
@@ -17,4 +19,4 @@ import { LeaveGuardsProvider, createLeaveGuards, useLeaveGuard, useLeaveGuards }
17
19
  import { PanneauProvider, usePanneau, usePlugins, useResource } from "./react/provider.js";
18
20
  import { useForm, useFormField } from "./react/useForm.js";
19
21
  import { useList } from "./react/useList.js";
20
- export { DEFAULT_PER_PAGE, LeaveGuardsProvider, PanneauProvider, can, canRunAction, createForm, createHistoryRouter, createLeaveGuards, createList, createLocalStore, createMemoryRouter, createPluginRegistry, definePlugin, fillActionUrl, findResource, formatRuleFailure, getActionPlacements, getCommands, getDefaultValues, getItemActions, getItemValues, getLayoutFieldNames, getOpenMode, getProblem, getResourceActions, getSearchableResources, groupActions, isActionAllowedOn, isEqual, isItem, isSearchable, loadMessages, partitionByAction, resolveFields, resolveForm, resolveList, resolveResource, resolveTheme, selectErrorCount, selectErrors, selectItemActions, selectValue, selectVisible, setValue, useForm, useFormField, useLeaveGuard, useLeaveGuards, useList, usePanneau, usePlugins, useResource };
22
+ export { DEFAULT_CALENDAR_PER_PAGE, DEFAULT_PER_PAGE, LeaveGuardsProvider, PanneauProvider, can, canRunAction, canUpdateField, canViewField, canViewPage, createForm, createHistoryRouter, createLeaveGuards, createList, createLocalStore, createMemoryRouter, createPluginRegistry, createStorageViewStore, currentMonth, definePlugin, fillActionUrl, findResource, formatRuleFailure, getActionPlacements, getCalendarRange, getCommands, getDefaultValues, getItemActions, getItemValues, getLayoutFieldNames, getOpenMode, getProblem, getResourceActions, getSearchableResources, getVisibleFields, groupActions, isActionAllowedOn, isEqual, isItem, isMonth, isSearchable, loadMessages, partitionByAction, resolveFields, resolveForm, resolveList, resolveResource, resolveTheme, selectErrorCount, selectErrors, selectItemActions, selectValue, selectVisible, setValue, shiftMonth, useForm, useFormField, useLeaveGuard, useLeaveGuards, useList, usePanneau, usePlugins, useResource };
@@ -0,0 +1,15 @@
1
+ /** Whether a value is a month, as the view of a calendar keeps it (`2026-11`). */
2
+ export declare function isMonth(value: unknown): value is string;
3
+ /** The month of a day, in the time zone of the browser (`2026-11`). Defaults to today. */
4
+ export declare function currentMonth(now?: Date): string;
5
+ /** The month `offset` months after another one (`-1` for the previous one). */
6
+ export declare function shiftMonth(month: string, offset: number): string;
7
+ /**
8
+ * The days a calendar asks for to show a month (decision 0044): from 6 days before its first day
9
+ * to 6 days after its last, so that the weeks shown are covered whatever day they start on.
10
+ */
11
+ export declare function getCalendarRange(month: string): {
12
+ from: string;
13
+ to: string;
14
+ };
15
+ //# sourceMappingURL=calendar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.d.ts","sourceRoot":"","sources":["../../src/list/calendar.ts"],"names":[],"mappings":"AAYA,kFAAkF;AAClF,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEvD;AAED,0FAA0F;AAC1F,wBAAgB,YAAY,CAAC,GAAG,GAAE,IAAiB,GAAG,MAAM,CAE3D;AAED,+EAA+E;AAC/E,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAIhE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAS5E"}
@@ -0,0 +1,42 @@
1
+ //#region src/list/calendar.ts
2
+ var MONTH = /^(\d{4})-(0[1-9]|1[0-2])$/;
3
+ /** Days before and after a month that a calendar asks for: weeks start on any day. */
4
+ var PADDING = 6;
5
+ function pad(value, length = 2) {
6
+ return String(value).padStart(length, "0");
7
+ }
8
+ function toDay(date) {
9
+ return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
10
+ }
11
+ /** Whether a value is a month, as the view of a calendar keeps it (`2026-11`). */
12
+ function isMonth(value) {
13
+ return typeof value === "string" && MONTH.test(value);
14
+ }
15
+ /** The month of a day, in the time zone of the browser (`2026-11`). Defaults to today. */
16
+ function currentMonth(now = /* @__PURE__ */ new Date()) {
17
+ return `${pad(now.getFullYear(), 4)}-${pad(now.getMonth() + 1)}`;
18
+ }
19
+ /** The month `offset` months after another one (`-1` for the previous one). */
20
+ function shiftMonth(month, offset) {
21
+ const [, year = "1970", index = "01"] = MONTH.exec(month) ?? [];
22
+ const date = new Date(Date.UTC(Number(year), Number(index) - 1 + offset, 1));
23
+ return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}`;
24
+ }
25
+ /**
26
+ * The days a calendar asks for to show a month (decision 0044): from 6 days before its first day
27
+ * to 6 days after its last, so that the weeks shown are covered whatever day they start on.
28
+ */
29
+ function getCalendarRange(month) {
30
+ const [, year = "1970", index = "01"] = MONTH.exec(month) ?? [];
31
+ const first = Date.UTC(Number(year), Number(index) - 1, 1);
32
+ const last = Date.UTC(Number(year), Number(index), 0);
33
+ const day = 864e5;
34
+ return {
35
+ from: toDay(/* @__PURE__ */ new Date(first - PADDING * day)),
36
+ to: toDay(new Date(last + PADDING * day))
37
+ };
38
+ }
39
+ //#endregion
40
+ export { currentMonth, getCalendarRange, isMonth, shiftMonth };
41
+
42
+ //# sourceMappingURL=calendar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.js","names":["MONTH","PADDING","pad","value","length","String","padStart","toDay","date","Date","getUTCFullYear","getUTCMonth","getUTCDate","isMonth","test","currentMonth","now","getFullYear","getMonth","shiftMonth","month","offset","year","index","exec","UTC","Number","getCalendarRange","from","to","first","last","day"],"sources":["../../src/list/calendar.ts"],"sourcesContent":["const MONTH = /^(\\d{4})-(0[1-9]|1[0-2])$/;\n/** Days before and after a month that a calendar asks for: weeks start on any day. */\nconst PADDING = 6;\n\nfunction pad(value: number, length = 2): string {\n return String(value).padStart(length, '0');\n}\n\nfunction toDay(date: Date): string {\n return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;\n}\n\n/** Whether a value is a month, as the view of a calendar keeps it (`2026-11`). */\nexport function isMonth(value: unknown): value is string {\n return typeof value === 'string' && MONTH.test(value);\n}\n\n/** The month of a day, in the time zone of the browser (`2026-11`). Defaults to today. */\nexport function currentMonth(now: Date = new Date()): string {\n return `${pad(now.getFullYear(), 4)}-${pad(now.getMonth() + 1)}`;\n}\n\n/** The month `offset` months after another one (`-1` for the previous one). */\nexport function shiftMonth(month: string, offset: number): string {\n const [, year = '1970', index = '01'] = MONTH.exec(month) ?? [];\n const date = new Date(Date.UTC(Number(year), Number(index) - 1 + offset, 1));\n return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}`;\n}\n\n/**\n * The days a calendar asks for to show a month (decision 0044): from 6 days before its first day\n * to 6 days after its last, so that the weeks shown are covered whatever day they start on.\n */\nexport function getCalendarRange(month: string): { from: string; to: string } {\n const [, year = '1970', index = '01'] = MONTH.exec(month) ?? [];\n const first = Date.UTC(Number(year), Number(index) - 1, 1);\n const last = Date.UTC(Number(year), Number(index), 0);\n const day = 86_400_000;\n return {\n from: toDay(new Date(first - PADDING * day)),\n to: toDay(new Date(last + PADDING * day)),\n };\n}\n"],"mappings":";AAAA,IAAMA,QAAQ;;AAEd,IAAMC,UAAU;AAEhB,SAASC,IAAIC,OAAeC,SAAS,GAAW;CAC5C,OAAOC,OAAOF,KAAK,CAAC,CAACG,SAASF,QAAQ,GAAG;AAC7C;AAEA,SAASG,MAAMC,MAAoB;CAC/B,OAAO,GAAGN,IAAIM,KAAKE,eAAe,GAAG,CAAC,EAAC,GAAIR,IAAIM,KAAKG,YAAY,IAAI,CAAC,EAAC,GAAIT,IAAIM,KAAKI,WAAW,CAAC;AACnG;;AAGA,SAAgBC,QAAQV,OAAiC;CACrD,OAAO,OAAOA,UAAU,YAAYH,MAAMc,KAAKX,KAAK;AACxD;;AAGA,SAAgBY,aAAaC,sBAAY,IAAIP,KAAK,GAAW;CACzD,OAAO,GAAGP,IAAIc,IAAIC,YAAY,GAAG,CAAC,EAAC,GAAIf,IAAIc,IAAIE,SAAS,IAAI,CAAC;AACjE;;AAGA,SAAgBC,WAAWC,OAAeC,QAAwB;CAC9D,MAAM,GAAGC,OAAO,QAAQC,QAAQ,QAAQvB,MAAMwB,KAAKJ,KAAK,KAAK,CAAA;CAC7D,MAAMZ,OAAO,IAAIC,KAAKA,KAAKgB,IAAIC,OAAOJ,IAAI,GAAGI,OAAOH,KAAK,IAAI,IAAIF,QAAQ,CAAC,CAAC;CAC3E,OAAO,GAAGnB,IAAIM,KAAKE,eAAe,GAAG,CAAC,EAAC,GAAIR,IAAIM,KAAKG,YAAY,IAAI,CAAC;AACzE;;;;;AAMA,SAAgBgB,iBAAiBP,OAA6C;CAC1E,MAAM,GAAGE,OAAO,QAAQC,QAAQ,QAAQvB,MAAMwB,KAAKJ,KAAK,KAAK,CAAA;CAC7D,MAAMU,QAAQrB,KAAKgB,IAAIC,OAAOJ,IAAI,GAAGI,OAAOH,KAAK,IAAI,GAAG,CAAC;CACzD,MAAMQ,OAAOtB,KAAKgB,IAAIC,OAAOJ,IAAI,GAAGI,OAAOH,KAAK,GAAG,CAAC;CACpD,MAAMS,MAAM;CACZ,OAAO;EACHJ,MAAMrB,sBAAM,IAAIE,KAAKqB,QAAQ7B,UAAU+B,GAAG,CAAC;EAC3CH,IAAItB,MAAM,IAAIE,KAAKsB,OAAO9B,UAAU+B,GAAG,CAAC;CAC5C;AACJ"}
@@ -1,6 +1,7 @@
1
1
  import type { FilterValue, ListQuery, Selection } from '@panneau/protocol';
2
- import type { ResolvedList } from '../definition/list.js';
2
+ import type { ResolvedCalendar, ResolvedList } from '../definition/list.js';
3
3
  import type { Router } from './router.js';
4
+ import { type ListViewState, type ListViewStore } from './viewStore.js';
4
5
  /**
5
6
  * Selected items: some ids, or every item matching the list query (filters and search) except
6
7
  * some ids. "All matching" covers the items of every page.
@@ -15,12 +16,20 @@ export type ListSelection = {
15
16
  export interface ListState {
16
17
  /** The query to fetch: the list's defaults, overridden by the current state. */
17
18
  query: ListQuery;
19
+ /** How the items are shown: the layout and the columns, when they aren't the defaults. */
20
+ view: ListViewState;
18
21
  selection: ListSelection;
19
22
  }
20
23
  export interface ListDefaults {
21
24
  perPage?: number;
22
25
  /** Default sort, as `sort` query values (`['-published_at']`). */
23
26
  sort?: string[];
27
+ /** The default layout. */
28
+ layout?: string;
29
+ /** The ids of the columns shown by default, in their order. */
30
+ columns?: string[];
31
+ /** The calendar of the list, for its `calendar` layout (decision 0044). */
32
+ calendar?: ResolvedCalendar | null;
24
33
  }
25
34
  export interface ListOptions {
26
35
  /** A resolved list, for the defaults (`perPage`, `defaultSort`). */
@@ -31,6 +40,15 @@ export interface ListOptions {
31
40
  query?: ListQuery;
32
41
  /** Keeps the query in the URL. The router's query string wins over `query`. */
33
42
  router?: Router | null;
43
+ /**
44
+ * Remembers the view of the list (filters, sort, page size, layout and columns) under `key`,
45
+ * in `store` (the browser's `localStorage` by default), and restores it when the list opens
46
+ * without a query of its own: a URL without any parameter of the list (decision 0042).
47
+ */
48
+ remember?: {
49
+ key: string;
50
+ store?: ListViewStore;
51
+ } | null;
34
52
  }
35
53
  /** A headless list: query and selection. React components use `useList()`. */
36
54
  export interface List {
@@ -58,8 +76,16 @@ export interface List {
58
76
  setFilter(id: string, value: FilterValue | undefined): void;
59
77
  /** Sets the search, goes back to the first page, and clears the selection. */
60
78
  setSearch(q: string): void;
61
- /** Removes the page, filters, search and sort: back to the defaults. */
79
+ /** Removes the page, filters, search and sort: back to the defaults. The view stays. */
62
80
  resetQuery(): void;
81
+ /** Shows the items in a layout (`cards`). */
82
+ setLayout(layout: string): void;
83
+ /** Shows these columns, by id, in this order. */
84
+ setColumns(ids: readonly string[]): void;
85
+ /** Back to the columns of the definition. */
86
+ resetColumns(): void;
87
+ /** Shows a month in the calendar (`2026-11`). */
88
+ setMonth(month: string): void;
63
89
  /** Adds ids to the selection (removes them from the exceptions in "all matching" mode). */
64
90
  select(ids: readonly string[]): void;
65
91
  /** Removes ids from the selection (adds them to the exceptions in "all matching" mode). */
@@ -1 +1 @@
1
- {"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/list/list.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAG3E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC;;;GAGG;AACH,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,KAAK,CAAC;IA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B,wBAAgB,UAAU,CAAC,OAAO,GAAE,WAAgB,GAAG,IAAI,CAoT1D"}
package/dist/list/list.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { isEqual } from "../values.js";
2
+ import { currentMonth, getCalendarRange, isMonth } from "./calendar.js";
3
+ import { createStorageViewStore } from "./viewStore.js";
2
4
  import { fromSearchParams, isFilterRange, toSearchParams } from "@panneau/protocol/runtime";
3
5
  //#region src/list/list.ts
4
6
  var EMPTY_SELECTION = {
@@ -10,7 +12,7 @@ var FIRST_PAGE = {
10
12
  page: 1,
11
13
  cursor: void 0
12
14
  };
13
- var LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|filter\[.+)$/;
15
+ var LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|layout|columns|month|filter\[.+)$/;
14
16
  /** Removes the values that are the defaults, so the URL only keeps what the user changed. */
15
17
  function normalize(query, defaults) {
16
18
  const result = {};
@@ -24,25 +26,87 @@ function normalize(query, defaults) {
24
26
  if (query.fields !== void 0) result.fields = query.fields;
25
27
  return result;
26
28
  }
29
+ /** Removes the parts of the view that are the defaults. */
30
+ function normalizeView(view, defaults) {
31
+ const result = {};
32
+ if (view.layout !== void 0 && view.layout !== "" && view.layout !== defaults.layout) result.layout = view.layout;
33
+ if (view.columns !== void 0 && view.columns.length > 0 && !isEqual(view.columns, defaults.columns)) result.columns = [...view.columns];
34
+ if (isMonth(view.month) && view.month !== currentMonth()) result.month = view.month;
35
+ return result;
36
+ }
37
+ function readView(search) {
38
+ const view = {};
39
+ const layout = search.get("layout");
40
+ if (layout !== null) view.layout = layout;
41
+ const columns = search.get("columns");
42
+ if (columns !== null) view.columns = columns.split(",").filter((id) => id !== "");
43
+ const month = search.get("month");
44
+ if (month !== null) view.month = month;
45
+ return view;
46
+ }
47
+ /** What a list remembers of its query: not its page, cursor or search. */
48
+ function rememberedQuery(query) {
49
+ const result = {};
50
+ if (query.filter !== void 0) result.filter = query.filter;
51
+ if (query.sort !== void 0) result.sort = query.sort;
52
+ if (query.perPage !== void 0) result.perPage = query.perPage;
53
+ return result;
54
+ }
27
55
  /** Creates a headless list. */
28
56
  function createList(options = {}) {
29
57
  const defaults = {
30
58
  perPage: options.defaults?.perPage ?? options.list?.perPage ?? 20,
31
- sort: options.defaults?.sort ?? options.list?.defaultSort ?? []
59
+ sort: options.defaults?.sort ?? options.list?.defaultSort ?? [],
60
+ calendar: options.defaults?.calendar ?? options.list?.calendar ?? null
32
61
  };
62
+ const defaultLayout = options.defaults?.layout ?? options.list?.layouts[0];
63
+ if (defaultLayout !== void 0) defaults.layout = defaultLayout;
64
+ const defaultColumns = options.defaults?.columns ?? options.list?.columns.filter((column) => !column.hidden).map((column) => column.id);
65
+ if (defaultColumns !== void 0) defaults.columns = defaultColumns;
33
66
  const router = options.router ?? null;
34
- const readRouter = () => router !== null ? normalize(fromSearchParams(new URLSearchParams(router.getSearch())), defaults) : {};
35
- let params = router !== null ? readRouter() : normalize(options.query ?? {}, defaults);
67
+ const readRouter = () => {
68
+ if (router === null) return {
69
+ query: {},
70
+ view: {}
71
+ };
72
+ const search = new URLSearchParams(router.getSearch());
73
+ return {
74
+ query: normalize(fromSearchParams(search), defaults),
75
+ view: normalizeView(readView(search), defaults)
76
+ };
77
+ };
78
+ const hasListParams = () => router !== null && [...new URLSearchParams(router.getSearch()).keys()].some((key) => LIST_PARAM.test(key));
79
+ const remember = options.remember ?? null;
80
+ const store = remember !== null ? remember.store ?? createStorageViewStore() : null;
81
+ const remembered = remember !== null && store !== null && (router !== null ? !hasListParams() : options.query === void 0) ? store.get(remember.key) : null;
82
+ const initial = router !== null ? readRouter() : null;
83
+ let params = normalize(remembered?.query ?? initial?.query ?? options.query ?? {}, defaults);
84
+ let view = normalizeView(remembered?.view ?? initial?.view ?? {}, defaults);
85
+ let restoring = remembered !== null && router !== null;
36
86
  let selection = EMPTY_SELECTION;
37
87
  let trail = [];
38
88
  const cursors = options.list?.pagination === "cursor";
89
+ const sortQuery = () => params.sort !== void 0 || defaults.sort.length > 0 ? { sort: params.sort ?? defaults.sort } : {};
90
+ const calendarQuery = (calendar) => {
91
+ const { page: _page, cursor: _cursor, perPage: _perPage, ...rest } = params;
92
+ return {
93
+ ...rest,
94
+ ...sortQuery(),
95
+ perPage: calendar.perPage,
96
+ filter: {
97
+ ...params.filter,
98
+ [calendar.filter]: getCalendarRange(view.month ?? currentMonth())
99
+ }
100
+ };
101
+ };
39
102
  const compute = () => ({
40
- query: {
103
+ query: defaults.calendar !== null && (view.layout ?? defaults.layout) === "calendar" ? calendarQuery(defaults.calendar) : {
41
104
  ...params,
42
105
  ...cursors ? {} : { page: params.page ?? 1 },
43
106
  perPage: params.perPage ?? defaults.perPage,
44
- ...params.sort !== void 0 || defaults.sort.length > 0 ? { sort: params.sort ?? defaults.sort } : {}
107
+ ...sortQuery()
45
108
  },
109
+ view,
46
110
  selection
47
111
  });
48
112
  let state = compute();
@@ -56,9 +120,29 @@ function createList(options = {}) {
56
120
  const search = new URLSearchParams(router.getSearch());
57
121
  [...search.keys()].filter((key) => LIST_PARAM.test(key)).forEach((key) => search.delete(key));
58
122
  toSearchParams(params).forEach((value, key) => search.append(key, value));
123
+ if (view.layout !== void 0) search.set("layout", view.layout);
124
+ if (view.columns !== void 0) search.set("columns", view.columns.join(","));
125
+ if (view.month !== void 0) search.set("month", view.month);
59
126
  const next = search.toString();
60
127
  if (next !== router.getSearch()) router.setSearch(next, { replace });
61
128
  };
129
+ const save = () => {
130
+ if (remember === null || store === null) return;
131
+ const query = rememberedQuery(params);
132
+ const { month: _month, ...remembered } = view;
133
+ store.set(remember.key, Object.keys(query).length > 0 || Object.keys(remembered).length > 0 ? {
134
+ query,
135
+ view: remembered
136
+ } : null);
137
+ };
138
+ const setView = (next, { replace = false } = {}) => {
139
+ const normalized = normalizeView(next, defaults);
140
+ if (isEqual(normalized, view)) return;
141
+ view = normalized;
142
+ writeRouter(replace);
143
+ save();
144
+ notify();
145
+ };
62
146
  const setParams = (next, { replace = false } = {}) => {
63
147
  const normalized = normalize(next, defaults);
64
148
  if (isEqual(normalized, params)) return;
@@ -69,6 +153,7 @@ function createList(options = {}) {
69
153
  params = normalized;
70
154
  if (scopeChanged) selection = EMPTY_SELECTION;
71
155
  writeRouter(replace);
156
+ save();
72
157
  notify();
73
158
  };
74
159
  const setSelection = (next) => {
@@ -77,10 +162,13 @@ function createList(options = {}) {
77
162
  };
78
163
  let unsubscribeRouter = null;
79
164
  const onRouterChange = () => {
80
- const next = readRouter();
81
- if (isEqual(next, params)) return;
165
+ if (restoring && !hasListParams()) return;
166
+ restoring = false;
167
+ const { query: next, view: nextView } = readRouter();
168
+ if (isEqual(next, params) && isEqual(nextView, view)) return;
82
169
  if (!isEqual(next.filter, params.filter) || next.q !== params.q) selection = EMPTY_SELECTION;
83
170
  params = next;
171
+ view = nextView;
84
172
  notify();
85
173
  };
86
174
  const list = {
@@ -92,6 +180,10 @@ function createList(options = {}) {
92
180
  listeners.add(listener);
93
181
  if (router !== null && unsubscribeRouter === null) {
94
182
  unsubscribeRouter = router.subscribe(onRouterChange);
183
+ if (restoring) {
184
+ restoring = false;
185
+ writeRouter(true);
186
+ }
95
187
  onRouterChange();
96
188
  }
97
189
  return () => {
@@ -169,6 +261,22 @@ function createList(options = {}) {
169
261
  ...FIRST_PAGE
170
262
  }, { replace: true }),
171
263
  resetQuery: () => setParams({}),
264
+ setLayout: (layout) => setView({
265
+ ...view,
266
+ layout
267
+ }),
268
+ setColumns: (ids) => setView({
269
+ ...view,
270
+ columns: [...ids]
271
+ }, { replace: true }),
272
+ resetColumns() {
273
+ const { columns: _columns, ...rest } = view;
274
+ setView(rest, { replace: true });
275
+ },
276
+ setMonth: (month) => setView({
277
+ ...view,
278
+ month
279
+ }),
172
280
  select(ids) {
173
281
  if (selection.mode === "all") setSelection({
174
282
  mode: "all",
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":["FilterValue","ListQuery","Selection","fromSearchParams","isFilterRange","toSearchParams","ResolvedList","isEqual","Router","ListSelection","mode","ids","except","ListState","query","selection","ListDefaults","perPage","sort","ListOptions","list","defaults","router","List","getState","subscribe","listener","setPage","page","nextPage","cursor","previousPage","setPerPage","setSort","toggleSort","field","setFilter","id","value","setSearch","q","resetQuery","select","deselect","toggle","selectAllMatching","clearSelection","isSelected","getSelectedCount","total","getSelection","EMPTY_SELECTION","FIRST_PAGE","undefined","LIST_PARAM","normalize","Required","result","filter","Object","fromEntries","entries","Array","isArray","length","keys","fields","createList","options","defaultSort","readRouter","URLSearchParams","getSearch","params","trail","cursors","pagination","compute","state","listeners","Set","notify","forEach","writeRouter","replace","search","key","test","delete","append","next","toString","setParams","normalized","scopeChanged","_next","nextQuery","_current","currentQuery","setSelection","unsubscribeRouter","onRouterChange","add","size","current","back","at","rest","slice","_sort","_removed","includes","Math","max","Record"],"sources":["../../src/list/list.ts"],"sourcesContent":["import type { FilterValue, ListQuery, Selection } from '@panneau/protocol';\nimport { fromSearchParams, isFilterRange, toSearchParams } from '@panneau/protocol/runtime';\n\nimport type { ResolvedList } from '../definition/list';\nimport { isEqual } from '../values';\nimport type { Router } from './router';\n\n/**\n * Selected items: some ids, or every item matching the list query (filters and search) except\n * some ids. \"All matching\" covers the items of every page.\n */\nexport type ListSelection =\n { mode: 'ids'; ids: readonly string[] } | { mode: 'all'; except: readonly string[] };\n\nexport interface ListState {\n /** The query to fetch: the list's defaults, overridden by the current state. */\n query: ListQuery;\n selection: ListSelection;\n}\n\nexport interface ListDefaults {\n perPage?: number;\n /** Default sort, as `sort` query values (`['-published_at']`). */\n sort?: string[];\n}\n\nexport interface ListOptions {\n /** A resolved list, for the defaults (`perPage`, `defaultSort`). */\n list?: ResolvedList;\n /** Defaults, over those of `list`. Default values are not written to the URL. */\n defaults?: ListDefaults;\n /** The starting query, when there is no router. */\n query?: ListQuery;\n /** Keeps the query in the URL. The router's query string wins over `query`. */\n router?: Router | null;\n}\n\n/** A headless list: query and selection. React components use `useList()`. */\nexport interface List {\n getState(): ListState;\n subscribe(listener: () => void): () => void;\n setPage(page: number): void;\n /**\n * In a list paged with cursors: goes to the page of `nextCursor`, and remembers the cursor of\n * the page it leaves, for `previousPage()`.\n */\n nextPage(cursor: string): void;\n /**\n * In a list paged with cursors: goes back a page, to `previousCursor` when the backend gives\n * one (`null` for the first page), or else to the page it came from. Without either, it goes\n * to the first page.\n */\n previousPage(cursor?: string | null): void;\n /** Sets the page size, and goes back to the first page. */\n setPerPage(perPage: number): void;\n /** Sets the sort (`['-published_at', 'title']`), and goes back to the first page. */\n setSort(sort: readonly string[]): void;\n /** Sorts by a field: ascending, then descending, then back to the default sort. */\n toggleSort(field: string): void;\n /** Sets or removes (`undefined`) a filter, goes back to the first page, and clears the selection. */\n setFilter(id: string, value: FilterValue | undefined): void;\n /** Sets the search, goes back to the first page, and clears the selection. */\n setSearch(q: string): void;\n /** Removes the page, filters, search and sort: back to the defaults. */\n resetQuery(): void;\n /** Adds ids to the selection (removes them from the exceptions in \"all matching\" mode). */\n select(ids: readonly string[]): void;\n /** Removes ids from the selection (adds them to the exceptions in \"all matching\" mode). */\n deselect(ids: readonly string[]): void;\n toggle(id: string): void;\n /** Selects every item matching the query, on every page. */\n selectAllMatching(): void;\n clearSelection(): void;\n isSelected(id: string): boolean;\n /** How many items are selected, given the total of the list. */\n getSelectedCount(total: number): number;\n /** The selection to send with an action, or `null` when nothing is selected. */\n getSelection(): Selection | null;\n}\n\nconst EMPTY_SELECTION: ListSelection = { mode: 'ids', ids: [] };\n/** Back to the first page: page 1, or no cursor. */\nconst FIRST_PAGE = { page: 1, cursor: undefined };\nconst LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|filter\\[.+)$/;\n\n/** Removes the values that are the defaults, so the URL only keeps what the user changed. */\nfunction normalize(query: ListQuery, defaults: Required<ListDefaults>): ListQuery {\n const result: ListQuery = {};\n if (query.page !== undefined && query.page > 1) {\n result.page = query.page;\n }\n if (query.perPage !== undefined && query.perPage !== defaults.perPage) {\n result.perPage = query.perPage;\n }\n if (query.cursor !== undefined && query.cursor !== '') {\n result.cursor = query.cursor;\n }\n if (query.sort !== undefined && !isEqual(query.sort, defaults.sort)) {\n result.sort = [...query.sort];\n }\n const filter = Object.fromEntries(\n Object.entries(query.filter ?? {}).filter(\n ([, value]) =>\n value !== '' &&\n !(Array.isArray(value) && value.length === 0) &&\n !(isFilterRange(value) && Object.keys(value).length === 0),\n ),\n );\n if (Object.keys(filter).length > 0) {\n result.filter = filter;\n }\n if (query.q !== undefined && query.q !== '') {\n result.q = query.q;\n }\n if (query.fields !== undefined) {\n result.fields = query.fields;\n }\n return result;\n}\n\n/** Creates a headless list. */\nexport function createList(options: ListOptions = {}): List {\n const defaults: Required<ListDefaults> = {\n perPage: options.defaults?.perPage ?? options.list?.perPage ?? 20,\n sort: options.defaults?.sort ?? options.list?.defaultSort ?? [],\n };\n const router = options.router ?? null;\n const readRouter = (): ListQuery =>\n router !== null\n ? normalize(fromSearchParams(new URLSearchParams(router.getSearch())), defaults)\n : {};\n\n let params: ListQuery =\n router !== null ? readRouter() : normalize(options.query ?? {}, defaults);\n let selection: ListSelection = EMPTY_SELECTION;\n // The cursors of the pages before this one, as `nextPage()` followed them.\n let trail: (string | null)[] = [];\n\n // A list paged with cursors has no page numbers: its query has a cursor, after the first page.\n const cursors = options.list?.pagination === 'cursor';\n const compute = (): ListState => ({\n query: {\n ...params,\n ...(cursors ? {} : { page: params.page ?? 1 }),\n perPage: params.perPage ?? defaults.perPage,\n ...(params.sort !== undefined || defaults.sort.length > 0\n ? { sort: params.sort ?? defaults.sort }\n : {}),\n },\n selection,\n });\n\n let state = compute();\n const listeners = new Set<() => void>();\n const notify = () => {\n state = compute();\n listeners.forEach((listener) => listener());\n };\n\n const writeRouter = (replace: boolean) => {\n if (router === null) {\n return;\n }\n const search = new URLSearchParams(router.getSearch());\n [...search.keys()]\n .filter((key) => LIST_PARAM.test(key))\n .forEach((key) => search.delete(key));\n toSearchParams(params).forEach((value, key) => search.append(key, value));\n const next = search.toString();\n if (next !== router.getSearch()) {\n router.setSearch(next, { replace });\n }\n };\n\n const setParams = (next: ListQuery, { replace = false } = {}) => {\n const normalized = normalize(next, defaults);\n if (isEqual(normalized, params)) {\n return;\n }\n const scopeChanged =\n !isEqual(normalized.filter, params.filter) || normalized.q !== params.q;\n // Another query starts its pages over.\n const { cursor: _next, ...nextQuery } = normalized;\n const { cursor: _current, ...currentQuery } = params;\n if (!isEqual(nextQuery, currentQuery)) {\n trail = [];\n }\n params = normalized;\n if (scopeChanged) {\n selection = EMPTY_SELECTION;\n }\n writeRouter(replace);\n notify();\n };\n\n const setSelection = (next: ListSelection) => {\n selection = next;\n notify();\n };\n\n let unsubscribeRouter: (() => void) | null = null;\n const onRouterChange = () => {\n const next = readRouter();\n if (isEqual(next, params)) {\n return;\n }\n if (!isEqual(next.filter, params.filter) || next.q !== params.q) {\n selection = EMPTY_SELECTION;\n }\n params = next;\n notify();\n };\n\n const list: List = {\n getState() {\n if (router !== null && unsubscribeRouter === null) {\n onRouterChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n if (router !== null && unsubscribeRouter === null) {\n unsubscribeRouter = router.subscribe(onRouterChange);\n onRouterChange();\n }\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeRouter !== null) {\n unsubscribeRouter();\n unsubscribeRouter = null;\n }\n };\n },\n setPage: (page) => setParams({ ...params, page }),\n nextPage(cursor) {\n const current = params.cursor ?? null;\n setParams({ ...params, cursor });\n trail = [...trail, current];\n },\n previousPage(cursor) {\n const back = cursor !== undefined ? cursor : (trail.at(-1) ?? null);\n const rest = trail.slice(0, -1);\n setParams({ ...params, cursor: back ?? undefined });\n trail = rest;\n },\n setPerPage: (perPage) => setParams({ ...params, perPage, ...FIRST_PAGE }),\n setSort: (sort) => setParams({ ...params, sort: [...sort], ...FIRST_PAGE }),\n toggleSort(field) {\n const sort = state.query.sort ?? [];\n if (sort[0] === field) {\n setParams({ ...params, sort: [`-${field}`], ...FIRST_PAGE });\n } else if (sort[0] === `-${field}` && params.sort !== undefined) {\n const { sort: _sort, ...rest } = params;\n setParams({ ...rest, ...FIRST_PAGE });\n } else {\n setParams({ ...params, sort: [field], ...FIRST_PAGE });\n }\n },\n setFilter(id, value) {\n const { [id]: _removed, ...filter } = params.filter ?? {};\n setParams({\n ...params,\n filter: value === undefined ? filter : { ...filter, [id]: value },\n ...FIRST_PAGE,\n });\n },\n setSearch: (q) => setParams({ ...params, q, ...FIRST_PAGE }, { replace: true }),\n resetQuery: () => setParams({}),\n select(ids) {\n if (selection.mode === 'all') {\n setSelection({\n mode: 'all',\n except: selection.except.filter((id) => !ids.includes(id)),\n });\n } else {\n setSelection({ mode: 'ids', ids: [...new Set([...selection.ids, ...ids])] });\n }\n },\n deselect(ids) {\n if (selection.mode === 'all') {\n setSelection({ mode: 'all', except: [...new Set([...selection.except, ...ids])] });\n } else {\n setSelection({ mode: 'ids', ids: selection.ids.filter((id) => !ids.includes(id)) });\n }\n },\n toggle(id) {\n if (list.isSelected(id)) {\n list.deselect([id]);\n } else {\n list.select([id]);\n }\n },\n selectAllMatching: () => setSelection({ mode: 'all', except: [] }),\n clearSelection: () => setSelection(EMPTY_SELECTION),\n isSelected: (id) =>\n selection.mode === 'all' ? !selection.except.includes(id) : selection.ids.includes(id),\n getSelectedCount: (total) =>\n selection.mode === 'all'\n ? Math.max(0, total - selection.except.length)\n : selection.ids.length,\n getSelection() {\n if (selection.mode === 'ids') {\n return selection.ids.length > 0 ? { ids: [...selection.ids] } : null;\n }\n const query: { filter?: Record<string, unknown>; q?: string } = {};\n if (params.filter !== undefined) {\n query.filter = params.filter;\n }\n if (params.q !== undefined) {\n query.q = params.q;\n }\n return selection.except.length > 0\n ? { query, except: [...selection.except] }\n : { query };\n },\n };\n return list;\n}\n"],"mappings":";;;AAgFA,IAAMmD,kBAAiC;CAAEzC,MAAM;CAAOC,KAAK,CAAA;AAAG;;AAE9D,IAAMyC,aAAa;CAAExB,MAAM;CAAGE,QAAQuB,KAAAA;AAAU;AAChD,IAAMC,a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E,EAAE,IAAItB,UAAUJ,IAAIoG,SAAS1E,EAAE;EACzFW,mBAAmBC,UACflC,UAAUL,SAAS,QACbsG,KAAKC,IAAI,GAAGhE,QAAQlC,UAAUH,OAAOoD,MAAM,IAC3CjD,UAAUJ,IAAIqD;EACxBd,eAAe;GACX,IAAInC,UAAUL,SAAS,OACnB,OAAOK,UAAUJ,IAAIqD,SAAS,IAAI,EAAErD,KAAK,CAAC,GAAGI,UAAUJ,GAAG,EAAE,IAAI;GAEpE,MAAMG,QAA0D,CAAC;GACjE,IAAI2D,OAAOf,WAAWL,KAAAA,GAClBvC,MAAM4C,SAASe,OAAOf;GAE1B,IAAIe,OAAOjC,MAAMa,KAAAA,GACbvC,MAAM0B,IAAIiC,OAAOjC;GAErB,OAAOzB,UAAUH,OAAOoD,SAAS,IAC3B;IAAElD;IAAOF,QAAQ,CAAC,GAAGG,UAAUH,MAAM;GAAE,IACvC,EAAEE,MAAM;EAClB;CACJ;CACA,OAAOM;AACX"}
1
+ {"version":3,"file":"list.js","names":["FilterValue","ListQuery","Selection","fromSearchParams","isFilterRange","toSearchParams","ResolvedCalendar","ResolvedList","isEqual","currentMonth","getCalendarRange","isMonth","Router","ListViewState","ListViewStore","RememberedView","createStorageViewStore","ListSelection","mode","ids","except","ListState","query","view","selection","ListDefaults","perPage","sort","layout","columns","calendar","ListOptions","list","defaults","router","remember","key","store","List","getState","subscribe","listener","setPage","page","nextPage","cursor","previousPage","setPerPage","setSort","toggleSort","field","setFilter","id","value","setSearch","q","resetQuery","setLayout","setColumns","resetColumns","setMonth","month","select","deselect","toggle","selectAllMatching","clearSelection","isSelected","getSelectedCount","total","getSelection","EMPTY_SELECTION","FIRST_PAGE","undefined","LIST_PARAM","Defaults","Required","Pick","normalize","result","filter","Object","fromEntries","entries","Array","isArray","length","keys","fields","normalizeView","readView","search","URLSearchParams","get","split","rememberedQuery","createList","options","defaultSort","defaultLayout","layouts","defaultColumns","column","hidden","map","readRouter","getSearch","hasListParams","some","test","remembered","initial","params","restoring","trail","cursors","pagination","sortQuery","calendarQuery","_page","_cursor","_perPage","rest","compute","state","listeners","Set","notify","forEach","writeRouter","replace","delete","append","set","join","next","toString","save","_month","setView","normalized","setParams","scopeChanged","_next","nextQuery","_current","currentQuery","setSelection","unsubscribeRouter","onRouterChange","nextView","add","size","current","back","at","slice","_sort","_removed","_columns","includes","Math","max","Record"],"sources":["../../src/list/list.ts"],"sourcesContent":["import type { FilterValue, ListQuery, Selection } from '@panneau/protocol';\nimport { fromSearchParams, isFilterRange, toSearchParams } from '@panneau/protocol/runtime';\n\nimport type { ResolvedCalendar, ResolvedList } from '../definition/list';\nimport { isEqual } from '../values';\nimport { currentMonth, getCalendarRange, isMonth } from './calendar';\nimport type { Router } from './router';\nimport {\n type ListViewState,\n type ListViewStore,\n type RememberedView,\n createStorageViewStore,\n} from './viewStore';\n\n/**\n * Selected items: some ids, or every item matching the list query (filters and search) except\n * some ids. \"All matching\" covers the items of every page.\n */\nexport type ListSelection =\n { mode: 'ids'; ids: readonly string[] } | { mode: 'all'; except: readonly string[] };\n\nexport interface ListState {\n /** The query to fetch: the list's defaults, overridden by the current state. */\n query: ListQuery;\n /** How the items are shown: the layout and the columns, when they aren't the defaults. */\n view: ListViewState;\n selection: ListSelection;\n}\n\nexport interface ListDefaults {\n perPage?: number;\n /** Default sort, as `sort` query values (`['-published_at']`). */\n sort?: string[];\n /** The default layout. */\n layout?: string;\n /** The ids of the columns shown by default, in their order. */\n columns?: string[];\n /** The calendar of the list, for its `calendar` layout (decision 0044). */\n calendar?: ResolvedCalendar | null;\n}\n\nexport interface ListOptions {\n /** A resolved list, for the defaults (`perPage`, `defaultSort`). */\n list?: ResolvedList;\n /** Defaults, over those of `list`. Default values are not written to the URL. */\n defaults?: ListDefaults;\n /** The starting query, when there is no router. */\n query?: ListQuery;\n /** Keeps the query in the URL. The router's query string wins over `query`. */\n router?: Router | null;\n /**\n * Remembers the view of the list (filters, sort, page size, layout and columns) under `key`,\n * in `store` (the browser's `localStorage` by default), and restores it when the list opens\n * without a query of its own: a URL without any parameter of the list (decision 0042).\n */\n remember?: { key: string; store?: ListViewStore } | null;\n}\n\n/** A headless list: query and selection. React components use `useList()`. */\nexport interface List {\n getState(): ListState;\n subscribe(listener: () => void): () => void;\n setPage(page: number): void;\n /**\n * In a list paged with cursors: goes to the page of `nextCursor`, and remembers the cursor of\n * the page it leaves, for `previousPage()`.\n */\n nextPage(cursor: string): void;\n /**\n * In a list paged with cursors: goes back a page, to `previousCursor` when the backend gives\n * one (`null` for the first page), or else to the page it came from. Without either, it goes\n * to the first page.\n */\n previousPage(cursor?: string | null): void;\n /** Sets the page size, and goes back to the first page. */\n setPerPage(perPage: number): void;\n /** Sets the sort (`['-published_at', 'title']`), and goes back to the first page. */\n setSort(sort: readonly string[]): void;\n /** Sorts by a field: ascending, then descending, then back to the default sort. */\n toggleSort(field: string): void;\n /** Sets or removes (`undefined`) a filter, goes back to the first page, and clears the selection. */\n setFilter(id: string, value: FilterValue | undefined): void;\n /** Sets the search, goes back to the first page, and clears the selection. */\n setSearch(q: string): void;\n /** Removes the page, filters, search and sort: back to the defaults. The view stays. */\n resetQuery(): void;\n /** Shows the items in a layout (`cards`). */\n setLayout(layout: string): void;\n /** Shows these columns, by id, in this order. */\n setColumns(ids: readonly string[]): void;\n /** Back to the columns of the definition. */\n resetColumns(): void;\n /** Shows a month in the calendar (`2026-11`). */\n setMonth(month: string): void;\n /** Adds ids to the selection (removes them from the exceptions in \"all matching\" mode). */\n select(ids: readonly string[]): void;\n /** Removes ids from the selection (adds them to the exceptions in \"all matching\" mode). */\n deselect(ids: readonly string[]): void;\n toggle(id: string): void;\n /** Selects every item matching the query, on every page. */\n selectAllMatching(): void;\n clearSelection(): void;\n isSelected(id: string): boolean;\n /** How many items are selected, given the total of the list. */\n getSelectedCount(total: number): number;\n /** The selection to send with an action, or `null` when nothing is selected. */\n getSelection(): Selection | null;\n}\n\nconst EMPTY_SELECTION: ListSelection = { mode: 'ids', ids: [] };\n/** Back to the first page: page 1, or no cursor. */\nconst FIRST_PAGE = { page: 1, cursor: undefined };\nconst LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|layout|columns|month|filter\\[.+)$/;\n\ntype Defaults = Required<Pick<ListDefaults, 'perPage' | 'sort'>> &\n Pick<ListDefaults, 'layout' | 'columns'> & { calendar: ResolvedCalendar | null };\n\n/** Removes the values that are the defaults, so the URL only keeps what the user changed. */\nfunction normalize(query: ListQuery, defaults: Defaults): ListQuery {\n const result: ListQuery = {};\n if (query.page !== undefined && query.page > 1) {\n result.page = query.page;\n }\n if (query.perPage !== undefined && query.perPage !== defaults.perPage) {\n result.perPage = query.perPage;\n }\n if (query.cursor !== undefined && query.cursor !== '') {\n result.cursor = query.cursor;\n }\n if (query.sort !== undefined && !isEqual(query.sort, defaults.sort)) {\n result.sort = [...query.sort];\n }\n const filter = Object.fromEntries(\n Object.entries(query.filter ?? {}).filter(\n ([, value]) =>\n value !== '' &&\n !(Array.isArray(value) && value.length === 0) &&\n !(isFilterRange(value) && Object.keys(value).length === 0),\n ),\n );\n if (Object.keys(filter).length > 0) {\n result.filter = filter;\n }\n if (query.q !== undefined && query.q !== '') {\n result.q = query.q;\n }\n if (query.fields !== undefined) {\n result.fields = query.fields;\n }\n return result;\n}\n\n/** Removes the parts of the view that are the defaults. */\nfunction normalizeView(view: ListViewState, defaults: Defaults): ListViewState {\n const result: ListViewState = {};\n if (view.layout !== undefined && view.layout !== '' && view.layout !== defaults.layout) {\n result.layout = view.layout;\n }\n if (\n view.columns !== undefined &&\n view.columns.length > 0 &&\n !isEqual(view.columns, defaults.columns)\n ) {\n result.columns = [...view.columns];\n }\n if (isMonth(view.month) && view.month !== currentMonth()) {\n result.month = view.month;\n }\n return result;\n}\n\nfunction readView(search: URLSearchParams): ListViewState {\n const view: ListViewState = {};\n const layout = search.get('layout');\n if (layout !== null) {\n view.layout = layout;\n }\n const columns = search.get('columns');\n if (columns !== null) {\n view.columns = columns.split(',').filter((id) => id !== '');\n }\n const month = search.get('month');\n if (month !== null) {\n view.month = month;\n }\n return view;\n}\n\n/** What a list remembers of its query: not its page, cursor or search. */\nfunction rememberedQuery(query: ListQuery): RememberedView['query'] {\n const result: RememberedView['query'] = {};\n if (query.filter !== undefined) {\n result.filter = query.filter;\n }\n if (query.sort !== undefined) {\n result.sort = query.sort;\n }\n if (query.perPage !== undefined) {\n result.perPage = query.perPage;\n }\n return result;\n}\n\n/** Creates a headless list. */\nexport function createList(options: ListOptions = {}): List {\n const defaults: Defaults = {\n perPage: options.defaults?.perPage ?? options.list?.perPage ?? 20,\n sort: options.defaults?.sort ?? options.list?.defaultSort ?? [],\n calendar: options.defaults?.calendar ?? options.list?.calendar ?? null,\n };\n const defaultLayout = options.defaults?.layout ?? options.list?.layouts[0];\n if (defaultLayout !== undefined) {\n defaults.layout = defaultLayout;\n }\n const defaultColumns =\n options.defaults?.columns ??\n options.list?.columns.filter((column) => !column.hidden).map((column) => column.id);\n if (defaultColumns !== undefined) {\n defaults.columns = defaultColumns;\n }\n const router = options.router ?? null;\n const readRouter = (): { query: ListQuery; view: ListViewState } => {\n if (router === null) {\n return { query: {}, view: {} };\n }\n const search = new URLSearchParams(router.getSearch());\n return {\n query: normalize(fromSearchParams(search), defaults),\n view: normalizeView(readView(search), defaults),\n };\n };\n const hasListParams = (): boolean =>\n router !== null &&\n [...new URLSearchParams(router.getSearch()).keys()].some((key) => LIST_PARAM.test(key));\n\n const remember = options.remember ?? null;\n const store = remember !== null ? (remember.store ?? createStorageViewStore()) : null;\n // A list that opens without a query of its own shows the view it remembers.\n const remembered =\n remember !== null &&\n store !== null &&\n (router !== null ? !hasListParams() : options.query === undefined)\n ? store.get(remember.key)\n : null;\n\n const initial = router !== null ? readRouter() : null;\n let params: ListQuery = normalize(\n remembered?.query ?? initial?.query ?? options.query ?? {},\n defaults,\n );\n let view: ListViewState = normalizeView(remembered?.view ?? initial?.view ?? {}, defaults);\n // The remembered view is written to the URL once the list is subscribed to: not while it\n // renders.\n let restoring = remembered !== null && router !== null;\n let selection: ListSelection = EMPTY_SELECTION;\n // The cursors of the pages before this one, as `nextPage()` followed them.\n let trail: (string | null)[] = [];\n\n // A list paged with cursors has no page numbers: its query has a cursor, after the first page.\n const cursors = options.list?.pagination === 'cursor';\n const sortQuery = (): Pick<ListQuery, 'sort'> =>\n params.sort !== undefined || defaults.sort.length > 0\n ? { sort: params.sort ?? defaults.sort }\n : {};\n // In the calendar, a month: the days around it through its filter, instead of a page.\n const calendarQuery = (calendar: ResolvedCalendar): ListQuery => {\n const { page: _page, cursor: _cursor, perPage: _perPage, ...rest } = params;\n return {\n ...rest,\n ...sortQuery(),\n perPage: calendar.perPage,\n filter: {\n ...params.filter,\n [calendar.filter]: getCalendarRange(view.month ?? currentMonth()),\n },\n };\n };\n const compute = (): ListState => ({\n query:\n defaults.calendar !== null && (view.layout ?? defaults.layout) === 'calendar'\n ? calendarQuery(defaults.calendar)\n : {\n ...params,\n ...(cursors ? {} : { page: params.page ?? 1 }),\n perPage: params.perPage ?? defaults.perPage,\n ...sortQuery(),\n },\n view,\n selection,\n });\n\n let state = compute();\n const listeners = new Set<() => void>();\n const notify = () => {\n state = compute();\n listeners.forEach((listener) => listener());\n };\n\n const writeRouter = (replace: boolean) => {\n if (router === null) {\n return;\n }\n const search = new URLSearchParams(router.getSearch());\n [...search.keys()]\n .filter((key) => LIST_PARAM.test(key))\n .forEach((key) => search.delete(key));\n toSearchParams(params).forEach((value, key) => search.append(key, value));\n if (view.layout !== undefined) {\n search.set('layout', view.layout);\n }\n if (view.columns !== undefined) {\n search.set('columns', view.columns.join(','));\n }\n if (view.month !== undefined) {\n search.set('month', view.month);\n }\n const next = search.toString();\n if (next !== router.getSearch()) {\n router.setSearch(next, { replace });\n }\n };\n\n // Only what the user changes is remembered: not the view of a link they opened.\n const save = () => {\n if (remember === null || store === null) {\n return;\n }\n const query = rememberedQuery(params);\n // A calendar opens on the current month.\n const { month: _month, ...remembered } = view;\n store.set(\n remember.key,\n Object.keys(query).length > 0 || Object.keys(remembered).length > 0\n ? { query, view: remembered }\n : null,\n );\n };\n\n const setView = (next: ListViewState, { replace = false } = {}) => {\n const normalized = normalizeView(next, defaults);\n if (isEqual(normalized, view)) {\n return;\n }\n view = normalized;\n writeRouter(replace);\n save();\n notify();\n };\n\n const setParams = (next: ListQuery, { replace = false } = {}) => {\n const normalized = normalize(next, defaults);\n if (isEqual(normalized, params)) {\n return;\n }\n const scopeChanged =\n !isEqual(normalized.filter, params.filter) || normalized.q !== params.q;\n // Another query starts its pages over.\n const { cursor: _next, ...nextQuery } = normalized;\n const { cursor: _current, ...currentQuery } = params;\n if (!isEqual(nextQuery, currentQuery)) {\n trail = [];\n }\n params = normalized;\n if (scopeChanged) {\n selection = EMPTY_SELECTION;\n }\n writeRouter(replace);\n save();\n notify();\n };\n\n const setSelection = (next: ListSelection) => {\n selection = next;\n notify();\n };\n\n let unsubscribeRouter: (() => void) | null = null;\n const onRouterChange = () => {\n // Until the remembered view is in the URL, the bare URL doesn't replace it.\n if (restoring && !hasListParams()) {\n return;\n }\n restoring = false;\n const { query: next, view: nextView } = readRouter();\n if (isEqual(next, params) && isEqual(nextView, view)) {\n return;\n }\n if (!isEqual(next.filter, params.filter) || next.q !== params.q) {\n selection = EMPTY_SELECTION;\n }\n params = next;\n view = nextView;\n notify();\n };\n\n const list: List = {\n getState() {\n if (router !== null && unsubscribeRouter === null) {\n onRouterChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n if (router !== null && unsubscribeRouter === null) {\n unsubscribeRouter = router.subscribe(onRouterChange);\n if (restoring) {\n // Replacing the entry: Back doesn't go through the bare URL.\n restoring = false;\n writeRouter(true);\n }\n onRouterChange();\n }\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeRouter !== null) {\n unsubscribeRouter();\n unsubscribeRouter = null;\n }\n };\n },\n setPage: (page) => setParams({ ...params, page }),\n nextPage(cursor) {\n const current = params.cursor ?? null;\n setParams({ ...params, cursor });\n trail = [...trail, current];\n },\n previousPage(cursor) {\n const back = cursor !== undefined ? cursor : (trail.at(-1) ?? null);\n const rest = trail.slice(0, -1);\n setParams({ ...params, cursor: back ?? undefined });\n trail = rest;\n },\n setPerPage: (perPage) => setParams({ ...params, perPage, ...FIRST_PAGE }),\n setSort: (sort) => setParams({ ...params, sort: [...sort], ...FIRST_PAGE }),\n toggleSort(field) {\n const sort = state.query.sort ?? [];\n if (sort[0] === field) {\n setParams({ ...params, sort: [`-${field}`], ...FIRST_PAGE });\n } else if (sort[0] === `-${field}` && params.sort !== undefined) {\n const { sort: _sort, ...rest } = params;\n setParams({ ...rest, ...FIRST_PAGE });\n } else {\n setParams({ ...params, sort: [field], ...FIRST_PAGE });\n }\n },\n setFilter(id, value) {\n const { [id]: _removed, ...filter } = params.filter ?? {};\n setParams({\n ...params,\n filter: value === undefined ? filter : { ...filter, [id]: value },\n ...FIRST_PAGE,\n });\n },\n setSearch: (q) => setParams({ ...params, q, ...FIRST_PAGE }, { replace: true }),\n resetQuery: () => setParams({}),\n setLayout: (layout) => setView({ ...view, layout }),\n setColumns: (ids) => setView({ ...view, columns: [...ids] }, { replace: true }),\n resetColumns() {\n const { columns: _columns, ...rest } = view;\n setView(rest, { replace: true });\n },\n setMonth: (month) => setView({ ...view, month }),\n select(ids) {\n if (selection.mode === 'all') {\n setSelection({\n mode: 'all',\n except: selection.except.filter((id) => !ids.includes(id)),\n });\n } else {\n setSelection({ mode: 'ids', ids: [...new Set([...selection.ids, ...ids])] });\n }\n },\n deselect(ids) {\n if (selection.mode === 'all') {\n setSelection({ mode: 'all', except: [...new Set([...selection.except, ...ids])] });\n } else {\n setSelection({ mode: 'ids', ids: selection.ids.filter((id) => !ids.includes(id)) });\n }\n },\n toggle(id) {\n if (list.isSelected(id)) {\n list.deselect([id]);\n } else {\n list.select([id]);\n }\n },\n selectAllMatching: () => setSelection({ mode: 'all', except: [] }),\n clearSelection: () => setSelection(EMPTY_SELECTION),\n isSelected: (id) =>\n selection.mode === 'all' ? !selection.except.includes(id) : selection.ids.includes(id),\n getSelectedCount: (total) =>\n selection.mode === 'all'\n ? Math.max(0, total - selection.except.length)\n : selection.ids.length,\n getSelection() {\n if (selection.mode === 'ids') {\n return selection.ids.length > 0 ? { ids: [...selection.ids] } : null;\n }\n const query: { filter?: Record<string, unknown>; q?: string } = {};\n if (params.filter !== undefined) {\n query.filter = params.filter;\n }\n if (params.q !== undefined) {\n query.q = params.q;\n }\n return selection.except.length > 0\n ? { query, except: [...selection.except] }\n : { query };\n },\n };\n return list;\n}\n"],"mappings":";;;;;AA6GA,IAAMuE,kBAAiC;CAAErD,MAAM;CAAOC,KAAK,CAAA;AAAG;;AAE9D,IAAMqD,aAAa;CAAE7B,MAAM;CAAGE,QAAQ4B,KAAAA;AAAU;AAChD,IAAMC,aAAa;;AAMnB,SAASI,UAAUxD,OAAkBW,UAA+B;CAChE,MAAM8C,SAAoB,CAAC;CAC3B,IAAIzD,MAAMqB,SAAS8B,KAAAA,KAAanD,MAAMqB,OAAO,GACzCoC,OAAOpC,OAAOrB,MAAMqB;CAExB,IAAIrB,MAAMI,YAAY+C,KAAAA,KAAanD,MAAMI,YAAYO,SAASP,SAC1DqD,OAAOrD,UAAUJ,MAAMI;CAE3B,IAAIJ,MAAMuB,WAAW4B,KAAAA,KAAanD,MAAMuB,WAAW,IAC/CkC,OAAOlC,SAASvB,MAAMuB;CAE1B,IAAIvB,MAAMK,SAAS8C,KAAAA,KAAa,CAACjE,QAAQc,MAAMK,MAAMM,SAASN,IAAI,GAC9DoD,OAAOpD,OAAO,CAAC,GAAGL,MAAMK,IAAI;CAEhC,MAAMqD,SAASC,OAAOC,YAClBD,OAAOE,QAAQ7D,MAAM0D,UAAU,CAAC,CAAC,CAAC,CAACA,QAC9B,GAAG3B,WACAA,UAAU,MACV,EAAE+B,MAAMC,QAAQhC,KAAK,KAAKA,MAAMiC,WAAW,MAC3C,EAAElF,cAAciD,KAAK,KAAK4B,OAAOM,KAAKlC,KAAK,CAA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AE,IAAI;GAEpE,MAAMG,QAA0D,CAAC;GACjE,IAAI0F,OAAOhC,WAAWP,KAAAA,GAClBnD,MAAM0D,SAASgC,OAAOhC;GAE1B,IAAIgC,OAAOzD,MAAMkB,KAAAA,GACbnD,MAAMiC,IAAIyD,OAAOzD;GAErB,OAAO/B,UAAUJ,OAAOkE,SAAS,IAC3B;IAAEhE;IAAOF,QAAQ,CAAC,GAAGI,UAAUJ,MAAM;GAAE,IACvC,EAAEE,MAAM;EAClB;CACJ;CACA,OAAOU;AACX"}
@@ -0,0 +1,36 @@
1
+ import type { ListQuery } from '@panneau/protocol';
2
+ /**
3
+ * The view of a list: how it shows its items, not what it fetches (decision 0042). Each part is
4
+ * left out while it is the list's default.
5
+ */
6
+ export interface ListViewState {
7
+ /** The layout chosen (`cards`). */
8
+ layout?: string;
9
+ /** The ids of the columns shown, in their order. */
10
+ columns?: string[];
11
+ /** The month a calendar shows (`2026-11`), when it isn't the current one. Not remembered. */
12
+ month?: string;
13
+ }
14
+ /**
15
+ * What a list remembers of its last view: the filters, sort and page size of its query (not its
16
+ * page, cursor or search), and its view.
17
+ */
18
+ export interface RememberedView {
19
+ query: Pick<ListQuery, 'filter' | 'sort' | 'perPage'>;
20
+ view: ListViewState;
21
+ }
22
+ /**
23
+ * Where lists remember their view, by key. `createStorageViewStore()` keeps them in the browser.
24
+ * Reading is synchronous: a list restores its view before its first fetch.
25
+ */
26
+ export interface ListViewStore {
27
+ get(key: string): RememberedView | null;
28
+ /** Saves the view of a list, or forgets it with `null`. */
29
+ set(key: string, view: RememberedView | null): void;
30
+ }
31
+ /**
32
+ * A store of list views in the browser's `localStorage` (or another `Storage`). Storage that is
33
+ * blocked (private windows, site data settings) or full only means views aren't remembered.
34
+ */
35
+ export declare function createStorageViewStore(storage?: () => Storage | null): ListViewStore;
36
+ //# sourceMappingURL=viewStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewStore.d.ts","sourceRoot":"","sources":["../../src/list/viewStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC1B,mCAAmC;IACnC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oDAAoD;IACpD,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,6FAA6F;IAC7F,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC3B,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC,CAAC;IACtD,IAAI,EAAE,aAAa,CAAC;CACvB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC1B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAAC;IACxC,2DAA2D;IAC3D,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,GAAG,IAAI,GAAG,IAAI,CAAC;CACvD;AA2CD;;;GAGG;AACH,wBAAgB,sBAAsB,CAClC,OAAO,GAAE,MAAM,OAAO,GAAG,IAAqB,GAC/C,aAAa,CAsBf"}
@@ -0,0 +1,54 @@
1
+ //#region src/list/viewStore.ts
2
+ var PREFIX = "panneau:list:";
3
+ function isRecord(value) {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+ function isStringArray(value) {
7
+ return Array.isArray(value) && value.every((part) => typeof part === "string");
8
+ }
9
+ /** Reads a stored view, leaving out what isn't one. */
10
+ function parseView(value) {
11
+ if (!isRecord(value) || !isRecord(value.query) || !isRecord(value.view)) return null;
12
+ const { filter, sort, perPage } = value.query;
13
+ const { layout, columns } = value.view;
14
+ const query = {};
15
+ if (isRecord(filter)) query.filter = filter;
16
+ if (isStringArray(sort)) query.sort = sort;
17
+ if (typeof perPage === "number" && Number.isInteger(perPage) && perPage > 0) query.perPage = perPage;
18
+ const view = {};
19
+ if (typeof layout === "string" && layout !== "") view.layout = layout;
20
+ if (isStringArray(columns) && columns.length > 0) view.columns = columns;
21
+ return {
22
+ query,
23
+ view
24
+ };
25
+ }
26
+ function defaultStorage() {
27
+ return typeof window !== "undefined" ? window.localStorage : null;
28
+ }
29
+ /**
30
+ * A store of list views in the browser's `localStorage` (or another `Storage`). Storage that is
31
+ * blocked (private windows, site data settings) or full only means views aren't remembered.
32
+ */
33
+ function createStorageViewStore(storage = defaultStorage) {
34
+ return {
35
+ get(key) {
36
+ try {
37
+ const stored = storage()?.getItem(`${PREFIX}${key}`) ?? null;
38
+ return stored !== null ? parseView(JSON.parse(stored)) : null;
39
+ } catch {
40
+ return null;
41
+ }
42
+ },
43
+ set(key, view) {
44
+ try {
45
+ if (view === null) storage()?.removeItem(`${PREFIX}${key}`);
46
+ else storage()?.setItem(`${PREFIX}${key}`, JSON.stringify(view));
47
+ } catch {}
48
+ }
49
+ };
50
+ }
51
+ //#endregion
52
+ export { createStorageViewStore };
53
+
54
+ //# sourceMappingURL=viewStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewStore.js","names":["ListQuery","ListViewState","layout","columns","month","RememberedView","query","Pick","view","ListViewStore","get","key","set","PREFIX","isRecord","value","Record","Array","isArray","isStringArray","every","part","parseView","filter","sort","perPage","NonNullable","Number","isInteger","length","defaultStorage","Storage","window","localStorage","createStorageViewStore","storage","stored","getItem","JSON","parse","removeItem","setItem","stringify"],"sources":["../../src/list/viewStore.ts"],"sourcesContent":["import type { ListQuery } from '@panneau/protocol';\n\n/**\n * The view of a list: how it shows its items, not what it fetches (decision 0042). Each part is\n * left out while it is the list's default.\n */\nexport interface ListViewState {\n /** The layout chosen (`cards`). */\n layout?: string;\n /** The ids of the columns shown, in their order. */\n columns?: string[];\n /** The month a calendar shows (`2026-11`), when it isn't the current one. Not remembered. */\n month?: string;\n}\n\n/**\n * What a list remembers of its last view: the filters, sort and page size of its query (not its\n * page, cursor or search), and its view.\n */\nexport interface RememberedView {\n query: Pick<ListQuery, 'filter' | 'sort' | 'perPage'>;\n view: ListViewState;\n}\n\n/**\n * Where lists remember their view, by key. `createStorageViewStore()` keeps them in the browser.\n * Reading is synchronous: a list restores its view before its first fetch.\n */\nexport interface ListViewStore {\n get(key: string): RememberedView | null;\n /** Saves the view of a list, or forgets it with `null`. */\n set(key: string, view: RememberedView | null): void;\n}\n\nconst PREFIX = 'panneau:list:';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((part) => typeof part === 'string');\n}\n\n/** Reads a stored view, leaving out what isn't one. */\nfunction parseView(value: unknown): RememberedView | null {\n if (!isRecord(value) || !isRecord(value.query) || !isRecord(value.view)) {\n return null;\n }\n const { filter, sort, perPage } = value.query;\n const { layout, columns } = value.view;\n const query: RememberedView['query'] = {};\n if (isRecord(filter)) {\n query.filter = filter as NonNullable<ListQuery['filter']>;\n }\n if (isStringArray(sort)) {\n query.sort = sort;\n }\n if (typeof perPage === 'number' && Number.isInteger(perPage) && perPage > 0) {\n query.perPage = perPage;\n }\n const view: ListViewState = {};\n if (typeof layout === 'string' && layout !== '') {\n view.layout = layout;\n }\n if (isStringArray(columns) && columns.length > 0) {\n view.columns = columns;\n }\n return { query, view };\n}\n\nfunction defaultStorage(): Storage | null {\n return typeof window !== 'undefined' ? window.localStorage : null;\n}\n\n/**\n * A store of list views in the browser's `localStorage` (or another `Storage`). Storage that is\n * blocked (private windows, site data settings) or full only means views aren't remembered.\n */\nexport function createStorageViewStore(\n storage: () => Storage | null = defaultStorage,\n): ListViewStore {\n return {\n get(key) {\n try {\n const stored = storage()?.getItem(`${PREFIX}${key}`) ?? null;\n return stored !== null ? parseView(JSON.parse(stored)) : null;\n } catch {\n return null;\n }\n },\n set(key, view) {\n try {\n if (view === null) {\n storage()?.removeItem(`${PREFIX}${key}`);\n } else {\n storage()?.setItem(`${PREFIX}${key}`, JSON.stringify(view));\n }\n } catch {\n // The view then lasts until the page is reloaded.\n }\n },\n };\n}\n"],"mappings":";AAkCA,IAAMa,SAAS;AAEf,SAASC,SAASC,OAAkD;CAChE,OAAOA,UAAU,QAAQ,OAAOA,UAAU,YAAY,CAACE,MAAMC,QAAQH,KAAK;AAC9E;AAEA,SAASI,cAAcJ,OAAmC;CACtD,OAAOE,MAAMC,QAAQH,KAAK,KAAKA,MAAMK,OAAOC,SAAS,OAAOA,SAAS,QAAQ;AACjF;;AAGA,SAASC,UAAUP,OAAuC;CACtD,IAAI,CAACD,SAASC,KAAK,KAAK,CAACD,SAASC,MAAMT,KAAK,KAAK,CAACQ,SAASC,MAAMP,IAAI,GAClE,OAAO;CAEX,MAAM,EAAEe,QAAQC,MAAMC,YAAYV,MAAMT;CACxC,MAAM,EAAEJ,QAAQC,YAAYY,MAAMP;CAClC,MAAMF,QAAiC,CAAC;CACxC,IAAIQ,SAASS,MAAM,GACfjB,MAAMiB,SAASA;CAEnB,IAAIJ,cAAcK,IAAI,GAClBlB,MAAMkB,OAAOA;CAEjB,IAAI,OAAOC,YAAY,YAAYE,OAAOC,UAAUH,OAAO,KAAKA,UAAU,GACtEnB,MAAMmB,UAAUA;CAEpB,MAAMjB,OAAsB,CAAC;CAC7B,IAAI,OAAON,WAAW,YAAYA,WAAW,IACzCM,KAAKN,SAASA;CAElB,IAAIiB,cAAchB,OAAO,KAAKA,QAAQ0B,SAAS,GAC3CrB,KAAKL,UAAUA;CAEnB,OAAO;EAAEG;EAAOE;CAAK;AACzB;AAEA,SAASsB,iBAAiC;CACtC,OAAO,OAAOE,WAAW,cAAcA,OAAOC,eAAe;AACjE;;;;;AAMA,SAAgBC,uBACZC,UAAgCL,gBACnB;CACb,OAAO;EACHpB,IAAIC,KAAK;GACL,IAAI;IACA,MAAMyB,SAASD,QAAQ,CAAC,EAAEE,QAAQ,GAAGxB,SAASF,KAAK,KAAK;IACxD,OAAOyB,WAAW,OAAOd,UAAUgB,KAAKC,MAAMH,MAAM,CAAC,IAAI;GAC7D,QAAQ;IACJ,OAAO;GACX;EACJ;EACAxB,IAAID,KAAKH,MAAM;GACX,IAAI;IACA,IAAIA,SAAS,MACT2B,QAAQ,CAAC,EAAEK,WAAW,GAAG3B,SAASF,KAAK;SAEvCwB,QAAQ,CAAC,EAAEM,QAAQ,GAAG5B,SAASF,OAAO2B,KAAKI,UAAUlC,IAAI,CAAC;GAElE,QAAQ,CACJ;EAER;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panneau/core",
3
- "version": "5.0.0-alpha.12",
3
+ "version": "5.0.0-alpha.14",
4
4
  "description": "The engine of Panneau: plugin registry, definition to forms and lists, form and list state, with React hooks. No UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,6 +33,6 @@
33
33
  "react": "^19.2.0"
34
34
  },
35
35
  "dependencies": {
36
- "@panneau/protocol": "5.0.0-alpha.12"
36
+ "@panneau/protocol": "5.0.0-alpha.14"
37
37
  }
38
38
  }