@panneau/core 5.0.0-alpha.1 → 5.0.0-alpha.11
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 +2 -0
- package/dist/commands.d.ts +38 -0
- package/dist/commands.d.ts.map +1 -0
- package/dist/commands.js +22 -0
- package/dist/commands.js.map +1 -0
- package/dist/definition/abilities.d.ts +15 -4
- package/dist/definition/abilities.d.ts.map +1 -1
- package/dist/definition/abilities.js +18 -5
- package/dist/definition/abilities.js.map +1 -1
- package/dist/definition/form.d.ts +3 -2
- package/dist/definition/form.d.ts.map +1 -1
- package/dist/definition/form.js +24 -2
- package/dist/definition/form.js.map +1 -1
- package/dist/definition/itemActions.d.ts +53 -0
- package/dist/definition/itemActions.d.ts.map +1 -0
- package/dist/definition/itemActions.js +64 -0
- package/dist/definition/itemActions.js.map +1 -0
- package/dist/definition/list.d.ts +16 -0
- package/dist/definition/list.d.ts.map +1 -1
- package/dist/definition/list.js +64 -3
- package/dist/definition/list.js.map +1 -1
- package/dist/definition/resource.d.ts +2 -2
- package/dist/definition/resource.js +1 -1
- package/dist/definition/resource.js.map +1 -1
- package/dist/form/form.d.ts +8 -3
- package/dist/form/form.d.ts.map +1 -1
- package/dist/form/form.js +1 -0
- package/dist/form/form.js.map +1 -1
- package/dist/form/messages.d.ts.map +1 -1
- package/dist/form/messages.js +1 -0
- package/dist/form/messages.js.map +1 -1
- package/dist/form/problem.d.ts +1 -1
- package/dist/form/problem.js.map +1 -1
- package/dist/form/selectors.d.ts +1 -1
- package/dist/form/selectors.js.map +1 -1
- package/dist/form/store.d.ts +1 -1
- package/dist/form/store.js.map +1 -1
- package/dist/index.d.ts +20 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/list/list.d.ts +13 -2
- package/dist/list/list.d.ts.map +1 -1
- package/dist/list/list.js +37 -9
- package/dist/list/list.js.map +1 -1
- package/dist/list/router.js.map +1 -1
- package/dist/plugins.d.ts +22 -10
- package/dist/plugins.d.ts.map +1 -1
- package/dist/plugins.js +23 -3
- package/dist/plugins.js.map +1 -1
- package/dist/preview.d.ts +14 -0
- package/dist/preview.d.ts.map +1 -0
- package/dist/react/leaveGuards.d.ts +34 -0
- package/dist/react/leaveGuards.d.ts.map +1 -0
- package/dist/react/leaveGuards.js +84 -0
- package/dist/react/leaveGuards.js.map +1 -0
- package/dist/react/provider.d.ts +4 -4
- package/dist/react/provider.js +3 -1
- package/dist/react/provider.js.map +1 -1
- package/dist/react/useForm.d.ts +1 -1
- package/dist/react/useForm.js.map +1 -1
- package/dist/react/useList.d.ts +1 -1
- package/dist/react/useList.js.map +1 -1
- package/dist/values.d.ts +1 -1
- package/dist/values.d.ts.map +1 -1
- package/dist/values.js +5 -1
- package/dist/values.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.js","names":[],"sources":["../../src/definition/list.ts"],"sourcesContent":["import type { Action, ActionPlacement, Column, Field, Filter, Resource } from '@panneau/protocol';\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 /** 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/**\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(resource.actions ?? []);\n const hasSelectionAction = (resource.actions ?? []).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 inlineEdit: list.inlineEdit ?? [],\n selectable: (list.selectable ?? true) && hasSelectionAction,\n actions,\n };\n}\n"],"mappings":";;;AAyCA,IAAM,uBAAuB;AAC7B,IAAM,mCAAmB,IAAI,IAAI;CAAC;CAAS;CAAY;AAAU,CAAC;AAElE,IAAa,mBAAmB;AAEhC,SAAS,kBAAkB,UAA8B;CACrD,MAAM,QAAQ,SAAS;CACvB,MAAM,SAAS,SAAS,OAAO,QAAQ,UAAU,CAAC,iBAAiB,IAAI,MAAM,IAAI,CAAC;CAQlF,QANI,UAAU,KAAA,IACJ,CACI,GAAG,OAAO,QAAQ,UAAU,MAAM,SAAS,KAAK,GAChD,GAAG,OAAO,QAAQ,UAAU,MAAM,SAAS,KAAK,CAAC,IAErD,OAAA,CACK,MAAM,GAAG,oBAAoB,CAAC,CAAC,KAAK,WAAW,EAAE,OAAO,MAAM,KAAK,EAAE;AACxF;;AAGA,SAAgB,aAAa,SAA+D;CACxF,MAAM,SAA4C;EAAE,KAAK,CAAA;EAAI,SAAS,CAAA;EAAI,MAAM,CAAA;EAAI,MAAM,CAAA;CAAG;CAC7F,QAAQ,OAAO,YAAY,CAAC,CAAC,SAAS,WAAW;EAC7C,oBAAoB,MAAM,CAAC,CAAC,SAAS,cAAc,OAAO,UAAU,CAAC,KAAK,MAAM,CAAC;CACrF,CAAC;CACD,OAAO;AACX;;;;;AAMA,SAAgB,YAAY,UAAkC;CAC1D,MAAM,OAAO,SAAS,QAAQ,CAAC;CAC/B,MAAM,SAAS,IAAI,IAAI,SAAS,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC;CAC1E,MAAM,QAAQ,KAAK,SAAS,CAAA;CAC5B,MAAM,WAAW,KAAK,WAAW,kBAAkB,QAAQ,EAAA,CAAG,KAAK,WAA2B;EAC1F,MAAM,QAAQ,OAAO,UAAU,KAAA,IAAa,OAAO,IAAI,OAAO,KAAK,KAAK,OAAQ;EAChF,MAAM,KAAK,OAAO,MAAM,OAAO,SAAS;EACxC,MAAM,WAA2B;GAC7B;GACA;GACA,OAAO,OAAO,SAAS,OAAO,SAAS;GACvC,SAAS,OAAO,WAAW,OAAO,WAAW,OAAO,QAAQ;GAC5D,UACI,OAAO,aAAa,OAAO,UAAU,KAAA,KAAa,MAAM,SAAS,OAAO,KAAK;EACrF;EACA,IAAI,OAAO,UAAU,KAAA,GACjB,SAAS,QAAQ,OAAO;EAE5B,IAAI,OAAO,UAAU,KAAA,GACjB,SAAS,QAAQ,OAAO;EAE5B,OAAO;CACX,CAAC;CACD,MAAM,UAAU,aAAa,SAAS,WAAW,CAAA,CAAE;CACnD,MAAM,sBAAsB,SAAS,WAAW,CAAA,EAAA,CAAI,MAC/C,WAAW,OAAO,MAAM,SAAS,WAAW,KAAK,aAAa,MAAM,CACzE;CACA,OAAO;EACH;EACA,SAAS,KAAK,WAAW,CAAA;EACzB;EACA,cAAc,KAAK,eAAe,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,SAAS,EAAE;EAC7E,QAAQ,KAAK,UAAU;EACvB,SAAS,KAAK,WAAW,CAAC,OAAO;EACjC,SAAS,KAAK,WAAA;EACd,gBAAgB,KAAK,kBAAkB,CAAA;EACvC,YAAY,KAAK,cAAc,CAAA;EAC/B,aAAa,KAAK,cAAc,SAAS;EACzC;CACJ;AACJ"}
|
|
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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AaL,OAAO6C,IAAID,OAAOxE,KAAK,KAAK,OAAQ;EAChF,MAAMD,KAAKyE,OAAOzE,MAAMyE,OAAOxE,SAAS;EACxC,MAAM0E,WAA2B;GAC7B3E;GACAC;GACAC,OAAOuE,OAAOvE,SAASD,OAAOC,SAASF;GACvCG,SAASsE,OAAOtE,WAAWF,OAAOE,WAAWF,OAAO+B,QAAQ;GAC5D5B,UACIqE,OAAOrE,aAAaqE,OAAOxE,UAAUiC,KAAAA,KAAaxB,MAAMkE,SAASH,OAAOxE,KAAK;EACrF;EACA,IAAIwE,OAAOpE,UAAU6B,KAAAA,GACjByC,SAAStE,QAAQoE,OAAOpE;EAE5B,IAAIoE,OAAOnE,UAAU4B,KAAAA,GACjByC,SAASrE,QAAQmE,OAAOnE;EAE5B,OAAOqE;CACX,CAAC;CACD,MAAMxD,UAAUmB,aAAaqB,mBAAmBjC,QAAQ,CAAC;CACzD,MAAMmD,qBAAqBlB,mBAAmBjC,QAAQ,CAAC,CAACoD,MACnDjC,WAAWA,OAAOO,MAAMwB,SAAS,WAAW,KAAK/E,aAAagD,MAAM,CACzE;CACA,OAAO;EACHrC;EACAC,SAAS8D,KAAK9D,WAAW,CAAA;EACzBC;EACAC,cAAc4D,KAAK5D,eAAe,GAAA,CAAIoE,MAAM,GAAG,CAAC,CAACjD,QAAQkD,SAASA,SAAS,EAAE;EAC7EpE,QAAQ2D,KAAK3D,UAAU;EACvBC,SAAS0D,KAAK1D,WAAW,CAAC,OAAO;EACjCC,SAASyD,KAAKzD,WAAAA;EACdC,gBAAgBwD,KAAKxD,kBAAkB,CAAA;EACvCC,YAAYuD,KAAKvD,cAAc;EAC/BC,YAAYsD,KAAKtD,cAAc,CAAA;EAC/BC,aAAaqD,KAAKrD,cAAc,SAAS2D;EACzC1D;CACJ;AACJ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Definition, Resource } from '@panneau/protocol';
|
|
2
|
-
import { type ResolveFormOptions, type ResolvedForm } from './form';
|
|
3
|
-
import { type ResolvedList } from './list';
|
|
2
|
+
import { type ResolveFormOptions, type ResolvedForm } from './form.js';
|
|
3
|
+
import { type ResolvedList } from './list.js';
|
|
4
4
|
/** What the current user can do with a resource as a whole. */
|
|
5
5
|
export interface ResourceAbilities {
|
|
6
6
|
viewAny: boolean;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { can } from "./abilities.js";
|
|
2
|
-
import { resolveForm } from "./form.js";
|
|
3
2
|
import { resolveList } from "./list.js";
|
|
3
|
+
import { resolveForm } from "./form.js";
|
|
4
4
|
//#region src/definition/resource.ts
|
|
5
5
|
/** Resolves a resource into its form, its list and its abilities. */
|
|
6
6
|
function resolveResource(resource, formOptions = { mode: "create" }) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.js","names":[],"sources":["../../src/definition/resource.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\n\nimport { can } from './abilities';\nimport { type ResolveFormOptions, type ResolvedForm, resolveForm } from './form';\nimport { type ResolvedList, resolveList } from './list';\n\n/** What the current user can do with a resource as a whole. */\nexport interface ResourceAbilities {\n viewAny: boolean;\n create: boolean;\n}\n\n/** A resource with its form, its list and its abilities resolved. */\nexport interface ResolvedResource {\n resource: Resource;\n /** The form to create an item. Use `resolveForm()` for an update, or an item type. */\n form: ResolvedForm;\n list: ResolvedList;\n abilities: ResourceAbilities;\n}\n\n/** Resolves a resource into its form, its list and its abilities. */\nexport function resolveResource(\n resource: Resource,\n formOptions: ResolveFormOptions = { mode: 'create' },\n): ResolvedResource {\n return {\n resource,\n form: resolveForm(resource, formOptions),\n list: resolveList(resource),\n abilities: {\n viewAny: can(resource.abilities, 'viewAny'),\n create: can(resource.abilities, 'create'),\n },\n };\n}\n\n/** Finds a resource of a definition by id. */\nexport function findResource(definition: Definition, id: string): Resource | undefined {\n return definition.resources.find((resource) => resource.id === id);\n}\n"],"mappings":";;;;;AAsBA,
|
|
1
|
+
{"version":3,"file":"resource.js","names":["Definition","Resource","can","ResolveFormOptions","ResolvedForm","resolveForm","ResolvedList","resolveList","ResourceAbilities","viewAny","create","ResolvedResource","resource","form","list","abilities","resolveResource","formOptions","mode","findResource","definition","id","resources","find"],"sources":["../../src/definition/resource.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\n\nimport { can } from './abilities';\nimport { type ResolveFormOptions, type ResolvedForm, resolveForm } from './form';\nimport { type ResolvedList, resolveList } from './list';\n\n/** What the current user can do with a resource as a whole. */\nexport interface ResourceAbilities {\n viewAny: boolean;\n create: boolean;\n}\n\n/** A resource with its form, its list and its abilities resolved. */\nexport interface ResolvedResource {\n resource: Resource;\n /** The form to create an item. Use `resolveForm()` for an update, or an item type. */\n form: ResolvedForm;\n list: ResolvedList;\n abilities: ResourceAbilities;\n}\n\n/** Resolves a resource into its form, its list and its abilities. */\nexport function resolveResource(\n resource: Resource,\n formOptions: ResolveFormOptions = { mode: 'create' },\n): ResolvedResource {\n return {\n resource,\n form: resolveForm(resource, formOptions),\n list: resolveList(resource),\n abilities: {\n viewAny: can(resource.abilities, 'viewAny'),\n create: can(resource.abilities, 'create'),\n },\n };\n}\n\n/** Finds a resource of a definition by id. */\nexport function findResource(definition: Definition, id: string): Resource | undefined {\n return definition.resources.find((resource) => resource.id === id);\n}\n"],"mappings":";;;;;AAsBA,SAAgBgB,gBACZJ,UACAK,cAAkC,EAAEC,MAAM,SAAS,GACnC;CAChB,OAAO;EACHN;EACAC,MAAMR,YAAYO,UAAUK,WAAW;EACvCH,MAAMP,YAAYK,QAAQ;EAC1BG,WAAW;GACPN,SAASP,IAAIU,SAASG,WAAW,SAAS;GAC1CL,QAAQR,IAAIU,SAASG,WAAW,QAAQ;EAC5C;CACJ;AACJ;;AAGA,SAAgBI,aAAaC,YAAwBC,IAAkC;CACnF,OAAOD,WAAWE,UAAUC,MAAMX,aAAaA,SAASS,OAAOA,EAAE;AACrE"}
|
package/dist/form/form.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';
|
|
2
|
-
import type { FormMode } from '../definition/form';
|
|
3
|
-
import { type Values } from '../values';
|
|
4
|
-
import { type FormStore } from './store';
|
|
2
|
+
import type { FormMode } from '../definition/form.js';
|
|
3
|
+
import { type Values } from '../values.js';
|
|
4
|
+
import { type FormStore } from './store.js';
|
|
5
5
|
/**
|
|
6
6
|
* - `idle`: nothing submitted yet, or after a reset;
|
|
7
7
|
* - `submitting`: waiting for `onSubmit`;
|
|
@@ -95,6 +95,11 @@ export interface GetErrorsOptions {
|
|
|
95
95
|
* (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).
|
|
96
96
|
*/
|
|
97
97
|
export interface Form {
|
|
98
|
+
/**
|
|
99
|
+
* Whether the form creates or updates an item: its `mode` option, or `update` with a version
|
|
100
|
+
* and `create` without. Rules limited to a mode apply in this one.
|
|
101
|
+
*/
|
|
102
|
+
readonly mode: FormMode;
|
|
98
103
|
getState(): FormState;
|
|
99
104
|
subscribe(listener: () => void): () => void;
|
|
100
105
|
/** Updates the options that can change between renders. */
|
package/dist/form/form.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/form/form.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAG7E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,KAAK,MAAM,EAAyB,MAAM,WAAW,CAAC;AAI/D,OAAO,EAAE,KAAK,SAAS,EAAoB,MAAM,SAAS,CAAC;AAE3D;;;;;;;GAOG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC;AAEhG,MAAM,WAAW,YAAY;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C,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB;;;OAGG;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,MAAM,EAAE,CAAC;IAC9D;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAAC;IAC9C;;;;OAIG;IACH,SAAS,CAAC,MAAM,EAAE;QAAE,WAAW,CAAC,EAAE,SAAS,GAAG,SAAS,CAAA;KAAE,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IACzF,+FAA+F;IAC/F,QAAQ,IAAI,OAAO,CAAC;IACpB,wCAAwC;IACxC,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC;IACxD,wCAAwC;IACxC,MAAM,IAAI,OAAO,CAAC,YAAY,CAAC,CAAC;IAChC,4EAA4E;IAC5E,KAAK,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;IACtD;;;;;OAKG;IACH,eAAe,CAAC,MAAM,EAAE,QAAQ,GAAG,WAAW,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;CACjF;AAED,mEAAmE;AACnE,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,EAAE,MAAM,GAAE,MAAW,GAAG,MAAM,CAQtF;AAYD,+BAA+B;AAC/B,wBAAgB,UAAU,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CA0QrD"}
|
package/dist/form/form.js
CHANGED
package/dist/form/form.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form.js","names":[],"sources":["../../src/form/form.ts"],"sourcesContent":["import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';\nimport { checkValues, getValue } from '@panneau/protocol/runtime';\n\nimport type { FormMode } from '../definition/form';\nimport { type Values, isEqual, isPathWithin } from '../values';\nimport { formatRuleFailure } from './messages';\nimport { getItemValues, getProblem, isItem } from './problem';\nimport { selectErrorCount, selectErrors, selectValue, selectVisible } from './selectors';\nimport { type FormStore, createLocalStore } from './store';\n\n/**\n * - `idle`: nothing submitted yet, or after a reset;\n * - `submitting`: waiting for `onSubmit`;\n * - `submitted`: the last submit succeeded;\n * - `invalid`: client validation or the server (`422`) found errors;\n * - `conflict`: the item changed since the form's version (`412`), see `resolveConflict()`;\n * - `error`: the last submit failed for another reason (network, `403`, `500`…), see `error`.\n */\nexport type FormStatus = 'idle' | 'submitting' | 'submitted' | 'invalid' | 'conflict' | 'error';\n\nexport interface FormConflict {\n /** The current version of the item, when the backend sent it. */\n current: Item | null;\n}\n\n/** A snapshot of a form. A new object is created on every change. */\nexport interface FormState {\n values: Values;\n /** The values the form started from, or was last saved with. `dirty` compares to them. */\n initialValues: Values;\n /** The version of the item the values were edited from, sent with the submit. */\n version: string | null;\n /** Whether the values differ from the initial values. */\n dirty: boolean;\n /**\n * Errors shown, by dot path (`title.fr`): client errors of touched fields (all of them after a\n * submit), then server errors. A server error goes away when its value changes.\n */\n errors: Record<string, string[]>;\n /** Paths of the fields that lost focus at least once. */\n touched: ReadonlySet<string>;\n status: FormStatus;\n /** With the `conflict` status: what the backend says is current. */\n conflict: FormConflict | null;\n /** With the `error` status: what `onSubmit` threw. */\n error: unknown;\n submitCount: number;\n}\n\nexport interface SubmitContext {\n mode: FormMode;\n /** The version to send as `If-Match`. */\n version: string | null;\n /** The top-level values that differ from the initial values, for partial updates. */\n changes: Values;\n}\n\nexport type SubmitResult =\n | { status: 'submitted'; result: unknown }\n | { status: 'invalid'; errors: Record<string, string[]> }\n | { status: 'conflict'; current: Item | null }\n | { status: 'error'; error: unknown };\n\nexport interface FormOptions {\n /** The fields of the form, as resolved by `resolveForm()`. */\n fields: Field[];\n /** Initial values. In `create` mode, fields without a value get their `default`. */\n values?: Values;\n /** The version of the item the values come from. */\n version?: string | null;\n /** Defaults to `update` when a version is given, `create` otherwise. */\n mode?: FormMode;\n /** Locales a `required` localized field must be filled in (all of them, usually). */\n locales?: string[];\n /** Where the values live. Defaults to a local store. */\n store?: FormStore;\n /** Message of a failed rule. Defaults to `formatRuleFailure()`. */\n formatError?: (failure: RuleFailure, path: string) => string;\n /**\n * Saves the values. When it returns an item, the form continues from that item. When it\n * throws an error that carries problem details (`getProblem()`), `422` errors are shown by\n * path and `412` puts the form in the `conflict` status.\n */\n onSubmit?: (values: Values, context: SubmitContext) => unknown;\n}\n\n/** Form options that can change after the form is created. */\nexport type UpdatableFormOptions = Pick<\n FormOptions,\n 'fields' | 'locales' | 'formatError' | 'onSubmit'\n>;\n\nexport interface GetErrorsOptions {\n /** Also return the errors of nested paths (`title.fr` for `title`). */\n nested?: boolean;\n}\n\n/**\n * A headless form: values, errors, visibility and submit. React components use `useForm()`.\n *\n * The methods that read the state (`getValue()`, `getErrors()`, `countErrors()`, `isVisible()`)\n * are not React APIs: the React Compiler memoizes their calls by their arguments, so they return\n * stale results in components. Components read the state they subscribed to with the selectors\n * (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).\n */\nexport interface Form {\n getState(): FormState;\n subscribe(listener: () => void): () => void;\n /** Updates the options that can change between renders. */\n setOptions(options: Partial<UpdatableFormOptions>): void;\n /**\n * The value at a dot path. Not a React API: components use `selectValue(state, path)` (see\n * {@link Form}).\n */\n getValue(path: string): unknown;\n setValue(path: string, value: unknown): void;\n /** Marks a field as touched, which shows its client errors. */\n blur(path: string): void;\n /**\n * Errors at a path. Not a React API: components use `selectErrors(state, path, options)` (see\n * {@link Form}).\n */\n getErrors(path: string, options?: GetErrorsOptions): string[];\n /**\n * The number of paths with errors within the given paths, for counts on tabs and sections. Not\n * a React API: components use `selectErrorCount(state, paths)` (see {@link Form}).\n */\n countErrors(paths: readonly string[]): number;\n /**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it. Not a\n * React API: components use `selectVisible(state, target, parentPath)` (see {@link Form}).\n */\n isVisible(target: { visibleWhen?: Condition | undefined }, parentPath?: string): boolean;\n /** Checks every value with the portable rules and shows every error. Returns whether valid. */\n validate(): boolean;\n /** Shows server errors, by dot path. */\n setServerErrors(errors: Record<string, string[]>): void;\n /** Validates, then calls `onSubmit`. */\n submit(): Promise<SubmitResult>;\n /** Starts over from new values (or the initial ones), and a new version. */\n reset(values?: Values, version?: string | null): void;\n /**\n * Leaves the `conflict` status:\n *\n * - `reload` drops the local changes and continues from the current item;\n * - `overwrite` keeps the local changes and submits them again over the current version.\n */\n resolveConflict(choice: 'reload' | 'overwrite'): Promise<SubmitResult | null>;\n}\n\n/** Initial values of fields that have a `default` and no value. */\nexport function getDefaultValues(fields: readonly Field[], values: Values = {}): Values {\n return fields.reduce<Values>(\n (result, field) =>\n field.default !== undefined && result[field.name] === undefined\n ? { ...result, [field.name]: field.default }\n : result,\n values,\n );\n}\n\nfunction mergeErrors(...sources: Record<string, string[]>[]): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n sources.forEach((source) =>\n Object.entries(source).forEach(([path, messages]) => {\n merged[path] = [...(merged[path] ?? []), ...messages];\n }),\n );\n return merged;\n}\n\n/** Creates a headless form. */\nexport function createForm(options: FormOptions): Form {\n const current: Required<UpdatableFormOptions> = {\n fields: options.fields,\n locales: options.locales ?? [],\n formatError: options.formatError ?? formatRuleFailure,\n onSubmit: options.onSubmit ?? (() => undefined),\n };\n const mode: FormMode =\n options.mode ??\n (options.version !== undefined && options.version !== null ? 'update' : 'create');\n const startValues =\n mode === 'create'\n ? getDefaultValues(options.fields, options.values)\n : (options.values ?? {});\n const store = options.store ?? createLocalStore(startValues);\n if (options.store !== undefined && options.values !== undefined) {\n store.setValues(startValues);\n }\n\n let initialValues = store.getValues();\n let version = options.version ?? null;\n let touched: ReadonlySet<string> = new Set();\n let serverErrors: Record<string, string[]> = {};\n let status: FormStatus = 'idle';\n let conflict: FormConflict | null = null;\n let error: unknown = null;\n let submitCount = 0;\n let pending: Promise<SubmitResult> | null = null;\n\n const listeners = new Set<() => void>();\n let unsubscribeStore: (() => void) | null = null;\n\n const clientErrors = (values: Values, all: boolean): Record<string, string[]> => {\n const failures = checkValues(current.fields, values, { mode, locales: current.locales });\n return Object.fromEntries(\n Object.entries(failures)\n .filter(\n ([path]) => all || [...touched].some((parent) => isPathWithin(path, parent)),\n )\n .map(([path, list]) => [\n path,\n list.map((failure) => current.formatError(failure, path)),\n ]),\n );\n };\n\n const compute = (values: Values): FormState => ({\n values,\n initialValues,\n version,\n dirty: !isEqual(values, initialValues),\n errors: mergeErrors(clientErrors(values, submitCount > 0), serverErrors),\n touched,\n status,\n conflict,\n error,\n submitCount,\n });\n\n let state = compute(store.getValues());\n\n const update = () => {\n state = compute(store.getValues());\n listeners.forEach((listener) => listener());\n };\n\n /** Server errors go away when their value changes. */\n const onStoreChange = () => {\n const previous = state.values;\n const values = store.getValues();\n if (values === previous) {\n return;\n }\n serverErrors = Object.fromEntries(\n Object.entries(serverErrors).filter(([path]) =>\n isEqual(getValue(previous, path), getValue(values, path)),\n ),\n );\n update();\n };\n\n const changes = (values: Values): Values =>\n Object.fromEntries(\n Object.entries({ ...initialValues, ...values }).flatMap(([key]) =>\n isEqual(values[key], initialValues[key]) ? [] : [[key, values[key]]],\n ),\n );\n\n const fieldNames = () => current.fields.map((field) => field.name);\n\n const reset = (values?: Values, nextVersion?: string | null) => {\n if (nextVersion !== undefined) {\n version = nextVersion;\n }\n touched = new Set();\n serverErrors = {};\n status = 'idle';\n conflict = null;\n error = null;\n submitCount = 0;\n if (values !== undefined) {\n initialValues = values;\n store.setValues(values);\n } else {\n store.setValues(initialValues);\n }\n update();\n };\n\n const runSubmit = async (): Promise<SubmitResult> => {\n submitCount += 1;\n serverErrors = {};\n const values = store.getValues();\n const errors = clientErrors(values, true);\n if (Object.keys(errors).length > 0) {\n status = 'invalid';\n update();\n return { status: 'invalid', errors };\n }\n status = 'submitting';\n conflict = null;\n error = null;\n update();\n try {\n const result = await current.onSubmit(values, {\n mode,\n version,\n changes: changes(values),\n });\n if (isItem(result)) {\n const saved = getItemValues(result, fieldNames());\n version = result.version;\n initialValues = saved;\n // Keep what was typed while saving; otherwise take the saved values.\n if (store.getValues() === values) {\n store.setValues(saved);\n }\n } else {\n initialValues = values;\n }\n touched = new Set();\n submitCount = 0;\n status = 'submitted';\n update();\n return { status: 'submitted', result };\n } catch (caught) {\n const problem = getProblem(caught);\n if (problem?.status === 412) {\n status = 'conflict';\n conflict = { current: problem.current ?? null };\n update();\n return { status: 'conflict', current: conflict.current };\n }\n if (problem?.status === 422 && problem.errors !== undefined) {\n status = 'invalid';\n serverErrors = problem.errors;\n update();\n return { status: 'invalid', errors: problem.errors };\n }\n status = 'error';\n error = caught;\n update();\n return { status: 'error', error: caught };\n }\n };\n\n const form: Form = {\n getState() {\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n unsubscribeStore ??= store.subscribe(onStoreChange);\n onStoreChange();\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeStore !== null) {\n unsubscribeStore();\n unsubscribeStore = null;\n }\n };\n },\n setOptions(next) {\n const { fields, locales, formatError, onSubmit } = next;\n if (onSubmit !== undefined) {\n current.onSubmit = onSubmit;\n }\n if (formatError !== undefined) {\n current.formatError = formatError;\n }\n // Fields and locales change what is valid: compare them by value, since a render can\n // create new arrays with the same content.\n const changed =\n (fields !== undefined && !isEqual(fields, current.fields)) ||\n (locales !== undefined && !isEqual(locales, current.locales));\n if (fields !== undefined) {\n current.fields = fields;\n }\n if (locales !== undefined) {\n current.locales = locales;\n }\n if (changed) {\n update();\n }\n },\n getValue: (path) => selectValue(form.getState(), path),\n setValue(path, value) {\n store.setValue(path, value);\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n },\n blur(path) {\n if (touched.has(path)) {\n return;\n }\n touched = new Set([...touched, path]);\n update();\n },\n getErrors: (path, getErrorsOptions) =>\n selectErrors(form.getState(), path, getErrorsOptions),\n countErrors: (paths) => selectErrorCount(form.getState(), paths),\n isVisible: (target, parentPath) => selectVisible(form.getState(), target, parentPath),\n validate() {\n submitCount = Math.max(submitCount, 1);\n update();\n return Object.keys(clientErrors(store.getValues(), true)).length === 0;\n },\n setServerErrors(errors) {\n serverErrors = errors;\n update();\n },\n submit() {\n pending ??= runSubmit().finally(() => {\n pending = null;\n });\n return pending;\n },\n reset,\n async resolveConflict(choice) {\n if (status !== 'conflict' || conflict === null) {\n return null;\n }\n const latest = conflict.current;\n if (choice === 'reload') {\n if (latest !== null) {\n reset(getItemValues(latest, fieldNames()), latest.version);\n } else {\n status = 'idle';\n conflict = null;\n update();\n }\n return null;\n }\n if (latest !== null) {\n version = latest.version;\n }\n conflict = null;\n return form.submit();\n },\n };\n return form;\n}\n"],"mappings":";;;;;;;;AAwJA,SAAgB,iBAAiB,QAA0B,SAAiB,CAAC,GAAW;CACpF,OAAO,OAAO,QACT,QAAQ,UACL,MAAM,YAAY,KAAA,KAAa,OAAO,MAAM,UAAU,KAAA,IAChD;EAAE,GAAG;GAAS,MAAM,OAAO,MAAM;CAAQ,IACzC,QACV,MACJ;AACJ;AAEA,SAAS,YAAY,GAAG,SAA+D;CACnF,MAAM,SAAmC,CAAC;CAC1C,QAAQ,SAAS,WACb,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,MAAM,cAAc;EACjD,OAAO,QAAQ,CAAC,GAAI,OAAO,SAAS,CAAA,GAAK,GAAG,QAAQ;CACxD,CAAC,CACL;CACA,OAAO;AACX;;AAGA,SAAgB,WAAW,SAA4B;CACnD,MAAM,UAA0C;EAC5C,QAAQ,QAAQ;EAChB,SAAS,QAAQ,WAAW,CAAA;EAC5B,aAAa,QAAQ,eAAe;EACpC,UAAU,QAAQ,mBAAmB,KAAA;CACzC;CACA,MAAM,OACF,QAAQ,SACP,QAAQ,YAAY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3,"file":"form.js","names":["Condition","Field","Item","RuleFailure","checkValues","getValue","FormMode","Values","isEqual","isPathWithin","formatRuleFailure","getItemValues","getProblem","isItem","selectErrorCount","selectErrors","selectValue","selectVisible","FormStore","createLocalStore","FormStatus","FormConflict","current","FormState","values","initialValues","version","dirty","errors","Record","touched","ReadonlySet","status","conflict","error","submitCount","SubmitContext","mode","changes","SubmitResult","result","FormOptions","fields","locales","store","formatError","failure","path","onSubmit","context","UpdatableFormOptions","Pick","GetErrorsOptions","nested","Form","getState","subscribe","listener","setOptions","options","Partial","setValue","value","blur","getErrors","countErrors","paths","isVisible","target","visibleWhen","parentPath","validate","setServerErrors","submit","Promise","reset","resolveConflict","choice","getDefaultValues","reduce","field","default","undefined","name","mergeErrors","sources","merged","forEach","source","Object","entries","messages","createForm","Required","startValues","setValues","getValues","Set","serverErrors","pending","listeners","unsubscribeStore","clientErrors","all","failures","fromEntries","filter","some","parent","map","list","compute","state","update","onStoreChange","previous","flatMap","key","fieldNames","nextVersion","runSubmit","keys","length","saved","caught","problem","form","add","delete","size","next","changed","has","getErrorsOptions","Math","max","finally","latest"],"sources":["../../src/form/form.ts"],"sourcesContent":["import type { Condition, Field, Item, RuleFailure } from '@panneau/protocol';\nimport { checkValues, getValue } from '@panneau/protocol/runtime';\n\nimport type { FormMode } from '../definition/form';\nimport { type Values, isEqual, isPathWithin } from '../values';\nimport { formatRuleFailure } from './messages';\nimport { getItemValues, getProblem, isItem } from './problem';\nimport { selectErrorCount, selectErrors, selectValue, selectVisible } from './selectors';\nimport { type FormStore, createLocalStore } from './store';\n\n/**\n * - `idle`: nothing submitted yet, or after a reset;\n * - `submitting`: waiting for `onSubmit`;\n * - `submitted`: the last submit succeeded;\n * - `invalid`: client validation or the server (`422`) found errors;\n * - `conflict`: the item changed since the form's version (`412`), see `resolveConflict()`;\n * - `error`: the last submit failed for another reason (network, `403`, `500`…), see `error`.\n */\nexport type FormStatus = 'idle' | 'submitting' | 'submitted' | 'invalid' | 'conflict' | 'error';\n\nexport interface FormConflict {\n /** The current version of the item, when the backend sent it. */\n current: Item | null;\n}\n\n/** A snapshot of a form. A new object is created on every change. */\nexport interface FormState {\n values: Values;\n /** The values the form started from, or was last saved with. `dirty` compares to them. */\n initialValues: Values;\n /** The version of the item the values were edited from, sent with the submit. */\n version: string | null;\n /** Whether the values differ from the initial values. */\n dirty: boolean;\n /**\n * Errors shown, by dot path (`title.fr`): client errors of touched fields (all of them after a\n * submit), then server errors. A server error goes away when its value changes.\n */\n errors: Record<string, string[]>;\n /** Paths of the fields that lost focus at least once. */\n touched: ReadonlySet<string>;\n status: FormStatus;\n /** With the `conflict` status: what the backend says is current. */\n conflict: FormConflict | null;\n /** With the `error` status: what `onSubmit` threw. */\n error: unknown;\n submitCount: number;\n}\n\nexport interface SubmitContext {\n mode: FormMode;\n /** The version to send as `If-Match`. */\n version: string | null;\n /** The top-level values that differ from the initial values, for partial updates. */\n changes: Values;\n}\n\nexport type SubmitResult =\n | { status: 'submitted'; result: unknown }\n | { status: 'invalid'; errors: Record<string, string[]> }\n | { status: 'conflict'; current: Item | null }\n | { status: 'error'; error: unknown };\n\nexport interface FormOptions {\n /** The fields of the form, as resolved by `resolveForm()`. */\n fields: Field[];\n /** Initial values. In `create` mode, fields without a value get their `default`. */\n values?: Values;\n /** The version of the item the values come from. */\n version?: string | null;\n /** Defaults to `update` when a version is given, `create` otherwise. */\n mode?: FormMode;\n /** Locales a `required` localized field must be filled in (all of them, usually). */\n locales?: string[];\n /** Where the values live. Defaults to a local store. */\n store?: FormStore;\n /** Message of a failed rule. Defaults to `formatRuleFailure()`. */\n formatError?: (failure: RuleFailure, path: string) => string;\n /**\n * Saves the values. When it returns an item, the form continues from that item. When it\n * throws an error that carries problem details (`getProblem()`), `422` errors are shown by\n * path and `412` puts the form in the `conflict` status.\n */\n onSubmit?: (values: Values, context: SubmitContext) => unknown;\n}\n\n/** Form options that can change after the form is created. */\nexport type UpdatableFormOptions = Pick<\n FormOptions,\n 'fields' | 'locales' | 'formatError' | 'onSubmit'\n>;\n\nexport interface GetErrorsOptions {\n /** Also return the errors of nested paths (`title.fr` for `title`). */\n nested?: boolean;\n}\n\n/**\n * A headless form: values, errors, visibility and submit. React components use `useForm()`.\n *\n * The methods that read the state (`getValue()`, `getErrors()`, `countErrors()`, `isVisible()`)\n * are not React APIs: the React Compiler memoizes their calls by their arguments, so they return\n * stale results in components. Components read the state they subscribed to with the selectors\n * (`selectValue()`, `selectErrors()`, `selectErrorCount()`, `selectVisible()`).\n */\nexport interface Form {\n /**\n * Whether the form creates or updates an item: its `mode` option, or `update` with a version\n * and `create` without. Rules limited to a mode apply in this one.\n */\n readonly mode: FormMode;\n getState(): FormState;\n subscribe(listener: () => void): () => void;\n /** Updates the options that can change between renders. */\n setOptions(options: Partial<UpdatableFormOptions>): void;\n /**\n * The value at a dot path. Not a React API: components use `selectValue(state, path)` (see\n * {@link Form}).\n */\n getValue(path: string): unknown;\n setValue(path: string, value: unknown): void;\n /** Marks a field as touched, which shows its client errors. */\n blur(path: string): void;\n /**\n * Errors at a path. Not a React API: components use `selectErrors(state, path, options)` (see\n * {@link Form}).\n */\n getErrors(path: string, options?: GetErrorsOptions): string[];\n /**\n * The number of paths with errors within the given paths, for counts on tabs and sections. Not\n * a React API: components use `selectErrorCount(state, paths)` (see {@link Form}).\n */\n countErrors(paths: readonly string[]): number;\n /**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it. Not a\n * React API: components use `selectVisible(state, target, parentPath)` (see {@link Form}).\n */\n isVisible(target: { visibleWhen?: Condition | undefined }, parentPath?: string): boolean;\n /** Checks every value with the portable rules and shows every error. Returns whether valid. */\n validate(): boolean;\n /** Shows server errors, by dot path. */\n setServerErrors(errors: Record<string, string[]>): void;\n /** Validates, then calls `onSubmit`. */\n submit(): Promise<SubmitResult>;\n /** Starts over from new values (or the initial ones), and a new version. */\n reset(values?: Values, version?: string | null): void;\n /**\n * Leaves the `conflict` status:\n *\n * - `reload` drops the local changes and continues from the current item;\n * - `overwrite` keeps the local changes and submits them again over the current version.\n */\n resolveConflict(choice: 'reload' | 'overwrite'): Promise<SubmitResult | null>;\n}\n\n/** Initial values of fields that have a `default` and no value. */\nexport function getDefaultValues(fields: readonly Field[], values: Values = {}): Values {\n return fields.reduce<Values>(\n (result, field) =>\n field.default !== undefined && result[field.name] === undefined\n ? { ...result, [field.name]: field.default }\n : result,\n values,\n );\n}\n\nfunction mergeErrors(...sources: Record<string, string[]>[]): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n sources.forEach((source) =>\n Object.entries(source).forEach(([path, messages]) => {\n merged[path] = [...(merged[path] ?? []), ...messages];\n }),\n );\n return merged;\n}\n\n/** Creates a headless form. */\nexport function createForm(options: FormOptions): Form {\n const current: Required<UpdatableFormOptions> = {\n fields: options.fields,\n locales: options.locales ?? [],\n formatError: options.formatError ?? formatRuleFailure,\n onSubmit: options.onSubmit ?? (() => undefined),\n };\n const mode: FormMode =\n options.mode ??\n (options.version !== undefined && options.version !== null ? 'update' : 'create');\n const startValues =\n mode === 'create'\n ? getDefaultValues(options.fields, options.values)\n : (options.values ?? {});\n const store = options.store ?? createLocalStore(startValues);\n if (options.store !== undefined && options.values !== undefined) {\n store.setValues(startValues);\n }\n\n let initialValues = store.getValues();\n let version = options.version ?? null;\n let touched: ReadonlySet<string> = new Set();\n let serverErrors: Record<string, string[]> = {};\n let status: FormStatus = 'idle';\n let conflict: FormConflict | null = null;\n let error: unknown = null;\n let submitCount = 0;\n let pending: Promise<SubmitResult> | null = null;\n\n const listeners = new Set<() => void>();\n let unsubscribeStore: (() => void) | null = null;\n\n const clientErrors = (values: Values, all: boolean): Record<string, string[]> => {\n const failures = checkValues(current.fields, values, { mode, locales: current.locales });\n return Object.fromEntries(\n Object.entries(failures)\n .filter(\n ([path]) => all || [...touched].some((parent) => isPathWithin(path, parent)),\n )\n .map(([path, list]) => [\n path,\n list.map((failure) => current.formatError(failure, path)),\n ]),\n );\n };\n\n const compute = (values: Values): FormState => ({\n values,\n initialValues,\n version,\n dirty: !isEqual(values, initialValues),\n errors: mergeErrors(clientErrors(values, submitCount > 0), serverErrors),\n touched,\n status,\n conflict,\n error,\n submitCount,\n });\n\n let state = compute(store.getValues());\n\n const update = () => {\n state = compute(store.getValues());\n listeners.forEach((listener) => listener());\n };\n\n /** Server errors go away when their value changes. */\n const onStoreChange = () => {\n const previous = state.values;\n const values = store.getValues();\n if (values === previous) {\n return;\n }\n serverErrors = Object.fromEntries(\n Object.entries(serverErrors).filter(([path]) =>\n isEqual(getValue(previous, path), getValue(values, path)),\n ),\n );\n update();\n };\n\n const changes = (values: Values): Values =>\n Object.fromEntries(\n Object.entries({ ...initialValues, ...values }).flatMap(([key]) =>\n isEqual(values[key], initialValues[key]) ? [] : [[key, values[key]]],\n ),\n );\n\n const fieldNames = () => current.fields.map((field) => field.name);\n\n const reset = (values?: Values, nextVersion?: string | null) => {\n if (nextVersion !== undefined) {\n version = nextVersion;\n }\n touched = new Set();\n serverErrors = {};\n status = 'idle';\n conflict = null;\n error = null;\n submitCount = 0;\n if (values !== undefined) {\n initialValues = values;\n store.setValues(values);\n } else {\n store.setValues(initialValues);\n }\n update();\n };\n\n const runSubmit = async (): Promise<SubmitResult> => {\n submitCount += 1;\n serverErrors = {};\n const values = store.getValues();\n const errors = clientErrors(values, true);\n if (Object.keys(errors).length > 0) {\n status = 'invalid';\n update();\n return { status: 'invalid', errors };\n }\n status = 'submitting';\n conflict = null;\n error = null;\n update();\n try {\n const result = await current.onSubmit(values, {\n mode,\n version,\n changes: changes(values),\n });\n if (isItem(result)) {\n const saved = getItemValues(result, fieldNames());\n version = result.version;\n initialValues = saved;\n // Keep what was typed while saving; otherwise take the saved values.\n if (store.getValues() === values) {\n store.setValues(saved);\n }\n } else {\n initialValues = values;\n }\n touched = new Set();\n submitCount = 0;\n status = 'submitted';\n update();\n return { status: 'submitted', result };\n } catch (caught) {\n const problem = getProblem(caught);\n if (problem?.status === 412) {\n status = 'conflict';\n conflict = { current: problem.current ?? null };\n update();\n return { status: 'conflict', current: conflict.current };\n }\n if (problem?.status === 422 && problem.errors !== undefined) {\n status = 'invalid';\n serverErrors = problem.errors;\n update();\n return { status: 'invalid', errors: problem.errors };\n }\n status = 'error';\n error = caught;\n update();\n return { status: 'error', error: caught };\n }\n };\n\n const form: Form = {\n mode,\n getState() {\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n unsubscribeStore ??= store.subscribe(onStoreChange);\n onStoreChange();\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeStore !== null) {\n unsubscribeStore();\n unsubscribeStore = null;\n }\n };\n },\n setOptions(next) {\n const { fields, locales, formatError, onSubmit } = next;\n if (onSubmit !== undefined) {\n current.onSubmit = onSubmit;\n }\n if (formatError !== undefined) {\n current.formatError = formatError;\n }\n // Fields and locales change what is valid: compare them by value, since a render can\n // create new arrays with the same content.\n const changed =\n (fields !== undefined && !isEqual(fields, current.fields)) ||\n (locales !== undefined && !isEqual(locales, current.locales));\n if (fields !== undefined) {\n current.fields = fields;\n }\n if (locales !== undefined) {\n current.locales = locales;\n }\n if (changed) {\n update();\n }\n },\n getValue: (path) => selectValue(form.getState(), path),\n setValue(path, value) {\n store.setValue(path, value);\n if (unsubscribeStore === null) {\n onStoreChange();\n }\n },\n blur(path) {\n if (touched.has(path)) {\n return;\n }\n touched = new Set([...touched, path]);\n update();\n },\n getErrors: (path, getErrorsOptions) =>\n selectErrors(form.getState(), path, getErrorsOptions),\n countErrors: (paths) => selectErrorCount(form.getState(), paths),\n isVisible: (target, parentPath) => selectVisible(form.getState(), target, parentPath),\n validate() {\n submitCount = Math.max(submitCount, 1);\n update();\n return Object.keys(clientErrors(store.getValues(), true)).length === 0;\n },\n setServerErrors(errors) {\n serverErrors = errors;\n update();\n },\n submit() {\n pending ??= runSubmit().finally(() => {\n pending = null;\n });\n return pending;\n },\n reset,\n async resolveConflict(choice) {\n if (status !== 'conflict' || conflict === null) {\n return null;\n }\n const latest = conflict.current;\n if (choice === 'reload') {\n if (latest !== null) {\n reset(getItemValues(latest, fieldNames()), latest.version);\n } else {\n status = 'idle';\n conflict = null;\n update();\n }\n return null;\n }\n if (latest !== null) {\n version = latest.version;\n }\n conflict = null;\n return form.submit();\n },\n };\n return form;\n}\n"],"mappings":";;;;;;;;AA6JA,SAAgB8E,iBAAiBpC,QAA0BlB,SAAiB,CAAC,GAAW;CACpF,OAAOkB,OAAOqC,QACTvC,QAAQwC,UACLA,MAAMC,YAAYC,KAAAA,KAAa1C,OAAOwC,MAAMG,UAAUD,KAAAA,IAChD;EAAE,GAAG1C;GAASwC,MAAMG,OAAOH,MAAMC;CAAQ,IACzCzC,QACVhB,MACJ;AACJ;AAEA,SAAS4D,YAAY,GAAGC,SAA+D;CACnF,MAAMC,SAAmC,CAAC;CAC1CD,QAAQE,SAASC,WACbC,OAAOC,QAAQF,MAAM,CAAC,CAACD,SAAS,CAACxC,MAAM4C,cAAc;EACjDL,OAAOvC,QAAQ,CAAC,GAAIuC,OAAOvC,SAAS,CAAA,GAAK,GAAG4C,QAAQ;CACxD,CAAC,CACL;CACA,OAAOL;AACX;;AAGA,SAAgBM,WAAWjC,SAA4B;CACnD,MAAMrC,UAA0C;EAC5CoB,QAAQiB,QAAQjB;EAChBC,SAASgB,QAAQhB,WAAW,CAAA;EAC5BE,aAAac,QAAQd,eAAenC;EACpCsC,UAAUW,QAAQX,mBAAmBkC,KAAAA;CACzC;CACA,MAAM7C,OACFsB,QAAQtB,SACPsB,QAAQjC,YAAYwD,KAAAA,KAAavB,QAAQjC,YAAY,OAAO,WAAW;CAC5E,MAAMoE,cACFzD,SAAS,WACHyC,iBAAiBnB,QAAQjB,QAAQiB,QAAQnC,MAAM,IAC9CmC,QAAQnC,UAAU,CAAC;CAC9B,MAAMoB,QAAQe,QAAQf,SAASzB,iBAAiB2E,WAAW;CAC3D,IAAInC,QAAQf,UAAUsC,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D,gBAAgB5C,QAAQ;GACpBsE,eAAetE;GACfqF,OAAO;EACX;EACAxC,SAAS;GACL0B,YAAYqB,UAAU,CAAC,CAACgB,cAAc;IAClCrC,UAAU;GACd,CAAC;GACD,OAAOA;EACX;EACAxB;EACA,MAAMC,gBAAgBC,QAAQ;GAC1B,IAAI7C,WAAW,cAAcC,aAAa,MACtC,OAAO;GAEX,MAAMwG,SAASxG,SAASX;GACxB,IAAIuD,WAAW,UAAU;IACrB,IAAI4D,WAAW,MACX9D,MAAMhE,cAAc8H,QAAQnB,WAAW,CAAC,GAAGmB,OAAO/G,OAAO;SACtD;KACHM,SAAS;KACTC,WAAW;KACXgF,OAAO;IACX;IACA,OAAO;GACX;GACA,IAAIwB,WAAW,MACX/G,UAAU+G,OAAO/G;GAErBO,WAAW;GACX,OAAO6F,KAAKrD,OAAO;EACvB;CACJ;CACA,OAAOqD;AACX"}
|
|
@@ -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;
|
|
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"}
|
package/dist/form/messages.js
CHANGED
|
@@ -6,6 +6,7 @@ var MESSAGES = {
|
|
|
6
6
|
pattern: () => "This value has an invalid format.",
|
|
7
7
|
email: () => "This value must be an email address.",
|
|
8
8
|
url: () => "This value must be a URL.",
|
|
9
|
+
json: () => "This value must be valid JSON: an object or an array.",
|
|
9
10
|
in: () => "This value is not one of the choices.",
|
|
10
11
|
accept: () => "This file type is not accepted.",
|
|
11
12
|
maxSize: () => "This file is too large.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","names":[],"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 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,
|
|
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"}
|
package/dist/form/problem.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Item, Problem } from '@panneau/protocol';
|
|
2
|
-
import type { Values } from '../values';
|
|
2
|
+
import type { Values } from '../values.js';
|
|
3
3
|
/**
|
|
4
4
|
* The problem details carried by an error: the error itself when it is a problem, or its
|
|
5
5
|
* `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw
|
package/dist/form/problem.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"problem.js","names":[],"sources":["../../src/form/problem.ts"],"sourcesContent":["import type { Item, Problem } from '@panneau/protocol';\nimport { isProblem } from '@panneau/protocol/runtime';\n\nimport type { Values } from '../values';\n\n/**\n * The problem details carried by an error: the error itself when it is a problem, or its\n * `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw\n * errors with a `problem` for forms to show validation errors and conflicts.\n */\nexport function getProblem(error: unknown): Problem | null {\n if (isProblem(error)) {\n return error;\n }\n if (error !== null && typeof error === 'object' && 'problem' in error) {\n return isProblem(error.problem) ? error.problem : null;\n }\n return null;\n}\n\nconst ITEM_KEYS = new Set(['id', 'version', 'abilities']);\n\n/** Whether a value looks like an item of the protocol (`id`, `version`, `abilities`). */\nexport function isItem(value: unknown): value is Item {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const item = value as Record<string, unknown>;\n return (\n typeof item.id === 'string' &&\n (typeof item.version === 'string' || item.version === null) &&\n item.abilities !== null &&\n typeof item.abilities === 'object'\n );\n}\n\n/**\n * The values of an item: every property except `id`, `version` and `abilities`, or only the\n * given field names.\n */\nexport function getItemValues(item: Item, names?: readonly string[]): Values {\n return Object.fromEntries(\n Object.entries(item).filter(([key]) =>\n names !== undefined ? names.includes(key) : !ITEM_KEYS.has(key),\n ),\n );\n}\n"],"mappings":";;;;;;;AAUA,
|
|
1
|
+
{"version":3,"file":"problem.js","names":["Item","Problem","isProblem","Values","getProblem","error","problem","ITEM_KEYS","Set","isItem","value","item","Record","id","version","abilities","getItemValues","names","Object","fromEntries","entries","filter","key","undefined","includes","has"],"sources":["../../src/form/problem.ts"],"sourcesContent":["import type { Item, Problem } from '@panneau/protocol';\nimport { isProblem } from '@panneau/protocol/runtime';\n\nimport type { Values } from '../values';\n\n/**\n * The problem details carried by an error: the error itself when it is a problem, or its\n * `problem` property, as on the errors of `@panneau/data`. A custom adapter only needs to throw\n * errors with a `problem` for forms to show validation errors and conflicts.\n */\nexport function getProblem(error: unknown): Problem | null {\n if (isProblem(error)) {\n return error;\n }\n if (error !== null && typeof error === 'object' && 'problem' in error) {\n return isProblem(error.problem) ? error.problem : null;\n }\n return null;\n}\n\nconst ITEM_KEYS = new Set(['id', 'version', 'abilities']);\n\n/** Whether a value looks like an item of the protocol (`id`, `version`, `abilities`). */\nexport function isItem(value: unknown): value is Item {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const item = value as Record<string, unknown>;\n return (\n typeof item.id === 'string' &&\n (typeof item.version === 'string' || item.version === null) &&\n item.abilities !== null &&\n typeof item.abilities === 'object'\n );\n}\n\n/**\n * The values of an item: every property except `id`, `version` and `abilities`, or only the\n * given field names.\n */\nexport function getItemValues(item: Item, names?: readonly string[]): Values {\n return Object.fromEntries(\n Object.entries(item).filter(([key]) =>\n names !== undefined ? names.includes(key) : !ITEM_KEYS.has(key),\n ),\n );\n}\n"],"mappings":";;;;;;;AAUA,SAAgBI,WAAWC,OAAgC;CACvD,IAAIH,UAAUG,KAAK,GACf,OAAOA;CAEX,IAAIA,UAAU,QAAQ,OAAOA,UAAU,YAAY,aAAaA,OAC5D,OAAOH,UAAUG,MAAMC,OAAO,IAAID,MAAMC,UAAU;CAEtD,OAAO;AACX;AAEA,IAAMC,4BAAY,IAAIC,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;;AAGxD,SAAgBC,OAAOC,OAA+B;CAClD,IAAIA,UAAU,QAAQ,OAAOA,UAAU,UACnC,OAAO;CAEX,MAAMC,OAAOD;CACb,OACI,OAAOC,KAAKE,OAAO,aAClB,OAAOF,KAAKG,YAAY,YAAYH,KAAKG,YAAY,SACtDH,KAAKI,cAAc,QACnB,OAAOJ,KAAKI,cAAc;AAElC;;;;;AAMA,SAAgBC,cAAcL,MAAYM,OAAmC;CACzE,OAAOC,OAAOC,YACVD,OAAOE,QAAQT,IAAI,CAAC,CAACU,QAAQ,CAACC,SAC1BL,UAAUM,KAAAA,IAAYN,MAAMO,SAASF,GAAG,IAAI,CAACf,UAAUkB,IAAIH,GAAG,CAClE,CACJ;AACJ"}
|
package/dist/form/selectors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Condition } from '@panneau/protocol';
|
|
2
|
-
import type { FormState, GetErrorsOptions } from './form';
|
|
2
|
+
import type { FormState, GetErrorsOptions } from './form.js';
|
|
3
3
|
/** The value at a dot path (`title.fr`). */
|
|
4
4
|
export declare function selectValue(state: FormState, path: string): unknown;
|
|
5
5
|
/** Errors at a path, and with `nested` at the paths inside it (`title.fr` for `title`). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectors.js","names":[],"sources":["../../src/form/selectors.ts"],"sourcesContent":["/*\n * Reads of a form state. React components read the state they subscribed to (`useForm()`, or\n * `useSyncExternalStore(form.subscribe, form.getState)`) through these selectors, not through the\n * form's methods: the React Compiler memoizes calls by their arguments, and a method such as\n * `form.getErrors(path)` reads the store, so its memoized result goes stale. A selector takes the\n * state as an argument, so the compiler calls it again when the state changes.\n */\nimport type { Condition } from '@panneau/protocol';\nimport { evaluateCondition, getValue } from '@panneau/protocol/runtime';\n\nimport { isPathWithin } from '../values';\nimport type { FormState, GetErrorsOptions } from './form';\n\n/** The value at a dot path (`title.fr`). */\nexport function selectValue(state: FormState, path: string): unknown {\n return getValue(state.values, path);\n}\n\n/** Errors at a path, and with `nested` at the paths inside it (`title.fr` for `title`). */\nexport function selectErrors(\n state: FormState,\n path: string,\n options: GetErrorsOptions = {},\n): string[] {\n const { nested = false } = options;\n return Object.entries(state.errors).flatMap(([key, messages]) =>\n key === path || (nested && isPathWithin(key, path)) ? messages : [],\n );\n}\n\n/** The number of paths with errors within the given paths, for counts on tabs and sections. */\nexport function selectErrorCount(state: FormState, paths: readonly string[]): number {\n return Object.keys(state.errors).filter((key) => paths.some((path) => isPathWithin(key, path)))\n .length;\n}\n\n/**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it.\n */\nexport function selectVisible(\n state: FormState,\n target: { visibleWhen?: Condition | undefined },\n parentPath = '',\n): boolean {\n return (\n target.visibleWhen === undefined ||\n evaluateCondition(target.visibleWhen, getValue(state.values, parentPath))\n );\n}\n"],"mappings":";;;;AAcA,
|
|
1
|
+
{"version":3,"file":"selectors.js","names":["Condition","evaluateCondition","getValue","isPathWithin","FormState","GetErrorsOptions","selectValue","state","path","values","selectErrors","options","nested","Object","entries","errors","flatMap","key","messages","selectErrorCount","paths","keys","filter","some","length","selectVisible","target","visibleWhen","parentPath","undefined"],"sources":["../../src/form/selectors.ts"],"sourcesContent":["/*\n * Reads of a form state. React components read the state they subscribed to (`useForm()`, or\n * `useSyncExternalStore(form.subscribe, form.getState)`) through these selectors, not through the\n * form's methods: the React Compiler memoizes calls by their arguments, and a method such as\n * `form.getErrors(path)` reads the store, so its memoized result goes stale. A selector takes the\n * state as an argument, so the compiler calls it again when the state changes.\n */\nimport type { Condition } from '@panneau/protocol';\nimport { evaluateCondition, getValue } from '@panneau/protocol/runtime';\n\nimport { isPathWithin } from '../values';\nimport type { FormState, GetErrorsOptions } from './form';\n\n/** The value at a dot path (`title.fr`). */\nexport function selectValue(state: FormState, path: string): unknown {\n return getValue(state.values, path);\n}\n\n/** Errors at a path, and with `nested` at the paths inside it (`title.fr` for `title`). */\nexport function selectErrors(\n state: FormState,\n path: string,\n options: GetErrorsOptions = {},\n): string[] {\n const { nested = false } = options;\n return Object.entries(state.errors).flatMap(([key, messages]) =>\n key === path || (nested && isPathWithin(key, path)) ? messages : [],\n );\n}\n\n/** The number of paths with errors within the given paths, for counts on tabs and sections. */\nexport function selectErrorCount(state: FormState, paths: readonly string[]): number {\n return Object.keys(state.errors).filter((key) => paths.some((path) => isPathWithin(key, path)))\n .length;\n}\n\n/**\n * Whether a field or a layout node is visible, from its `visibleWhen`. For nested fields, pass\n * the path of the object they belong to (`blocks.2`): conditions are relative to it.\n */\nexport function selectVisible(\n state: FormState,\n target: { visibleWhen?: Condition | undefined },\n parentPath = '',\n): boolean {\n return (\n target.visibleWhen === undefined ||\n evaluateCondition(target.visibleWhen, getValue(state.values, parentPath))\n );\n}\n"],"mappings":";;;;AAcA,SAAgBM,YAAYC,OAAkBC,MAAuB;CACjE,OAAON,SAASK,MAAME,QAAQD,IAAI;AACtC;;AAGA,SAAgBE,aACZH,OACAC,MACAG,UAA4B,CAAC,GACrB;CACR,MAAM,EAAEC,SAAS,UAAUD;CAC3B,OAAOE,OAAOC,QAAQP,MAAMQ,MAAM,CAAC,CAACC,SAAS,CAACC,KAAKC,cAC/CD,QAAQT,QAASI,UAAUT,aAAac,KAAKT,IAAI,IAAKU,WAAW,CAAA,CACrE;AACJ;;AAGA,SAAgBC,iBAAiBZ,OAAkBa,OAAkC;CACjF,OAAOP,OAAOQ,KAAKd,MAAMQ,MAAM,CAAC,CAACO,QAAQL,QAAQG,MAAMG,MAAMf,SAASL,aAAac,KAAKT,IAAI,CAAC,CAAC,CAAC,CAC1FgB;AACT;;;;;AAMA,SAAgBC,cACZlB,OACAmB,QACAE,aAAa,IACN;CACP,OACIF,OAAOC,gBAAgBE,KAAAA,KACvB5B,kBAAkByB,OAAOC,aAAazB,SAASK,MAAME,QAAQmB,UAAU,CAAC;AAEhF"}
|
package/dist/form/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Values } from '../values';
|
|
1
|
+
import { type Values } from '../values.js';
|
|
2
2
|
/**
|
|
3
3
|
* Where the values of a form live. The form only reads and writes values through this interface,
|
|
4
4
|
* so a shared store (Yjs, in `@panneau/collab`) can replace the local one. Errors, touched fields
|
package/dist/form/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","names":[],"sources":["../../src/form/store.ts"],"sourcesContent":["import { type Values, setValue } from '../values';\n\n/**\n * Where the values of a form live. The form only reads and writes values through this interface,\n * so a shared store (Yjs, in `@panneau/collab`) can replace the local one. Errors, touched fields\n * and the submit status stay local to each form.\n */\nexport interface FormStore {\n /** The current values. The same object is returned until the values change. */\n getValues(): Values;\n /** Sets the value at a dot path. */\n setValue(path: string, value: unknown): void;\n /** Replaces every value. */\n setValues(values: Values): void;\n /** Calls `listener` after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n}\n\n/** A store that keeps the values in memory. */\nexport function createLocalStore(initialValues: Values = {}): FormStore {\n let values = initialValues;\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n getValues: () => values,\n setValue(path, value) {\n values = setValue(values, path, value);\n notify();\n },\n setValues(next) {\n values = next;\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"],"mappings":";;;AAmBA,
|
|
1
|
+
{"version":3,"file":"store.js","names":["Values","setValue","FormStore","getValues","path","value","setValues","values","subscribe","listener","createLocalStore","initialValues","listeners","Set","notify","forEach","next","add","delete"],"sources":["../../src/form/store.ts"],"sourcesContent":["import { type Values, setValue } from '../values';\n\n/**\n * Where the values of a form live. The form only reads and writes values through this interface,\n * so a shared store (Yjs, in `@panneau/collab`) can replace the local one. Errors, touched fields\n * and the submit status stay local to each form.\n */\nexport interface FormStore {\n /** The current values. The same object is returned until the values change. */\n getValues(): Values;\n /** Sets the value at a dot path. */\n setValue(path: string, value: unknown): void;\n /** Replaces every value. */\n setValues(values: Values): void;\n /** Calls `listener` after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n}\n\n/** A store that keeps the values in memory. */\nexport function createLocalStore(initialValues: Values = {}): FormStore {\n let values = initialValues;\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n getValues: () => values,\n setValue(path, value) {\n values = setValue(values, path, value);\n notify();\n },\n setValues(next) {\n values = next;\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"],"mappings":";;;AAmBA,SAAgBU,iBAAiBC,gBAAwB,CAAC,GAAc;CACpE,IAAIJ,SAASI;CACb,MAAMC,4BAAY,IAAIC,IAAgB;CACtC,MAAMC,eAAeF,UAAUG,SAASN,aAAaA,SAAS,CAAC;CAC/D,OAAO;EACHN,iBAAiBI;EACjBN,SAASG,MAAMC,OAAO;GAClBE,SAASN,SAASM,QAAQH,MAAMC,KAAK;GACrCS,OAAO;EACX;EACAR,UAAUU,MAAM;GACZT,SAASS;GACTF,OAAO;EACX;EACAN,UAAUC,UAAU;GAChBG,UAAUK,IAAIR,QAAQ;GACtB,aAAa;IACTG,UAAUM,OAAOT,QAAQ;GAC7B;EACJ;CACJ;AACJ"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
|
-
export { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction, } from './definition/abilities';
|
|
2
|
-
export { type
|
|
3
|
-
export {
|
|
4
|
-
export { type
|
|
5
|
-
export { type
|
|
6
|
-
export {
|
|
7
|
-
export {
|
|
8
|
-
export {
|
|
9
|
-
export {
|
|
10
|
-
export { type
|
|
11
|
-
export { type
|
|
12
|
-
export { type
|
|
13
|
-
export {
|
|
14
|
-
export { type
|
|
15
|
-
export { type
|
|
16
|
-
export { type
|
|
1
|
+
export { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction, } from './definition/abilities.js';
|
|
2
|
+
export { type ActionItem, type ItemAction, type ItemActionsOptions, type ItemSurface, fillActionUrl, getItemActions, selectItemActions, } from './definition/itemActions.js';
|
|
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';
|
|
5
|
+
export { type ResolvedResource, type ResourceAbilities, findResource, resolveResource, } from './definition/resource.js';
|
|
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
|
+
export { formatRuleFailure } from './form/messages.js';
|
|
8
|
+
export { getItemValues, getProblem, isItem } from './form/problem.js';
|
|
9
|
+
export { selectErrorCount, selectErrors, selectValue, selectVisible } from './form/selectors.js';
|
|
10
|
+
export { type FormStore, createLocalStore } from './form/store.js';
|
|
11
|
+
export { type List, type ListDefaults, type ListOptions, type ListSelection, type ListState, createList, } from './list/list.js';
|
|
12
|
+
export { type MemoryRouter, type Router, createHistoryRouter, createMemoryRouter, } from './list/router.js';
|
|
13
|
+
export { type Messages, type MessagesLoader, type PanneauPlugin, type PluginComponent, type PluginComponentKind, type PluginRegistry, type Theme, createPluginRegistry, definePlugin, loadMessages, resolveTheme, } from './plugins.js';
|
|
14
|
+
export { type Command, type CommandContext, type CommandSource, getCommands, getSearchableResources, isSearchable, } from './commands.js';
|
|
15
|
+
export { type PreviewProps } from './preview.js';
|
|
16
|
+
export { type LeaveGuard, type LeaveGuards, LeaveGuardsProvider, type LeaveGuardsProviderProps, createLeaveGuards, useLeaveGuard, useLeaveGuards, } from './react/leaveGuards.js';
|
|
17
|
+
export { PanneauProvider, type PanneauContextValue, type PanneauProviderProps, usePanneau, usePlugins, useResource, } from './react/provider.js';
|
|
18
|
+
export { type UseFormFieldResult, type UseFormResult, useForm, useFormField, } from './react/useForm.js';
|
|
19
|
+
export { type UseListResult, useList } from './react/useList.js';
|
|
20
|
+
export { type Values, isEqual, setValue } from './values.js';
|
|
17
21
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,GAAG,EACH,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,GACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACH,KAAK,QAAQ,EACb,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,mBAAmB,EACnB,aAAa,EACb,WAAW,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACH,gBAAgB,EAChB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,YAAY,EACZ,WAAW,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACH,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,YAAY,EACZ,eAAe,GAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACH,KAAK,IAAI,EACT,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,UAAU,EACV,gBAAgB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EAA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BAAmB,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"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { can, canRunAction, getActionPlacements, isActionAllowedOn, partitionByAction } from "./definition/abilities.js";
|
|
2
|
+
import { DEFAULT_PER_PAGE, getOpenMode, getResourceActions, groupActions, resolveList } from "./definition/list.js";
|
|
3
|
+
import { fillActionUrl, getItemActions, selectItemActions } from "./definition/itemActions.js";
|
|
2
4
|
import { getLayoutFieldNames, resolveFields, resolveForm } from "./definition/form.js";
|
|
3
|
-
import { DEFAULT_PER_PAGE, groupActions, resolveList } from "./definition/list.js";
|
|
4
5
|
import { findResource, resolveResource } from "./definition/resource.js";
|
|
5
6
|
import { isEqual, setValue } from "./values.js";
|
|
6
7
|
import { formatRuleFailure } from "./form/messages.js";
|
|
@@ -10,8 +11,10 @@ import { createLocalStore } from "./form/store.js";
|
|
|
10
11
|
import { createForm, getDefaultValues } from "./form/form.js";
|
|
11
12
|
import { createList } from "./list/list.js";
|
|
12
13
|
import { createHistoryRouter, createMemoryRouter } from "./list/router.js";
|
|
13
|
-
import { createPluginRegistry, definePlugin, loadMessages } from "./plugins.js";
|
|
14
|
+
import { createPluginRegistry, definePlugin, loadMessages, resolveTheme } from "./plugins.js";
|
|
15
|
+
import { getCommands, getSearchableResources, isSearchable } from "./commands.js";
|
|
16
|
+
import { LeaveGuardsProvider, createLeaveGuards, useLeaveGuard, useLeaveGuards } from "./react/leaveGuards.js";
|
|
14
17
|
import { PanneauProvider, usePanneau, usePlugins, useResource } from "./react/provider.js";
|
|
15
18
|
import { useForm, useFormField } from "./react/useForm.js";
|
|
16
19
|
import { useList } from "./react/useList.js";
|
|
17
|
-
export { DEFAULT_PER_PAGE, PanneauProvider, can, canRunAction, createForm, createHistoryRouter, createList, createLocalStore, createMemoryRouter, createPluginRegistry, definePlugin, findResource, formatRuleFailure, getActionPlacements, getDefaultValues, getItemValues, getLayoutFieldNames, getProblem, groupActions, isActionAllowedOn, isEqual, isItem, loadMessages, partitionByAction, resolveFields, resolveForm, resolveList, resolveResource, selectErrorCount, selectErrors, selectValue, selectVisible, setValue, useForm, useFormField, useList, usePanneau, usePlugins, useResource };
|
|
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 };
|
package/dist/list/list.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { FilterValue, ListQuery, Selection } from '@panneau/protocol';
|
|
2
|
-
import type { ResolvedList } from '../definition/list';
|
|
3
|
-
import type { Router } from './router';
|
|
2
|
+
import type { ResolvedList } from '../definition/list.js';
|
|
3
|
+
import type { Router } from './router.js';
|
|
4
4
|
/**
|
|
5
5
|
* Selected items: some ids, or every item matching the list query (filters and search) except
|
|
6
6
|
* some ids. "All matching" covers the items of every page.
|
|
@@ -37,6 +37,17 @@ export interface List {
|
|
|
37
37
|
getState(): ListState;
|
|
38
38
|
subscribe(listener: () => void): () => void;
|
|
39
39
|
setPage(page: number): void;
|
|
40
|
+
/**
|
|
41
|
+
* In a list paged with cursors: goes to the page of `nextCursor`, and remembers the cursor of
|
|
42
|
+
* the page it leaves, for `previousPage()`.
|
|
43
|
+
*/
|
|
44
|
+
nextPage(cursor: string): void;
|
|
45
|
+
/**
|
|
46
|
+
* In a list paged with cursors: goes back a page, to `previousCursor` when the backend gives
|
|
47
|
+
* one (`null` for the first page), or else to the page it came from. Without either, it goes
|
|
48
|
+
* to the first page.
|
|
49
|
+
*/
|
|
50
|
+
previousPage(cursor?: string | null): void;
|
|
40
51
|
/** Sets the page size, and goes back to the first page. */
|
|
41
52
|
setPerPage(perPage: number): void;
|
|
42
53
|
/** Sets the sort (`['-published_at', 'title']`), and goes back to the first page. */
|
package/dist/list/list.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list.d.ts","sourceRoot":"","sources":["../../src/list/list.ts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E,MAAM,GAAG,IAAI,CAAC;IAC3B,wEAAwE;IACxE,UAAU,IAAI,IAAI,CAAC;IACnB,2FAA2F;IAC3F,MAAM,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IACrC,2FAA2F;IAC3F,QAAQ,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAAC;IACvC,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,4DAA4D;IAC5D,iBAAiB,IAAI,IAAI,CAAC;IAC1B,cAAc,IAAI,IAAI,CAAC;IACvB,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;IAChC,gEAAgE;IAChE,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACxC,gFAAgF;IAChF,YAAY,IAAI,SAAS,GAAG,IAAI,CAAC;CACpC;AA0CD,+BAA+B;AAC/B,wBAAgB,UAAU,CAAC,OAAO,GAAE,WAAgB,GAAG,IAAI,CAqM1D"}
|
package/dist/list/list.js
CHANGED
|
@@ -5,12 +5,18 @@ var EMPTY_SELECTION = {
|
|
|
5
5
|
mode: "ids",
|
|
6
6
|
ids: []
|
|
7
7
|
};
|
|
8
|
-
|
|
8
|
+
/** Back to the first page: page 1, or no cursor. */
|
|
9
|
+
var FIRST_PAGE = {
|
|
10
|
+
page: 1,
|
|
11
|
+
cursor: void 0
|
|
12
|
+
};
|
|
13
|
+
var LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|filter\[.+)$/;
|
|
9
14
|
/** Removes the values that are the defaults, so the URL only keeps what the user changed. */
|
|
10
15
|
function normalize(query, defaults) {
|
|
11
16
|
const result = {};
|
|
12
17
|
if (query.page !== void 0 && query.page > 1) result.page = query.page;
|
|
13
18
|
if (query.perPage !== void 0 && query.perPage !== defaults.perPage) result.perPage = query.perPage;
|
|
19
|
+
if (query.cursor !== void 0 && query.cursor !== "") result.cursor = query.cursor;
|
|
14
20
|
if (query.sort !== void 0 && !isEqual(query.sort, defaults.sort)) result.sort = [...query.sort];
|
|
15
21
|
const filter = Object.fromEntries(Object.entries(query.filter ?? {}).filter(([, value]) => value !== "" && !(Array.isArray(value) && value.length === 0) && !(isFilterRange(value) && Object.keys(value).length === 0)));
|
|
16
22
|
if (Object.keys(filter).length > 0) result.filter = filter;
|
|
@@ -28,10 +34,12 @@ function createList(options = {}) {
|
|
|
28
34
|
const readRouter = () => router !== null ? normalize(fromSearchParams(new URLSearchParams(router.getSearch())), defaults) : {};
|
|
29
35
|
let params = router !== null ? readRouter() : normalize(options.query ?? {}, defaults);
|
|
30
36
|
let selection = EMPTY_SELECTION;
|
|
37
|
+
let trail = [];
|
|
38
|
+
const cursors = options.list?.pagination === "cursor";
|
|
31
39
|
const compute = () => ({
|
|
32
40
|
query: {
|
|
33
41
|
...params,
|
|
34
|
-
page: params.page ?? 1,
|
|
42
|
+
...cursors ? {} : { page: params.page ?? 1 },
|
|
35
43
|
perPage: params.perPage ?? defaults.perPage,
|
|
36
44
|
...params.sort !== void 0 || defaults.sort.length > 0 ? { sort: params.sort ?? defaults.sort } : {}
|
|
37
45
|
},
|
|
@@ -55,6 +63,9 @@ function createList(options = {}) {
|
|
|
55
63
|
const normalized = normalize(next, defaults);
|
|
56
64
|
if (isEqual(normalized, params)) return;
|
|
57
65
|
const scopeChanged = !isEqual(normalized.filter, params.filter) || normalized.q !== params.q;
|
|
66
|
+
const { cursor: _next, ...nextQuery } = normalized;
|
|
67
|
+
const { cursor: _current, ...currentQuery } = params;
|
|
68
|
+
if (!isEqual(nextQuery, currentQuery)) trail = [];
|
|
58
69
|
params = normalized;
|
|
59
70
|
if (scopeChanged) selection = EMPTY_SELECTION;
|
|
60
71
|
writeRouter(replace);
|
|
@@ -95,33 +106,50 @@ function createList(options = {}) {
|
|
|
95
106
|
...params,
|
|
96
107
|
page
|
|
97
108
|
}),
|
|
109
|
+
nextPage(cursor) {
|
|
110
|
+
const current = params.cursor ?? null;
|
|
111
|
+
setParams({
|
|
112
|
+
...params,
|
|
113
|
+
cursor
|
|
114
|
+
});
|
|
115
|
+
trail = [...trail, current];
|
|
116
|
+
},
|
|
117
|
+
previousPage(cursor) {
|
|
118
|
+
const back = cursor !== void 0 ? cursor : trail.at(-1) ?? null;
|
|
119
|
+
const rest = trail.slice(0, -1);
|
|
120
|
+
setParams({
|
|
121
|
+
...params,
|
|
122
|
+
cursor: back ?? void 0
|
|
123
|
+
});
|
|
124
|
+
trail = rest;
|
|
125
|
+
},
|
|
98
126
|
setPerPage: (perPage) => setParams({
|
|
99
127
|
...params,
|
|
100
128
|
perPage,
|
|
101
|
-
|
|
129
|
+
...FIRST_PAGE
|
|
102
130
|
}),
|
|
103
131
|
setSort: (sort) => setParams({
|
|
104
132
|
...params,
|
|
105
133
|
sort: [...sort],
|
|
106
|
-
|
|
134
|
+
...FIRST_PAGE
|
|
107
135
|
}),
|
|
108
136
|
toggleSort(field) {
|
|
109
137
|
const sort = state.query.sort ?? [];
|
|
110
138
|
if (sort[0] === field) setParams({
|
|
111
139
|
...params,
|
|
112
140
|
sort: [`-${field}`],
|
|
113
|
-
|
|
141
|
+
...FIRST_PAGE
|
|
114
142
|
});
|
|
115
143
|
else if (sort[0] === `-${field}` && params.sort !== void 0) {
|
|
116
144
|
const { sort: _sort, ...rest } = params;
|
|
117
145
|
setParams({
|
|
118
146
|
...rest,
|
|
119
|
-
|
|
147
|
+
...FIRST_PAGE
|
|
120
148
|
});
|
|
121
149
|
} else setParams({
|
|
122
150
|
...params,
|
|
123
151
|
sort: [field],
|
|
124
|
-
|
|
152
|
+
...FIRST_PAGE
|
|
125
153
|
});
|
|
126
154
|
},
|
|
127
155
|
setFilter(id, value) {
|
|
@@ -132,13 +160,13 @@ function createList(options = {}) {
|
|
|
132
160
|
...filter,
|
|
133
161
|
[id]: value
|
|
134
162
|
},
|
|
135
|
-
|
|
163
|
+
...FIRST_PAGE
|
|
136
164
|
});
|
|
137
165
|
},
|
|
138
166
|
setSearch: (q) => setParams({
|
|
139
167
|
...params,
|
|
140
168
|
q,
|
|
141
|
-
|
|
169
|
+
...FIRST_PAGE
|
|
142
170
|
}, { replace: true }),
|
|
143
171
|
resetQuery: () => setParams({}),
|
|
144
172
|
select(ids) {
|