@panneau/core 5.0.0-alpha.5 → 5.0.0-alpha.7

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.
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\nimport { isSearchableResource } from '@panneau/protocol/runtime';\n\nimport { can } from './definition/abilities';\n\n/**\n * A command of the \"Go to…\" palette that a plugin adds (decision 0029): a link to follow or a\n * function to run, found by its label, description and keywords.\n */\nexport interface Command {\n /** Unique among the commands of the palette. */\n id: string;\n label: string;\n /** The group it is listed in. Defaults to the palette's group of commands. */\n group?: string;\n description?: string;\n /** More words it is found by. */\n keywords?: readonly string[];\n /** A Lucide icon name (`\"send\"`). */\n icon?: string;\n /** A path of the app, or a URL, to go to. */\n href?: string;\n /** What it does, without an `href`. */\n perform?: () => void;\n}\n\n/** What a plugin's commands can depend on. */\nexport interface CommandContext {\n /** The definition for the current user, or `null` outside of the app. */\n definition: Definition | null;\n}\n\n/** Commands, or a function that makes them for the current definition. */\nexport type CommandSource = readonly Command[] | ((context: CommandContext) => readonly Command[]);\n\n/** The commands of every source, in order. */\nexport function getCommands(sources: readonly CommandSource[], context: CommandContext): Command[] {\n return sources.flatMap((source) => (typeof source === 'function' ? source(context) : source));\n}\n\n/**\n * Whether a resource is in the global search: its `features.search`, or, without it, whether its\n * list has a search (`list.search`), so one setting serves both (decision 0029).\n */\nexport function isSearchable(resource: Resource): boolean {\n return isSearchableResource(resource);\n}\n\n/** The resources of the global search that the user can list. */\nexport function getSearchableResources(definition: Definition): Resource[] {\n return definition.resources.filter(\n (resource) => isSearchable(resource) && can(resource.abilities, 'viewAny'),\n );\n}\n"],"mappings":";;;;AAoCA,SAAgB,YAAY,SAAmC,SAAoC;CAC/F,OAAO,QAAQ,SAAS,WAAY,OAAO,WAAW,aAAa,OAAO,OAAO,IAAI,MAAO;AAChG;;;;;AAMA,SAAgB,aAAa,UAA6B;CACtD,OAAO,qBAAqB,QAAQ;AACxC;;AAGA,SAAgB,uBAAuB,YAAoC;CACvE,OAAO,WAAW,UAAU,QACvB,aAAa,aAAa,QAAQ,KAAK,IAAI,SAAS,WAAW,SAAS,CAC7E;AACJ"}
1
+ {"version":3,"file":"commands.js","names":["Definition","Resource","isSearchableResource","can","Command","id","label","group","description","keywords","icon","href","perform","CommandContext","definition","CommandSource","context","getCommands","sources","flatMap","source","isSearchable","resource","getSearchableResources","resources","filter","abilities"],"sources":["../src/commands.ts"],"sourcesContent":["import type { Definition, Resource } from '@panneau/protocol';\nimport { isSearchableResource } from '@panneau/protocol/runtime';\n\nimport { can } from './definition/abilities';\n\n/**\n * A command of the \"Go to…\" palette that a plugin adds (decision 0029): a link to follow or a\n * function to run, found by its label, description and keywords.\n */\nexport interface Command {\n /** Unique among the commands of the palette. */\n id: string;\n label: string;\n /** The group it is listed in. Defaults to the palette's group of commands. */\n group?: string;\n description?: string;\n /** More words it is found by. */\n keywords?: readonly string[];\n /** A Lucide icon name (`\"send\"`). */\n icon?: string;\n /** A path of the app, or a URL, to go to. */\n href?: string;\n /** What it does, without an `href`. */\n perform?: () => void;\n}\n\n/** What a plugin's commands can depend on. */\nexport interface CommandContext {\n /** The definition for the current user, or `null` outside of the app. */\n definition: Definition | null;\n}\n\n/** Commands, or a function that makes them for the current definition. */\nexport type CommandSource = readonly Command[] | ((context: CommandContext) => readonly Command[]);\n\n/** The commands of every source, in order. */\nexport function getCommands(sources: readonly CommandSource[], context: CommandContext): Command[] {\n return sources.flatMap((source) => (typeof source === 'function' ? source(context) : source));\n}\n\n/**\n * Whether a resource is in the global search: its `features.search`, or, without it, whether its\n * list has a search (`list.search`), so one setting serves both (decision 0029).\n */\nexport function isSearchable(resource: Resource): boolean {\n return isSearchableResource(resource);\n}\n\n/** The resources of the global search that the user can list. */\nexport function getSearchableResources(definition: Definition): Resource[] {\n return definition.resources.filter(\n (resource) => isSearchable(resource) && can(resource.abilities, 'viewAny'),\n );\n}\n"],"mappings":";;;;AAoCA,SAAgBiB,YAAYC,SAAmCF,SAAoC;CAC/F,OAAOE,QAAQC,SAASC,WAAY,OAAOA,WAAW,aAAaA,OAAOJ,OAAO,IAAII,MAAO;AAChG;;;;;AAMA,SAAgBC,aAAaC,UAA6B;CACtD,OAAOpB,qBAAqBoB,QAAQ;AACxC;;AAGA,SAAgBC,uBAAuBT,YAAoC;CACvE,OAAOA,WAAWU,UAAUC,QACvBH,aAAaD,aAAaC,QAAQ,KAAKnB,IAAImB,SAASI,WAAW,SAAS,CAC7E;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"abilities.js","names":[],"sources":["../../src/definition/abilities.ts"],"sourcesContent":["import type { Abilities, Action, ActionPlacement, Item } from '@panneau/protocol';\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 lists its id in\n * its abilities. Links to show and edit are allowed unless the item says otherwise.\n */\nexport function isActionAllowedOn(action: Action, item: Item): boolean {\n if (!canRunAction(action)) {\n return false;\n }\n if (action.kind === 'link') {\n return item.abilities[action.id] !== false;\n }\n return item.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/** Where an action appears when it doesn't say: rows and forms for items, the toolbar otherwise. */\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":";;;;;AAMA,SAAgB,IAAI,WAAkC,SAA0B;CAC5E,OAAO,cAAc,KAAA,KAAa,UAAU,aAAa;AAC7D;;AAGA,SAAgB,aAAa,QAAyB;CAClD,OAAO,OAAO,WAAW,QAAQ;AACrC;;;;;AAMA,SAAgB,kBAAkB,QAAgB,MAAqB;CACnE,IAAI,CAAC,aAAa,MAAM,GACpB,OAAO;CAEX,IAAI,OAAO,SAAS,QAChB,OAAO,KAAK,UAAU,OAAO,QAAQ;CAEzC,OAAO,KAAK,UAAU,OAAO,QAAQ;AACzC;;AAGA,SAAgB,kBACZ,QACA,OACoC;CACpC,MAAM,UAAkB,CAAA;CACxB,MAAM,UAAkB,CAAA;CACxB,MAAM,SAAS,UAAU,kBAAkB,QAAQ,IAAI,IAAI,UAAU,QAAA,CAAS,KAAK,IAAI,CAAC;CACxF,OAAO;EAAE;EAAS;CAAQ;AAC9B;;AAGA,SAAgB,oBAAoB,QAAmC;CACnE,IAAI,OAAO,cAAc,KAAA,GACrB,OAAO,OAAO;CAElB,MAAM,6BAAa,IAAI,IAAqB;CAC5C,OAAO,MAAM,SAAS,UAAU;EAC5B,IAAI,UAAU,QAAQ;GAClB,WAAW,IAAI,KAAK;GACpB,WAAW,IAAI,MAAM;EACzB,OACI,WAAW,IAAI,SAAS;CAEhC,CAAC;CACD,OAAO,CAAC,GAAG,UAAU;AACzB"}
1
+ {"version":3,"file":"abilities.js","names":["Abilities","Action","ActionPlacement","Item","can","abilities","ability","undefined","canRunAction","action","run","isActionAllowedOn","item","kind","id","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';\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 lists its id in\n * its abilities. Links to show and edit are allowed unless the item says otherwise.\n */\nexport function isActionAllowedOn(action: Action, item: Item): boolean {\n if (!canRunAction(action)) {\n return false;\n }\n if (action.kind === 'link') {\n return item.abilities[action.id] !== false;\n }\n return item.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/** Where an action appears when it doesn't say: rows and forms for items, the toolbar otherwise. */\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":";;;;;AAMA,SAAgBI,IAAIC,WAAkCC,SAA0B;CAC5E,OAAOD,cAAcE,KAAAA,KAAaF,UAAUC,aAAa;AAC7D;;AAGA,SAAgBE,aAAaC,QAAyB;CAClD,OAAOA,OAAOJ,WAAWK,QAAQ;AACrC;;;;;AAMA,SAAgBC,kBAAkBF,QAAgBG,MAAqB;CACnE,IAAI,CAACJ,aAAaC,MAAM,GACpB,OAAO;CAEX,IAAIA,OAAOI,SAAS,QAChB,OAAOD,KAAKP,UAAUI,OAAOK,QAAQ;CAEzC,OAAOF,KAAKP,UAAUI,OAAOK,QAAQ;AACzC;;AAGA,SAAgBC,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;;AAGA,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 +1 @@
1
- {"version":3,"file":"form.js","names":[],"sources":["../../src/definition/form.ts"],"sourcesContent":["import type { Field, LayoutNode, Resource } 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. Without a\n * 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/** 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 === 'create' && field.updateOnly === true) {\n return [];\n }\n if (mode === 'update' && field.createOnly === true) {\n return [{ ...field, readOnly: true }];\n }\n return [field];\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":";AA4BA,SAAS,gBAAgB,OAA8B,wBAAQ,IAAI,IAAY,GAAgB;CAC3F,MAAM,SAAS,SAAS;EACpB,IAAI,KAAK,SAAS,WAAW,KAAK,SAAS,KAAA,GACvC,MAAM,IAAI,KAAK,IAAI;EAEvB,gBAAgB,KAAK,YAAY,CAAA,GAAI,KAAK;CAC9C,CAAC;CACD,OAAO;AACX;AAEA,SAAS,YACL,OACA,QACY;CACZ,OAAO,M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,SAAgB,oBAAoB,QAAyC;CACzE,OAAO,CAAC,GAAG,gBAAgB,MAAM,CAAC;AACtC"}
1
+ {"version":3,"file":"form.js","names":["Field","LayoutNode","Resource","FormMode","ResolvedForm","fields","fieldsByName","ReadonlyMap","layout","ResolveFormOptions","mode","type","referencedNames","nodes","names","Set","forEach","node","name","undefined","add","children","pruneLayout","flatMap","has","resolveFields","Pick","resolved","field","updateOnly","createOnly","readOnly","Map","map","pruned","referenced","appended","filter","resolveForm","resource","options","typeFields","types","find","id","form","getLayoutFieldNames"],"sources":["../../src/definition/form.ts"],"sourcesContent":["import type { Field, LayoutNode, Resource } 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. Without a\n * 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/** 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 === 'create' && field.updateOnly === true) {\n return [];\n }\n if (mode === 'update' && field.createOnly === true) {\n return [{ ...field, readOnly: true }];\n }\n return [field];\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":";AA4BA,SAASY,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,KAAKC,IAAI,IAC1E,OAAO,CAAA;EAEX,IAAID,KAAKI,aAAaF,KAAAA,GAClB,OAAO,CAACF,IAAI;EAEhB,OAAO,CAAC;GAAE,GAAGA;GA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@
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,QAA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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","canRunAction","getActionPlacements","ResolvedColumn","id","field","label","display","sortable","width","align","ResolvedList","columns","filters","sorts","defaultSort","search","layouts","perPage","perPageOptions","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","resolveList","list","Map","column","get","resolved","includes","hasSelectionAction","some","scope","split","part"],"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,IAAM6B,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,QAAQ5B,UAAU,CAACoB,iBAAiBS,IAAI7B,MAAM8B,IAAI,CAAC;CAQlF,QANIL,UAAUO,KAAAA,IACJ,CACI,GAAGL,OAAOC,QAAQ5B,UAAUA,MAAMiC,SAASR,KAAK,GAChD,GAAGE,OAAOC,QAAQ5B,UAAUA,MAAMiC,SAASR,KAAK,CAAC,IAErDE,OAAAA,CACKO,MAAM,GAAGf,oBAAoB,CAAC,CAACgB,KAAKnC,WAAW,EAAEA,OAAOA,MAAMiC,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,OAAOhC,YAAY,CAAC,CAAC8C,SAASC,WAAW;EAC7C9C,oBAAoB8C,MAAM,CAAC,CAACD,SAASE,cAAcP,OAAOO,UAAU,CAACC,KAAKF,MAAM,CAAC;CACrF,CAAC;CACD,O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7E9C,QAAQoC,KAAKpC,UAAU;EACvBC,SAASmC,KAAKnC,WAAW,CAAC,OAAO;EACjCC,SAASkC,KAAKlC,WAAAA;EACdC,gBAAgBiC,KAAKjC,kBAAkB,CAAA;EACvCC,YAAYgC,KAAKhC,cAAc,CAAA;EAC/BC,aAAa+B,KAAK/B,cAAc,SAASqC;EACzCpC;CACJ;AACJ"}
@@ -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,SAAgB,gBACZ,UACA,cAAkC,EAAE,MAAM,SAAS,GACnC;CAChB,OAAO;EACH;EACA,MAAM,YAAY,UAAU,WAAW;EACvC,MAAM,YAAY,QAAQ;EAC1B,WAAW;GACP,SAAS,IAAI,SAAS,WAAW,SAAS;GAC1C,QAAQ,IAAI,SAAS,WAAW,QAAQ;EAC5C;CACJ;AACJ;;AAGA,SAAgB,aAAa,YAAwB,IAAkC;CACnF,OAAO,WAAW,UAAU,MAAM,aAAa,SAAS,OAAO,EAAE;AACrE"}
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"}
@@ -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,WA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G,OAAO,OAAO;SACtD;KACH,SAAS;KACT,WAAW;KACX,OAAO;IACX;IACA,OAAO;GACX;GACA,IAAI,WAAW,MACX,UAAU,OAAO;GAErB,WAAW;GACX,OAAO,KAAK,OAAO;EACvB;CACJ;CACA,OAAO;AACX"}
1
+ {"version":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 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,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,CAA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AAKnB,aAAa1D,MAAMoD,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC0B,WAAW;EACzE;EACAlD,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;AAgBrD;;;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;AAiBrD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE9D"}
@@ -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,IAAM,WAA6D;CAC/D,gBAAgB;CAChB,MAAM,YAAY,+BAA+B,OAAO,QAAQ,KAAK,EAAC;CACtE,MAAM,YAAY,8BAA8B,OAAO,QAAQ,KAAK,EAAC;CACrE,eAAe;CACf,aAAa;CACb,WAAW;CACX,UAAU;CACV,cAAc;CACd,eAAe;CACf,cAAc;CACd,aAAa;AACjB;;;;;AAMA,SAAgB,kBAAkB,SAA8B;CAC5D,OAAO,QAAQ,WAAW,SAAS,QAAQ,KAAK,GAAG,OAAO,KAAK;AACnE"}
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 +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,SAAgB,WAAW,OAAgC;CACvD,IAAI,UAAU,KAAK,GACf,OAAO;CAEX,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,aAAa,OAC5D,OAAO,UAAU,MAAM,OAAO,IAAI,MAAM,UAAU;CAEtD,OAAO;AACX;AAEA,IAAM,4BAAY,IAAI,IAAI;CAAC;CAAM;CAAW;AAAW,CAAC;;AAGxD,SAAgB,OAAO,OAA+B;CAClD,IAAI,UAAU,QAAQ,OAAO,UAAU,UACnC,OAAO;CAEX,MAAM,OAAO;CACb,OACI,OAAO,KAAK,OAAO,aAClB,OAAO,KAAK,YAAY,YAAY,KAAK,YAAY,SACtD,KAAK,cAAc,QACnB,OAAO,KAAK,cAAc;AAElC;;;;;AAMA,SAAgB,cAAc,MAAY,OAAmC;CACzE,OAAO,OAAO,YACV,OAAO,QAAQ,IAAI,CAAC,CAAC,QAAQ,CAAC,SAC1B,UAAU,KAAA,IAAY,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,IAAI,GAAG,CAClE,CACJ;AACJ"}
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"}
@@ -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,SAAgB,YAAY,OAAkB,MAAuB;CACjE,OAAO,SAAS,MAAM,QAAQ,IAAI;AACtC;;AAGA,SAAgB,aACZ,OACA,MACA,UAA4B,CAAC,GACrB;CACR,MAAM,EAAE,SAAS,UAAU;CAC3B,OAAO,OAAO,QAAQ,MAAM,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,cAC/C,QAAQ,QAAS,UAAU,aAAa,KAAK,IAAI,IAAK,WAAW,CAAA,CACrE;AACJ;;AAGA,SAAgB,iBAAiB,OAAkB,OAAkC;CACjF,OAAO,OAAO,KAAK,MAAM,MAAM,CAAC,CAAC,QAAQ,QAAQ,MAAM,MAAM,SAAS,aAAa,KAAK,IAAI,CAAC,CAAC,CAAC,CAC1F;AACT;;;;;AAMA,SAAgB,cACZ,OACA,QACA,aAAa,IACN;CACP,OACI,OAAO,gBAAgB,KAAA,KACvB,kBAAkB,OAAO,aAAa,SAAS,MAAM,QAAQ,UAAU,CAAC;AAEhF"}
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"}
@@ -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,SAAgB,iBAAiB,gBAAwB,CAAC,GAAc;CACpE,IAAI,SAAS;CACb,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAe,UAAU,SAAS,aAAa,SAAS,CAAC;CAC/D,OAAO;EACH,iBAAiB;EACjB,SAAS,MAAM,OAAO;GAClB,SAAS,SAAS,QAAQ,MAAM,KAAK;GACrC,OAAO;EACX;EACA,UAAU,MAAM;GACZ,SAAS;GACT,OAAO;EACX;EACA,UAAU,UAAU;GAChB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACT,UAAU,OAAO,QAAQ;GAC7B;EACJ;CACJ;AACJ"}
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"}
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":[],"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 /** 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: [] };\nconst LIST_PARAM = /^(page|perPage|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.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\n const compute = (): ListState => ({\n query: {\n ...params,\n 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 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 setPerPage: (perPage) => setParams({ ...params, perPage, page: 1 }),\n setSort: (sort) => setParams({ ...params, sort: [...sort], page: 1 }),\n toggleSort(field) {\n const sort = state.query.sort ?? [];\n if (sort[0] === field) {\n setParams({ ...params, sort: [`-${field}`], page: 1 });\n } else if (sort[0] === `-${field}` && params.sort !== undefined) {\n const { sort: _sort, ...rest } = params;\n setParams({ ...rest, page: 1 });\n } else {\n setParams({ ...params, sort: [field], page: 1 });\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 page: 1,\n });\n },\n setSearch: (q) => setParams({ ...params, q, page: 1 }, { 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":";;;AAqEA,IAAM,kBAAiC;CAAE,MAAM;CAAO,KAAK,CAAA;AAAG;AAC9D,IAAM,aAAa;;AAGnB,SAAS,UAAU,OAAkB,UAA6C;CAC9E,MAAM,SAAoB,CAAC;CAC3B,IAAI,MAAM,SAAS,KAAA,KAAa,MAAM,OAAO,GACzC,OAAO,OAAO,MAAM;CAExB,IAAI,MAAM,YAAY,KAAA,KAAa,MAAM,YAAY,SAAS,SAC1D,OAAO,UAAU,MAAM;CAE3B,IAAI,MAAM,SAAS,KAAA,KAAa,CAAC,QAAQ,MAAM,MAAM,SAAS,IAAI,GAC9D,OAAO,OAAO,CAAC,GAAG,MAAM,IAAI;CAEhC,MAAM,SAAS,OAAO,YAClB,OAA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GAAG,GAAG,CAAC,CAAC;GAAE,CAAC;EAEnF;EACA,SAAS,KAAK;GACV,IAAI,UAAU,SAAS,OACnB,aAAa;IAAE,MAAM;IAAO,QAAQ,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,UAAU,QAAQ,GAAG,GAAG,CAAC,CAAC;GAAE,CAAC;QAEjF,aAAa;IAAE,MAAM;IAAO,KAAK,UAAU,IAAI,QAAQ,OAAO,CAAC,IAAI,SAAS,EAAE,CAAC;GAAE,CAAC;EAE1F;EACA,OAAO,IAAI;GACP,IAAI,KAAK,WAAW,EAAE,GAClB,KAAK,SAAS,CAAC,EAAE,CAAC;QAElB,KAAK,OAAO,CAAC,EAAE,CAAC;EAExB;EACA,yBAAyB,aAAa;GAAE,MAAM;GAAO,QAAQ,CAAA;EAAG,CAAC;EACjE,sBAAsB,aAAa,eAAe;EAClD,aAAa,OACT,UAAU,SAAS,QAAQ,CAAC,UAAU,OAAO,SAAS,EAAE,IAAI,UAAU,IAAI,SAAS,EAAE;EACzF,mBAAmB,UACf,UAAU,SAAS,QACb,KAAK,IAAI,GAAG,QAAQ,UAAU,OAAO,MAAM,IAC3C,UAAU,IAAI;EACxB,eAAe;GACX,IAAI,UAAU,SAAS,OACnB,OAAO,UAAU,IAAI,SAAS,IAAI,EAAE,KAAK,CAAC,GAAG,UAAU,GAAG,EAAE,IAAI;GAEpE,MAAM,QAA0D,CAAC;GACjE,IAAI,OAAO,WAAW,KAAA,GAClB,MAAM,SAAS,OAAO;GAE1B,IAAI,OAAO,MAAM,KAAA,GACb,MAAM,IAAI,OAAO;GAErB,OAAO,UAAU,OAAO,SAAS,IAC3B;IAAE;IAAO,QAAQ,CAAC,GAAG,UAAU,MAAM;GAAE,IACvC,EAAE,MAAM;EAClB;CACJ;CACA,OAAO;AACX"}
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","setPerPage","setSort","toggleSort","field","setFilter","id","value","setSearch","q","resetQuery","select","deselect","toggle","selectAllMatching","clearSelection","isSelected","getSelectedCount","total","getSelection","EMPTY_SELECTION","LIST_PARAM","normalize","Required","result","undefined","filter","Object","fromEntries","entries","Array","isArray","length","keys","fields","createList","options","defaultSort","readRouter","URLSearchParams","getSearch","params","compute","state","listeners","Set","notify","forEach","writeRouter","replace","search","key","test","delete","append","next","toString","setParams","normalized","scopeChanged","setSelection","unsubscribeRouter","onRouterChange","add","size","_sort","rest","_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 /** 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: [] };\nconst LIST_PARAM = /^(page|perPage|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.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\n const compute = (): ListState => ({\n query: {\n ...params,\n 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 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 setPerPage: (perPage) => setParams({ ...params, perPage, page: 1 }),\n setSort: (sort) => setParams({ ...params, sort: [...sort], page: 1 }),\n toggleSort(field) {\n const sort = state.query.sort ?? [];\n if (sort[0] === field) {\n setParams({ ...params, sort: [`-${field}`], page: 1 });\n } else if (sort[0] === `-${field}` && params.sort !== undefined) {\n const { sort: _sort, ...rest } = params;\n setParams({ ...rest, page: 1 });\n } else {\n setParams({ ...params, sort: [field], page: 1 });\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 page: 1,\n });\n },\n setSearch: (q) => setParams({ ...params, q, page: 1 }, { 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":";;;AAqEA,IAAMgD,kBAAiC;CAAEtC,MAAM;CAAOC,KAAK,CAAA;AAAG;AAC9D,IAAMsC,aAAa;;AAGnB,SAASC,UAAUpC,OAAkBO,UAA6C;CAC9E,MAAM+B,SAAoB,CAAC;CAC3B,IAAItC,MAAMc,SAASyB,KAAAA,KAAavC,MAAMc,OAAO,GACzCwB,OAAOxB,OAAOd,MAAMc;CAExB,IAAId,MAAMG,YAAYoC,KAAAA,KAAavC,MAAMG,YAAYI,SAASJ,SAC1DmC,OAAOnC,UAAUH,MAAMG;CAE3B,IAAIH,MAAMI,SAASmC,KAAAA,KAAa,CAAC9C,QAAQO,MAAMI,MAAMG,SAASH,IAAI,GAC9DkC,OAAOlC,OAAO,CAAC,GAAGJ,MAAMI,IAAI;CAEhC,MAAMoC,SAASC,OAAOC,YAClBD,OAAOE,QAAQ3C,MAAMwC,UAAU,CAAC,CAAC,CAAC,CAACA,QAC9B,GAAGnB,WACAA,UAAU,MACV,EAAEuB,MAAMC,QAAQxB,KAAK,KAAKA,MAAMyB,WAAW,MAC3C,EAAExD,cAAc+B,KAAK,KAAKoB,OAAOM,KAAK1B,KAAK,CAAC,CAACyB,WAAW,EAChE,CACJ;CACA,IAAIL,OAAOM,KAAKP,MAAM,CAAC,CAACM,SAAS,GAC7BR,OAAOE,SAASA;CAEpB,IAAIxC,MAAMuB,MAAMgB,KAAAA,KAAavC,MAAMuB,MAAM,IACrCe,OAAOf,IAAIvB,MAAMuB;CAErB,IAAIvB,MAAMgD,WAAWT,KAAAA,GACjBD,OAAOU,SAAShD,MAAMgD;CAE1B,OAAOV;AACX;;AAGA,SAAgBW,WAAWC,UAAuB,CAAC,GAAS;CACx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AE9C;IAAOF,QAAQ,CAAC,GAAGG,UAAUH,MAAM;GAAE,IACvC,EAAEE,MAAM;EAClB;CACJ;CACA,OAAOM;AACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","names":[],"sources":["../../src/list/router.ts"],"sourcesContent":["/**\n * The part of a router that lists need: read and write the query string, and know when it\n * changes (back and forward). An app adapts its own router to it.\n */\nexport interface Router {\n /** The current query string, without `?`. */\n getSearch(): string;\n /** Navigates to the same path with another query string. `replace` doesn't add a history entry. */\n setSearch(search: string, options?: { replace?: boolean }): void;\n /** Calls `listener` when the query string changes. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n}\n\n/** A router over `window.history` and `window.location`. */\nexport function createHistoryRouter(target: Window = window): Router {\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n getSearch: () => target.location.search.replace(/^\\?/, ''),\n setSearch(search, { replace = false } = {}) {\n const url = `${target.location.pathname}${search !== '' ? `?${search}` : ''}${target.location.hash}`;\n if (replace) {\n target.history.replaceState(target.history.state, '', url);\n } else {\n target.history.pushState(target.history.state, '', url);\n }\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n target.addEventListener('popstate', listener);\n return () => {\n listeners.delete(listener);\n target.removeEventListener('popstate', listener);\n };\n },\n };\n}\n\n/** A router that keeps the query string in memory, for tests and embedded lists. */\nexport interface MemoryRouter extends Router {\n /** Query strings of the history entries, the last one being the current one. */\n history: string[];\n /** Goes back to the previous entry, like the browser's back button. */\n back(): void;\n}\n\n/** Creates a router that keeps the query string in memory. */\nexport function createMemoryRouter(initialSearch = ''): MemoryRouter {\n const history = [initialSearch];\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n history,\n getSearch: () => history.at(-1) ?? '',\n back() {\n if (history.length > 1) {\n history.pop();\n notify();\n }\n },\n setSearch(search, { replace = false } = {}) {\n if (replace) {\n history[history.length - 1] = search;\n } else {\n history.push(search);\n }\n notify();\n },\n subsc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
1
+ {"version":3,"file":"router.js","names":["Router","getSearch","setSearch","search","options","replace","subscribe","listener","createHistoryRouter","target","Window","window","listeners","Set","notify","forEach","location","url","pathname","hash","history","replaceState","state","pushState","add","addEventListener","delete","removeEventListener","MemoryRouter","back","createMemoryRouter","initialSearch","at","length","pop","push"],"sources":["../../src/list/router.ts"],"sourcesContent":["/**\n * The part of a router that lists need: read and write the query string, and know when it\n * changes (back and forward). An app adapts its own router to it.\n */\nexport interface Router {\n /** The current query string, without `?`. */\n getSearch(): string;\n /** Navigates to the same path with another query string. `replace` doesn't add a history entry. */\n setSearch(search: string, options?: { replace?: boolean }): void;\n /** Calls `listener` when the query string changes. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n}\n\n/** A router over `window.history` and `window.location`. */\nexport function createHistoryRouter(target: Window = window): Router {\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n getSearch: () => target.location.search.replace(/^\\?/, ''),\n setSearch(search, { replace = false } = {}) {\n const url = `${target.location.pathname}${search !== '' ? `?${search}` : ''}${target.location.hash}`;\n if (replace) {\n target.history.replaceState(target.history.state, '', url);\n } else {\n target.history.pushState(target.history.state, '', url);\n }\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n target.addEventListener('popstate', listener);\n return () => {\n listeners.delete(listener);\n target.removeEventListener('popstate', listener);\n };\n },\n };\n}\n\n/** A router that keeps the query string in memory, for tests and embedded lists. */\nexport interface MemoryRouter extends Router {\n /** Query strings of the history entries, the last one being the current one. */\n history: string[];\n /** Goes back to the previous entry, like the browser's back button. */\n back(): void;\n}\n\n/** Creates a router that keeps the query string in memory. */\nexport function createMemoryRouter(initialSearch = ''): MemoryRouter {\n const history = [initialSearch];\n const listeners = new Set<() => void>();\n const notify = () => listeners.forEach((listener) => listener());\n return {\n history,\n getSearch: () => history.at(-1) ?? '',\n back() {\n if (history.length > 1) {\n history.pop();\n notify();\n }\n },\n setSearch(search, { replace = false } = {}) {\n if (replace) {\n history[history.length - 1] = search;\n } else {\n history.push(search);\n }\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"],"mappings":";;AAcA,SAAgBQ,oBAAoBC,SAAiBE,QAAgB;CACjE,MAAMC,4BAAY,IAAIC,IAAgB;CACtC,MAAMC,eAAeF,UAAUG,SAASR,aAAaA,SAAS,CAAC;CAC/D,OAAO;EACHN,iBAAiBQ,OAAOO,SAASb,OAAOE,QAAQ,OAAO,EAAE;EACzDH,UAAUC,QAAQ,EAAEE,UAAU,UAAU,CAAC,GAAG;GACxC,MAAMY,MAAM,GAAGR,OAAOO,SAASE,WAAWf,WAAW,KAAK,IAAIA,WAAW,KAAKM,OAAOO,SAASG;GAC9F,IAAId,SACAI,OAAOW,QAAQC,aAAaZ,OAAOW,QAAQE,OAAO,IAAIL,GAAG;QAEzDR,OAAOW,QAAQG,UAAUd,OAAOW,QAAQE,OAAO,IAAIL,GAAG;GAE1DH,OAAO;EACX;EACAR,UAAUC,UAAU;GAChBK,UAAUY,IAAIjB,QAAQ;GACtBE,OAAOgB,iBAAiB,YAAYlB,QAAQ;GAC5C,aAAa;IACTK,UAAUc,OAAOnB,QAAQ;IACzBE,OAAOkB,oBAAoB,YAAYpB,QAAQ;GACnD;EACJ;CACJ;AACJ;;AAWA,SAAgBuB,mBAAmBC,gBAAgB,IAAkB;CACjE,MAAMX,UAAU,CAACW,aAAa;CAC9B,MAAMnB,4BAAY,IAAIC,IAAgB;CACtC,MAAMC,eAAeF,UAAUG,SAASR,aAAaA,SAAS,CAAC;CAC/D,OAAO;EACHa;EACAnB,iBAAiBmB,QAAQY,GAAG,EAAE,KAAK;EACnCH,OAAO;GACH,IAAIT,QAAQa,SAAS,GAAG;IACpBb,QAAQc,IAAI;IACZpB,OAAO;GACX;EACJ;EACAZ,UAAUC,QAAQ,EAAEE,UAAU,UAAU,CAAC,GAAG;GACxC,IAAIA,SACAe,QAAQA,QAAQa,SAAS,KAAK9B;QAE9BiB,QAAQe,KAAKhC,MAAM;GAEvBW,OAAO;EACX;EACAR,UAAUC,UAAU;GAChBK,UAAUY,IAAIjB,QAAQ;GACtB,aAAa;IACTK,UAAUc,OAAOnB,QAAQ;GAC7B;EACJ;CACJ;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.js","names":[],"sources":["../src/plugins.ts"],"sourcesContent":["import type { ComponentType } from 'react';\n\nimport type { DefinitionTheme, Theme } from '@panneau/protocol';\nimport { mergeThemes } from '@panneau/protocol/runtime';\n\nimport type { CommandSource } from './commands';\n\n/** A theme of `@panneau/ui`, as plain data: what plugins register (decision 0024). */\nexport type { Theme };\n\n/**\n * A component provided by a plugin. Its props are defined by the package that renders it (fields,\n * lists, app), so the registry stores it as given.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- see above\nexport type PluginComponent = ComponentType<any>;\n\n/** UI messages of a locale, keyed by message id. */\nexport type Messages = Record<string, string>;\n\n/** Messages, or a function that loads them (`() => import('./lang/fr.json')`). */\nexport type MessagesLoader = Messages | (() => Promise<Messages | { default: Messages }>);\n\n/** What a plugin adds to Panneau. Every part is keyed by the name the definition uses. */\nexport interface PanneauPlugin {\n /** Unique id of the plugin. */\n id: string;\n /** Field components, by field type (`text`, `page-slug`). */\n fields?: Record<string, PluginComponent>;\n /** Components that display a value in lists, by display (`date`, `page-slug`). */\n displays?: Record<string, PluginComponent>;\n /** List layouts, by id (`table`, `cards`). */\n listLayouts?: Record<string, PluginComponent>;\n /** Handlers of `client` actions, by the action's `component`. */\n actions?: Record<string, PluginComponent>;\n /** Pages, by component name (`dashboard`). */\n pages?: Record<string, PluginComponent>;\n /** Dashboard widgets, by widget type (`stat`). */\n widgets?: Record<string, PluginComponent>;\n /** Layout node components, for `component` nodes of form layouts. */\n components?: Record<string, PluginComponent>;\n /**\n * Previews of items, by name, for resources whose `features.preview` is a `component`\n * (`{ \"mode\": \"component\", \"component\": \"page\" }`). They get `PreviewProps`.\n */\n previews?: Record<string, PluginComponent>;\n /** Commands of the \"Go to…\" palette, or a function that makes them for the definition. */\n commands?: CommandSource;\n /** UI messages, by locale. Messages of later plugins override earlier ones. */\n locales?: Record<string, MessagesLoader>;\n /** Themes, by id, that the theme of the definition can extend. */\n themes?: Record<string, Theme>;\n}\n\n/** The kinds of components a plugin can provide. */\nexport type PluginComponentKind =\n | 'fields'\n | 'displays'\n | 'listLayouts'\n | 'actions'\n | 'pages'\n | 'widgets'\n | 'components'\n | 'previews';\n\nconst COMPONENT_KINDS: PluginComponentKind[] = [\n 'fields',\n 'displays',\n 'listLayouts',\n 'actions',\n 'pages',\n 'widgets',\n 'components',\n 'previews',\n];\n\n/** Everything the plugins provide, merged. A later plugin overrides an earlier one. */\nexport interface PluginRegistry {\n /** The plugins, in order. */\n plugins: readonly PanneauPlugin[];\n fields: ReadonlyMap<string, PluginComponent>;\n displays: ReadonlyMap<string, PluginComponent>;\n listLayouts: ReadonlyMap<string, PluginComponent>;\n actions: ReadonlyMap<string, PluginComponent>;\n pages: ReadonlyMap<string, PluginComponent>;\n widgets: ReadonlyMap<string, PluginComponent>;\n components: ReadonlyMap<string, PluginComponent>;\n previews: ReadonlyMap<string, PluginComponent>;\n /** The commands of the plugins, in plugin order: `getCommands()` makes them. */\n commands: readonly CommandSource[];\n /** Message loaders of each locale, in plugin order. */\n locales: ReadonlyMap<string, readonly MessagesLoader[]>;\n themes: ReadonlyMap<string, Theme>;\n}\n\n/** Declares a plugin. It returns the plugin as is, with its type checked. */\nexport function definePlugin(plugin: PanneauPlugin): PanneauPlugin {\n return plugin;\n}\n\n/**\n * Merges plugins into a registry. Later plugins override the components and themes of earlier\n * ones, so a project can replace a built-in field. Plugin ids must be unique.\n */\nexport function createPluginRegistry(plugins: readonly PanneauPlugin[]): PluginRegistry {\n const ids = new Set<string>();\n plugins.forEach((plugin) => {\n if (ids.has(plugin.id)) {\n throw new Error(`Two plugins have the id \\`${plugin.id}\\`.`);\n }\n ids.add(plugin.id);\n });\n const components = Object.fromEntries(\n COMPONENT_KINDS.map((kind) => [\n kind,\n new Map(plugins.flatMap((plugin) => Object.entries(plugin[kind] ?? {}))),\n ]),\n ) as Record<PluginComponentKind, Map<string, PluginComponent>>;\n const locales = new Map<string, MessagesLoader[]>();\n plugins.forEach((plugin) =>\n Object.entries(plugin.locales ?? {}).forEach(([locale, loader]) => {\n locales.set(locale, [...(locales.get(locale) ?? []), loader]);\n }),\n );\n return {\n plugins: [...plugins],\n ...components,\n locales,\n themes: new Map(plugins.flatMap((plugin) => Object.entries(plugin.themes ?? {}))),\n commands: plugins.flatMap((plugin) =>\n plugin.commands !== undefined ? [plugin.commands] : [],\n ),\n };\n}\n\n/**\n * Loads the messages of a locale from every plugin that provides it, merged in plugin order. A\n * regional locale (`fr-CA`) falls back to its language (`fr`) for missing messages.\n */\nexport async function loadMessages(registry: PluginRegistry, locale: string): Promise<Messages> {\n const language = locale.split('-')[0] ?? locale;\n const loaders = [\n ...(language !== locale ? (registry.locales.get(language) ?? []) : []),\n ...(registry.locales.get(locale) ?? []),\n ];\n const loaded = await Promise.all(\n loaders.map(async (loader) => {\n if (typeof loader !== 'function') {\n return loader;\n }\n const result = await loader();\n return 'default' in result && typeof result.default === 'object'\n ? (result.default as Messages)\n : (result as Messages);\n }),\n );\n return Object.assign({}, ...loaded) as Messages;\n}\n\n/**\n * The theme of the admin: the themes of plugins that the definition's theme extends, in order, then\n * the definition's own tokens, tones and variants. An id no plugin registers is skipped, with a\n * warning.\n */\nexport function resolveTheme(\n theme: DefinitionTheme | undefined,\n themes: ReadonlyMap<string, Theme>,\n): Theme {\n const { colorScheme: _colorScheme, extends: ids, ...own } = theme ?? {};\n const extended = (typeof ids === 'string' ? [ids] : (ids ?? [])).flatMap((id) => {\n const found = themes.get(id);\n if (found === undefined) {\n console.warn(`[panneau] No plugin registers the theme \"${id}\".`);\n return [];\n }\n return [found];\n });\n return mergeThemes(...extended, own);\n}\n"],"mappings":";;AAiEA,IAAM,kBAAyC;CAC3C;CACA;CAC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AAQ,IAAI,OAAO,WAAW;EAC1B,IAAI,OAAO,WAAW,YAClB,OAAO;EAEX,MAAM,SAAS,MAAM,OAAO;EAC5B,OAAO,aAAa,UAAU,OAAO,OAAO,YAAY,WACjD,OAAO,UACP;CACX,CAAC,CACL;CACA,OAAO,OAAO,OAAO,CAAC,GAAG,GAAG,MAAM;AACtC;;;;;;AAOA,SAAgB,aACZ,OACA,QACK;CACL,MAAM,EAAE,aAAa,cAAc,SAAS,KAAK,GAAG,QAAQ,SAAS,CAAC;CACtE,MAAM,YAAY,OAAO,QAAQ,WAAW,CAAC,GAAG,IAAK,OAAO,CAAA,EAAA,CAAK,SAAS,OAAO;EAC7E,MAAM,QAAQ,OAAO,IAAI,EAAE;EAC3B,IAAI,UAAU,KAAA,GAAW;GACrB,QAAQ,KAAK,4CAA4C,GAAE,GAAI;GAC/D,OAAO,CAAA;EACX;EACA,OAAO,CAAC,KAAK;CACjB,CAAC;CACD,OAAO,YAAY,GAAG,UAAU,GAAG;AACvC"}
1
+ {"version":3,"file":"plugins.js","names":["ComponentType","DefinitionTheme","Theme","mergeThemes","CommandSource","PluginComponent","Messages","Record","MessagesLoader","Promise","default","PanneauPlugin","id","fields","displays","listLayouts","actions","pages","widgets","components","previews","commands","locales","themes","PluginComponentKind","COMPONENT_KINDS","PluginRegistry","plugins","ReadonlyMap","definePlugin","plugin","createPluginRegistry","ids","Set","forEach","has","Error","add","Object","fromEntries","map","kind","Map","flatMap","entries","locale","loader","set","get","undefined","loadMessages","registry","language","split","loaders","loaded","all","result","assign","resolveTheme","theme","colorScheme","_colorScheme","extends","own","extended","found","console","warn"],"sources":["../src/plugins.ts"],"sourcesContent":["import type { ComponentType } from 'react';\n\nimport type { DefinitionTheme, Theme } from '@panneau/protocol';\nimport { mergeThemes } from '@panneau/protocol/runtime';\n\nimport type { CommandSource } from './commands';\n\n/** A theme of `@panneau/ui`, as plain data: what plugins register (decision 0024). */\nexport type { Theme };\n\n/**\n * A component provided by a plugin. Its props are defined by the package that renders it (fields,\n * lists, app), so the registry stores it as given.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- see above\nexport type PluginComponent = ComponentType<any>;\n\n/** UI messages of a locale, keyed by message id. */\nexport type Messages = Record<string, string>;\n\n/** Messages, or a function that loads them (`() => import('./lang/fr.json')`). */\nexport type MessagesLoader = Messages | (() => Promise<Messages | { default: Messages }>);\n\n/** What a plugin adds to Panneau. Every part is keyed by the name the definition uses. */\nexport interface PanneauPlugin {\n /** Unique id of the plugin. */\n id: string;\n /** Field components, by field type (`text`, `page-slug`). */\n fields?: Record<string, PluginComponent>;\n /** Components that display a value in lists, by display (`date`, `page-slug`). */\n displays?: Record<string, PluginComponent>;\n /** List layouts, by id (`table`, `cards`). */\n listLayouts?: Record<string, PluginComponent>;\n /** Handlers of `client` actions, by the action's `component`. */\n actions?: Record<string, PluginComponent>;\n /** Pages, by component name (`dashboard`). */\n pages?: Record<string, PluginComponent>;\n /** Dashboard widgets, by widget type (`stat`). */\n widgets?: Record<string, PluginComponent>;\n /** Layout node components, for `component` nodes of form layouts. */\n components?: Record<string, PluginComponent>;\n /**\n * Previews of items, by name, for resources whose `features.preview` is a `component`\n * (`{ \"mode\": \"component\", \"component\": \"page\" }`). They get `PreviewProps`.\n */\n previews?: Record<string, PluginComponent>;\n /** Commands of the \"Go to…\" palette, or a function that makes them for the definition. */\n commands?: CommandSource;\n /** UI messages, by locale. Messages of later plugins override earlier ones. */\n locales?: Record<string, MessagesLoader>;\n /** Themes, by id, that the theme of the definition can extend. */\n themes?: Record<string, Theme>;\n}\n\n/** The kinds of components a plugin can provide. */\nexport type PluginComponentKind =\n | 'fields'\n | 'displays'\n | 'listLayouts'\n | 'actions'\n | 'pages'\n | 'widgets'\n | 'components'\n | 'previews';\n\nconst COMPONENT_KINDS: PluginComponentKind[] = [\n 'fields',\n 'displays',\n 'listLayouts',\n 'actions',\n 'pages',\n 'widgets',\n 'components',\n 'previews',\n];\n\n/** Everything the plugins provide, merged. A later plugin overrides an earlier one. */\nexport interface PluginRegistry {\n /** The plugins, in order. */\n plugins: readonly PanneauPlugin[];\n fields: ReadonlyMap<string, PluginComponent>;\n displays: ReadonlyMap<string, PluginComponent>;\n listLayouts: ReadonlyMap<string, PluginComponent>;\n actions: ReadonlyMap<string, PluginComponent>;\n pages: ReadonlyMap<string, PluginComponent>;\n widgets: ReadonlyMap<string, PluginComponent>;\n components: ReadonlyMap<string, PluginComponent>;\n previews: ReadonlyMap<string, PluginComponent>;\n /** The commands of the plugins, in plugin order: `getCommands()` makes them. */\n commands: readonly CommandSource[];\n /** Message loaders of each locale, in plugin order. */\n locales: ReadonlyMap<string, readonly MessagesLoader[]>;\n themes: ReadonlyMap<string, Theme>;\n}\n\n/** Declares a plugin. It returns the plugin as is, with its type checked. */\nexport function definePlugin(plugin: PanneauPlugin): PanneauPlugin {\n return plugin;\n}\n\n/**\n * Merges plugins into a registry. Later plugins override the components and themes of earlier\n * ones, so a project can replace a built-in field. Plugin ids must be unique.\n */\nexport function createPluginRegistry(plugins: readonly PanneauPlugin[]): PluginRegistry {\n const ids = new Set<string>();\n plugins.forEach((plugin) => {\n if (ids.has(plugin.id)) {\n throw new Error(`Two plugins have the id \\`${plugin.id}\\`.`);\n }\n ids.add(plugin.id);\n });\n const components = Object.fromEntries(\n COMPONENT_KINDS.map((kind) => [\n kind,\n new Map(plugins.flatMap((plugin) => Object.entries(plugin[kind] ?? {}))),\n ]),\n ) as Record<PluginComponentKind, Map<string, PluginComponent>>;\n const locales = new Map<string, MessagesLoader[]>();\n plugins.forEach((plugin) =>\n Object.entries(plugin.locales ?? {}).forEach(([locale, loader]) => {\n locales.set(locale, [...(locales.get(locale) ?? []), loader]);\n }),\n );\n return {\n plugins: [...plugins],\n ...components,\n locales,\n themes: new Map(plugins.flatMap((plugin) => Object.entries(plugin.themes ?? {}))),\n commands: plugins.flatMap((plugin) =>\n plugin.commands !== undefined ? [plugin.commands] : [],\n ),\n };\n}\n\n/**\n * Loads the messages of a locale from every plugin that provides it, merged in plugin order. A\n * regional locale (`fr-CA`) falls back to its language (`fr`) for missing messages.\n */\nexport async function loadMessages(registry: PluginRegistry, locale: string): Promise<Messages> {\n const language = locale.split('-')[0] ?? locale;\n const loaders = [\n ...(language !== locale ? (registry.locales.get(language) ?? []) : []),\n ...(registry.locales.get(locale) ?? []),\n ];\n const loaded = await Promise.all(\n loaders.map(async (loader) => {\n if (typeof loader !== 'function') {\n return loader;\n }\n const result = await loader();\n return 'default' in result && typeof result.default === 'object'\n ? (result.default as Messages)\n : (result as Messages);\n }),\n );\n return Object.assign({}, ...loaded) as Messages;\n}\n\n/**\n * The theme of the admin: the themes of plugins that the definition's theme extends, in order, then\n * the definition's own tokens, tones and variants. An id no plugin registers is skipped, with a\n * warning.\n */\nexport function resolveTheme(\n theme: DefinitionTheme | undefined,\n themes: ReadonlyMap<string, Theme>,\n): Theme {\n const { colorScheme: _colorScheme, extends: ids, ...own } = theme ?? {};\n const extended = (typeof ids === 'string' ? [ids] : (ids ?? [])).flatMap((id) => {\n const found = themes.get(id);\n if (found === undefined) {\n console.warn(`[panneau] No plugin registers the theme \"${id}\".`);\n return [];\n }\n return [found];\n });\n return mergeThemes(...extended, own);\n}\n"],"mappings":";;AAiEA,IAAMyB,kBAAyC;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAAU;;AAuBd,SAAgBI,aAAaC,QAAsC;CAC/D,OAAOA;AACX;;;;;AAMA,SAAgBC,qBAAqBJ,SAAmD;CACpF,MAAMK,sBAAM,IAAIC,IAAY;CAC5BN,QAAQO,SAASJ,WAAW;EACxB,IAAIE,IAAIG,IAAIL,OAAOlB,EAAE,GACjB,MAAM,IAAIwB,MAAM,6BAA6BN,OAAOlB,GAAE,IAAK;EAE/DoB,IAAIK,IAAIP,OAAOlB,EAAE;CACrB,CAAC;CACD,MAAMO,aAAamB,OAAOC,YACtBd,gBAAgBe,KAAKC,SAAS,CAC1BA,MACA,IAAIC,IAAIf,QAAQgB,SAASb,WAAWQ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AaC,cAAcC,SAAS/B,KAAK,GAAGgC,QAAQJ,SAAS,CAAC;CACtE,MAAMK,YAAY,OAAOjC,QAAQ,WAAW,CAACA,GAAG,IAAKA,OAAO,CAAA,EAAA,CAAKW,SAAS/B,OAAO;EAC7E,MAAMsD,QAAQ3C,OAAOyB,IAAIpC,EAAE;EAC3B,IAAIsD,UAAUjB,KAAAA,GAAW;GACrBkB,QAAQC,KAAK,4CAA4CxD,GAAE,GAAI;GAC/D,OAAO,CAAA;EACX;EACA,OAAO,CAACsD,KAAK;CACjB,CAAC;CACD,OAAO/D,YAAY,GAAG8D,UAAUD,GAAG;AACvC"}
@@ -1 +1 @@
1
- {"version":3,"file":"leaveGuards.js","names":["guards","children","_c"],"sources":["../../src/react/leaveGuards.tsx"],"sourcesContent":["import { type ReactNode, createContext, use, useEffect, useRef } from 'react';\n\n/** Asks whether the user may leave: resolves `true` to leave, `false` to stay. */\nexport type LeaveGuard = () => Promise<boolean>;\n\n/**\n * What guards in-app navigation: forms with unsaved changes add a guard while they are dirty,\n * and the router asks them before it leaves the page.\n */\nexport interface LeaveGuards {\n /** Adds a guard. Returns a function that removes it. */\n add(guard: LeaveGuard): () => void;\n /** Whether a guard would ask: leaving now needs a confirmation. */\n isBlocking(): boolean;\n /** Asks each guard in turn. Resolves `true` when every one lets the user leave. */\n confirmLeave(): Promise<boolean>;\n}\n\n/** Creates the guards of an app, for `LeaveGuardsProvider`. */\nexport function createLeaveGuards(): LeaveGuards {\n const guards = new Set<LeaveGuard>();\n return {\n add(guard) {\n guards.add(guard);\n return () => {\n guards.delete(guard);\n };\n },\n isBlocking: () => guards.size > 0,\n async confirmLeave() {\n for (const guard of [...guards]) {\n if (!(await guard())) {\n return false;\n }\n }\n return true;\n },\n };\n}\n\nconst LeaveGuardsContext = createContext<LeaveGuards | null>(null);\n\nexport interface LeaveGuardsProviderProps {\n guards: LeaveGuards;\n children?: ReactNode;\n}\n\n/**\n * Gives the guards of the app's router to the forms below it, so that leaving a page with unsaved\n * changes asks first. Without it, forms only guard closing and reloading the page.\n */\nexport function LeaveGuardsProvider({ guards, children }: LeaveGuardsProviderProps) {\n return <LeaveGuardsContext value={guards}>{children}</LeaveGuardsContext>;\n}\n\n/** The guards of the closest `LeaveGuardsProvider`, or `null`. */\nexport function useLeaveGuards(): LeaveGuards | null {\n return use(LeaveGuardsContext);\n}\n\n/**\n * Adds `guard` to the guards of the closest `LeaveGuardsProvider` while `active` is true, such\n * as while a form has unsaved changes. The latest `guard` is the one asked.\n */\nexport function useLeaveGuard(active: boolean, guard: LeaveGuard): void {\n const guards = useLeaveGuards();\n const latest = useRef(guard);\n useEffect(() => {\n latest.current = guard;\n });\n useEffect(() => {\n if (!active || guards === null) {\n return undefined;\n }\n return guards.add(() => latest.current());\n }, [active, guards]);\n}\n"],"mappings":";;;;;AAmBA,SAAgB,oBAAiC;CAC7C,MAAM,yBAAS,IAAI,IAAgB;CACnC,OAAO;EACH,IAAI,OAAO;GACP,OAAO,IAAI,KAAK;GAChB,aAAa;IACT,OAAO,OAAO,KAAK;GACvB;EACJ;EACA,kBAAkB,OAAO,OAAO;EAChC,MAAM,eAAe;GACjB,KAAK,MAAM,SAAS,CAAC,GAAG,MAAM,GAC1B,IAAI,CAAE,MAAM,MAAM,GACd,OAAO;GAGf,OAAO;EACX;CACJ;AACJ;AAEA,IAAM,qBAAqB,cAAkC,IAAI;;;;;AAWjE,SAAO,oBAAA,IAAA;CAAA,MAAA,IAAAE,EAAA,CAAA;CAA6B,MAAA,EAAA,QAAA,aAAA;CAA8C,IAAA;CAAA,IAAA,EAAA,OAAA,YAAA,EAAA,OAAA,QAAA;EACvE,KAAA,oBAAC,oBAAD;GAA2BF,OAAA;GAAS;EAAjB,CAAA;EAA+C,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAAA,OAAlE;AAAkE;;AAI7E,SAAgB,iBAAqC;CACjD,OAAO,IAAI,kBAAkB;AACjC;;;;;AAMA,SAAO,cAAA,QAAA,OAAA;CAAA,MAAA,IAAAE,EAAA,CAAA;CACH,MAAA,SAAe,eAAe;CAC9B,MAAA,SAAe,OAAO,KAAK;CAAE,IAAA;CAAA,IAAA,EAAA,OAAA,OAAA;EACnB,WAAA;GACN,OAAM,UAAW;EAAH;EACjB,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAFD,UAAU,EAET;CAAC,IAAA;CAAA,IAAA;CAAA,IAAA,EAAA,OAAA,UAAA,EAAA,OAAA,QAAA;EACQ,WAAA;GACN,IAAI,CAAC,UAAU,WAAW,MAAI;GAE7B,OACM,OAAM,UAAW,OAAM,QAAS,CAAC;EAAC;EAC1C,KAAA,CAAC,QAAQ,MAAM;EAAC,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA;EAAA,KAAA,EAAA;EAAA,KAAA,EAAA;CAAA;CALnB,UAAU,IAKP,EAAgB;AAAC"}
1
+ {"version":3,"file":"leaveGuards.js","names":["ReactNode","createContext","use","useEffect","useRef","LeaveGuard","Promise","LeaveGuards","add","guard","isBlocking","confirmLeave","createLeaveGuards","guards","Set","delete","size","LeaveGuardsContext","LeaveGuardsProviderProps","children","LeaveGuardsProvider","t0","$","_c","t1","useLeaveGuards","useLeaveGuard","active","latest","current","t2","_c"],"sources":["../../src/react/leaveGuards.tsx"],"sourcesContent":["import { type ReactNode, createContext, use, useEffect, useRef } from 'react';\n\n/** Asks whether the user may leave: resolves `true` to leave, `false` to stay. */\nexport type LeaveGuard = () => Promise<boolean>;\n\n/**\n * What guards in-app navigation: forms with unsaved changes add a guard while they are dirty,\n * and the router asks them before it leaves the page.\n */\nexport interface LeaveGuards {\n /** Adds a guard. Returns a function that removes it. */\n add(guard: LeaveGuard): () => void;\n /** Whether a guard would ask: leaving now needs a confirmation. */\n isBlocking(): boolean;\n /** Asks each guard in turn. Resolves `true` when every one lets the user leave. */\n confirmLeave(): Promise<boolean>;\n}\n\n/** Creates the guards of an app, for `LeaveGuardsProvider`. */\nexport function createLeaveGuards(): LeaveGuards {\n const guards = new Set<LeaveGuard>();\n return {\n add(guard) {\n guards.add(guard);\n return () => {\n guards.delete(guard);\n };\n },\n isBlocking: () => guards.size > 0,\n async confirmLeave() {\n for (const guard of [...guards]) {\n if (!(await guard())) {\n return false;\n }\n }\n return true;\n },\n };\n}\n\nconst LeaveGuardsContext = createContext<LeaveGuards | null>(null);\n\nexport interface LeaveGuardsProviderProps {\n guards: LeaveGuards;\n children?: ReactNode;\n}\n\n/**\n * Gives the guards of the app's router to the forms below it, so that leaving a page with unsaved\n * changes asks first. Without it, forms only guard closing and reloading the page.\n */\nexport function LeaveGuardsProvider({ guards, children }: LeaveGuardsProviderProps) {\n return <LeaveGuardsContext value={guards}>{children}</LeaveGuardsContext>;\n}\n\n/** The guards of the closest `LeaveGuardsProvider`, or `null`. */\nexport function useLeaveGuards(): LeaveGuards | null {\n return use(LeaveGuardsContext);\n}\n\n/**\n * Adds `guard` to the guards of the closest `LeaveGuardsProvider` while `active` is true, such\n * as while a form has unsaved changes. The latest `guard` is the one asked.\n */\nexport function useLeaveGuard(active: boolean, guard: LeaveGuard): void {\n const guards = useLeaveGuards();\n const latest = useRef(guard);\n useEffect(() => {\n latest.current = guard;\n });\n useEffect(() => {\n if (!active || guards === null) {\n return undefined;\n }\n return guards.add(() => latest.current());\n }, [active, guards]);\n}\n"],"mappings":";;;;;AAmBA,SAAgBY,oBAAiC;CAC7C,MAAMC,yBAAS,IAAIC,IAAgB;CACnC,OAAO;EACHN,IAAIC,OAAO;GACPI,OAAOL,IAAIC,KAAK;GAChB,aAAa;IACTI,OAAOE,OAAON,KAAK;GACvB;EACJ;EACAC,kBAAkBG,OAAOG,OAAO;EAChC,MAAML,eAAe;GACjB,KAAK,MAAMF,SAAS,CAAC,GAAGI,MAAM,GAC1B,IAAI,CAAE,MAAMJ,MAAM,GACd,OAAO;GAGf,OAAO;EACX;CACJ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Providers can
10
10
  * be nested: a nested provider adds its plugins to those of its parent.
11
11
  */
12
- function PanneauProvider({ plugins = [], definition, router, children }) {
12
+ function PanneauProvider(t0) {
13
+ const { plugins: t1, definition, router, children } = t0;
14
+ const plugins = t1 === void 0 ? [] : t1;
13
15
  const parent = use(PanneauContext);
14
16
  const pluginList = [...parent?.pluginList ?? [], ...plugins];
15
17
  const value = {
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","names":["_c"],"sources":["../../src/react/provider.tsx"],"sourcesContent":["import { type ReactNode, createContext, use } from 'react';\n\nimport type { Definition } from '@panneau/protocol';\n\nimport { type ResolveFormOptions } from '../definition/form';\nimport { type ResolvedResource, findResource, resolveResource } from '../definition/resource';\nimport type { Router } from '../list/router';\nimport { type PanneauPlugin, type PluginRegistry, createPluginRegistry } from '../plugins';\n\n/** What `PanneauProvider` gives to the hooks below it. */\nexport interface PanneauContextValue {\n plugins: PluginRegistry;\n /** The plugins as passed, including those of parent providers. */\n pluginList: readonly PanneauPlugin[];\n definition: Definition | null;\n router: Router | null;\n}\n\nconst PanneauContext = createContext<PanneauContextValue | null>(null);\n\nexport interface PanneauProviderProps {\n /** Plugins, added after those of a parent provider (so they override them). */\n plugins?: readonly PanneauPlugin[];\n /** The definition, for `useResource()`. Defaults to the parent provider's. */\n definition?: Definition | null;\n /** The router that lists keep their query in. Defaults to the parent provider's. */\n router?: Router | null;\n children?: ReactNode;\n}\n\n/**\n * Provides plugins, the definition and the router to the hooks of `@panneau/core`. Providers can\n * be nested: a nested provider adds its plugins to those of its parent.\n */\nexport function PanneauProvider({\n plugins = [],\n definition,\n router,\n children,\n}: PanneauProviderProps) {\n const parent = use(PanneauContext);\n const pluginList = [...(parent?.pluginList ?? []), ...plugins];\n const value: PanneauContextValue = {\n plugins: createPluginRegistry(pluginList),\n pluginList,\n definition: definition === undefined ? (parent?.definition ?? null) : definition,\n router: router === undefined ? (parent?.router ?? null) : router,\n };\n return <PanneauContext value={value}>{children}</PanneauContext>;\n}\n\nconst EMPTY: PanneauContextValue = {\n plugins: createPluginRegistry([]),\n pluginList: [],\n definition: null,\n router: null,\n};\n\n/** The context of the closest `PanneauProvider`, or an empty one without a provider. */\nexport function usePanneau(): PanneauContextValue {\n return use(PanneauContext) ?? EMPTY;\n}\n\n/** The plugins of the closest `PanneauProvider`, merged. */\nexport function usePlugins(): PluginRegistry {\n return usePanneau().plugins;\n}\n\n/**\n * A resource of the definition, with its form, list and abilities resolved. Throws when there is\n * no definition or no such resource.\n */\nexport function useResource(id: string, formOptions?: ResolveFormOptions): ResolvedResource {\n const { definition } = usePanneau();\n if (definition === null) {\n throw new Error('useResource() needs a definition: pass one to <PanneauProvider>.');\n }\n const resource = findResource(definition, id);\n if (resource === undefined) {\n throw new Error(`The definition has no resource \\`${id}\\`.`);\n }\n return resolveResource(resource, formOptions);\n}\n"],"mappings":";;;;;;AAkBA,IAAM,iBAAiB,cAA0C,IAAI;;;;;AAgBrE,SAAgB,gBAAgB,EAC5B,UAAU,CAAA,GACV,YACA,QACA,YACqB;CACrB,MAAM,SAAS,IAAI,cAAc;CACjC,MAAM,aAAa,CAAC,GAAI,QAAQ,cAAc,CAAA,GAAK,GAAG,OAAO;CAC7D,MAAM,QAA6B;EAC/B,SAAS,qBAAqB,UAAU;EACxC;EACA,YAAY,eAAe,KAAA,IAAa,QAAQ,cAAc,OAAQ;EACtE,QAAQ,WAAW,KAAA,IAAa,QAAQ,UAAU,OAAQ;CAC9D;CACA,OAAO,oBAAC,gBAAD;EAAuB;EAAQ;CAAyB,CAAA;AACnE;AAEA,IAAM,QAA6B;CAC/B,SAAS,qBAAqB,CAAA,CAAE;CAChC,YAAY,CAAA;CACZ,YAAY;CACZ,QAAQ;AACZ;;AAGA,SAAgB,aAAkC;CAC9C,OAAO,IAAI,cAAc,KAAK;AAClC;;AAGA,SAAO,aAAA;CAAA,OACI,WAAW,CAAC,CAAA;AAAQ;;;;;AAO/B,SAAO,YAAA,IAAA,aAAA;CAAA,MAAA,IAAAA,EAAA,CAAA;CACH,MAAA,EAAA,eAAuB,WAAW;CAClC,IAAI,eAAe,MACf,MAAM,IAAI,MAAM,kEAAkE;CACrF,IAAA;CAAA,IAAA,EAAA,OAAA,cAAA,EAAA,OAAA,eAAA,EAAA,OAAA,IAAA;EACD,MAAA,WAAiB,aAAa,YAAY,EAAE;EAC5C,IAAI,aAAa,KAAA,GACb,MAAM,IAAI,MAAM,oCAAoC,GAAE,IAAK;EAExD,KAAA,gBAAgB,UAAU,WAAW;EAAC,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAAA,OAAtC;AAAsC"}
1
+ {"version":3,"file":"provider.js","names":["ReactNode","createContext","use","Definition","ResolveFormOptions","ResolvedResource","findResource","resolveResource","Router","PanneauPlugin","PluginRegistry","createPluginRegistry","PanneauContextValue","plugins","pluginList","definition","router","PanneauContext","PanneauProviderProps","children","PanneauProvider","t0","t1","undefined","parent","value","EMPTY","usePanneau","usePlugins","useResource","id","formOptions","$","_c","Error","resource","_c"],"sources":["../../src/react/provider.tsx"],"sourcesContent":["import { type ReactNode, createContext, use } from 'react';\n\nimport type { Definition } from '@panneau/protocol';\n\nimport { type ResolveFormOptions } from '../definition/form';\nimport { type ResolvedResource, findResource, resolveResource } from '../definition/resource';\nimport type { Router } from '../list/router';\nimport { type PanneauPlugin, type PluginRegistry, createPluginRegistry } from '../plugins';\n\n/** What `PanneauProvider` gives to the hooks below it. */\nexport interface PanneauContextValue {\n plugins: PluginRegistry;\n /** The plugins as passed, including those of parent providers. */\n pluginList: readonly PanneauPlugin[];\n definition: Definition | null;\n router: Router | null;\n}\n\nconst PanneauContext = createContext<PanneauContextValue | null>(null);\n\nexport interface PanneauProviderProps {\n /** Plugins, added after those of a parent provider (so they override them). */\n plugins?: readonly PanneauPlugin[];\n /** The definition, for `useResource()`. Defaults to the parent provider's. */\n definition?: Definition | null;\n /** The router that lists keep their query in. Defaults to the parent provider's. */\n router?: Router | null;\n children?: ReactNode;\n}\n\n/**\n * Provides plugins, the definition and the router to the hooks of `@panneau/core`. Providers can\n * be nested: a nested provider adds its plugins to those of its parent.\n */\nexport function PanneauProvider({\n plugins = [],\n definition,\n router,\n children,\n}: PanneauProviderProps) {\n const parent = use(PanneauContext);\n const pluginList = [...(parent?.pluginList ?? []), ...plugins];\n const value: PanneauContextValue = {\n plugins: createPluginRegistry(pluginList),\n pluginList,\n definition: definition === undefined ? (parent?.definition ?? null) : definition,\n router: router === undefined ? (parent?.router ?? null) : router,\n };\n return <PanneauContext value={value}>{children}</PanneauContext>;\n}\n\nconst EMPTY: PanneauContextValue = {\n plugins: createPluginRegistry([]),\n pluginList: [],\n definition: null,\n router: null,\n};\n\n/** The context of the closest `PanneauProvider`, or an empty one without a provider. */\nexport function usePanneau(): PanneauContextValue {\n return use(PanneauContext) ?? EMPTY;\n}\n\n/** The plugins of the closest `PanneauProvider`, merged. */\nexport function usePlugins(): PluginRegistry {\n return usePanneau().plugins;\n}\n\n/**\n * A resource of the definition, with its form, list and abilities resolved. Throws when there is\n * no definition or no such resource.\n */\nexport function useResource(id: string, formOptions?: ResolveFormOptions): ResolvedResource {\n const { definition } = usePanneau();\n if (definition === null) {\n throw new Error('useResource() needs a definition: pass one to <PanneauProvider>.');\n }\n const resource = findResource(definition, id);\n if (resource === undefined) {\n throw new Error(`The definition has no resource \\`${id}\\`.`);\n }\n return resolveResource(resource, formOptions);\n}\n"],"mappings":";;;;;;AAkBA,IAAMiB,iBAAiBhB,cAA0C,IAAI;;;;;AAgBrE,SAAOmB,gBAAAC,IAAA;CAAyB,MAAA,EAAAR,SAAAS,IAAAP,YAAAC,QAAAG,aAAAE;CAC5B,MAAAR,UAAAS,OAAAC,KAAAA,IAAA,CAAA,IAAAD;CAKA,MAAAE,SAAetB,IAAIe,cAAc;CACjC,MAAAH,aAAmB,CAAA,GAAKU,QAAMV,cAAN,CAAA,GAAwB,GAAMD,OAAO;CAC7D,MAAAY,QAAmC;EAAAZ,SACtBF,qBAAqBG,UAAU;EAACA;EAAAC,YAE7BA,eAAeQ,KAAAA,IAAaC,QAAMT,cAAN,OAA5BA;EAAoEC,QACxEA,WAAWO,KAAAA,IAAaC,QAAMR,UAAN,OAAxBA;CACZ;CAAE,OACK,oBAAC,gBAAD;EAAuBS;EAAQN;CAAhB,CAAA;AAA0C;AAGpE,IAAMO,QAA6B;CAC/Bb,SAASF,qBAAqB,CAAA,CAAE;CAChCG,YAAY,CAAA;CACZC,YAAY;CACZC,QAAQ;AACZ;;AAGA,SAAgBW,aAAkC;CAC9C,OAAOzB,IAAIe,cAAc,KAAKS;AAClC;;AAGA,SAAOE,aAAA;CAAA,OACID,WAAW,CAAC,CAAAd;AAAQ;;;;;AAO/B,SAAOgB,YAAAC,IAAAC,aAAA;CAAA,MAAAC,IAAAC,EAAA,CAAA;CACH,MAAA,EAAAlB,eAAuBY,WAAW;CAClC,IAAIZ,eAAe,MACf,MAAM,IAAImB,MAAM,kEAAkE;CACrF,IAAAb;CAAA,IAAAW,EAAA,OAAAjB,cAAAiB,EAAA,OAAAD,eAAAC,EAAA,OAAAF,IAAA;EACD,MAAAK,WAAiB7B,aAAaS,YAAYe,EAAE;EAC5C,IAAIK,aAAaZ,KAAAA,GACb,MAAM,IAAIW,MAAM,oCAAoCJ,GAAE,IAAK;EAExDT,KAAAd,gBAAgB4B,UAAUJ,WAAW;EAACC,EAAA,KAAAjB;EAAAiB,EAAA,KAAAD;EAAAC,EAAA,KAAAF;EAAAE,EAAA,KAAAX;CAAA,OAAAA,KAAAW,EAAA;CAAA,OAAtCX;AAAsC"}
@@ -1 +1 @@
1
- {"version":3,"file":"useForm.js","names":["_c"],"sources":["../../src/react/useForm.ts"],"sourcesContent":["import { useLayoutEffect, useState, useSyncExternalStore } from 'react';\n\nimport { type Form, type FormOptions, type FormState, createForm } from '../form/form';\nimport { selectErrors, selectValue } from '../form/selectors';\n\nexport interface UseFormResult extends FormState {\n /** The form, to change values, submit, reset or resolve a conflict. */\n form: Form;\n}\n\n/**\n * Creates a form for the life of the component. `fields`, `locales`, `formatError` and `onSubmit`\n * follow the latest render; initial values and the version don't: call `form.reset()`, or give\n * the component a new `key`, to start from another item.\n *\n * Read the returned state with the selectors (`selectErrors(state, path)`,\n * `selectVisible(state, field)`…), not with the form's reading methods, which go stale with the\n * React Compiler (see {@link Form}).\n */\nexport function useForm(options: FormOptions): UseFormResult {\n const [form] = useState(() => createForm(options));\n const { fields, locales, formatError, onSubmit } = options;\n useLayoutEffect(() => {\n form.setOptions({ fields, locales, formatError, onSubmit });\n });\n const state = useSyncExternalStore(form.subscribe, form.getState, form.getState);\n return { ...state, form };\n}\n\nexport interface UseFormFieldResult {\n value: unknown;\n onChange: (value: unknown) => void;\n onBlur: () => void;\n /** Errors at the path, and at nested paths (`title.fr` for `title`). */\n errors: string[];\n touched: boolean;\n}\n\n/** Props for a controlled field at a dot path of a form. */\nexport function useFormField(form: Form, path: string): UseFormFieldResult {\n const state = useSyncExternalStore(form.subscribe, form.getState, form.getState);\n return {\n value: selectValue(state, path),\n onChange: (value) => form.setValue(path, value),\n onBlur: () => form.blur(path),\n errors: selectErrors(state, path, { nested: true }),\n touched: state.touched.has(path),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,SAAO,QAAA,SAAA;CAAA,MAAA,IAAAA,EAAA,EAAA;CAAA,IAAA;CAAA,IAAA,EAAA,OAAA,SAAA;EACqB,WAAM,WAAW,OAAO;EAAC,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAAjD,MAAA,CAAA,QAAe,SAAS,EAAyB;CACjD,MAAA,EAAA,QAAA,SAAA,aAAA,aAAmD;CAAQ,IAAA;CAAA,IAAA,EAAA,OAAA,UAAA,EAAA,OAAA,QAAA,EAAA,OAAA,eAAA,EAAA,OAAA,WAAA,EAAA,OAAA,UAAA;EAC3C,WAAA;GACZ,KAAI,WAAY;IAAA;IAAA;IAAA;IAAA;GAAyC,CAAC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AAA,SAAA;EAC1C,KAAA,MAAK,QAAQ,IAAK,IAAI;EAAC,EAAA,MAAA;EAAA,EAAA,MAAA,MAAA;EAAA,EAAA,MAAA;CAAA,OAAA,KAAA,EAAA;CAAA,IAAA;CAAA,IAAA,EAAA,QAAA,MAAA,EAAA,QAAA,MAAA,EAAA,QAAA,MAAA,EAAA,QAAA,MAAA,EAAA,QAAA,IAAA;EAL7B,KAAA;GAAA,OACI;GAAwB,UACrB;GAAqC,QACvC;GAAqB,QACrB;GAA2C,SAC1C;EACb;EAAC,EAAA,MAAA;EAAA,EAAA,MAAA;EAAA,EAAA,MAAA;EAAA,EAAA,MAAA;EAAA,EAAA,MAAA;EAAA,EAAA,MAAA;CAAA,OAAA,KAAA,EAAA;CAAA,OANM;AAMN"}
1
+ {"version":3,"file":"useForm.js","names":["useLayoutEffect","useState","useSyncExternalStore","Form","FormOptions","FormState","createForm","selectErrors","selectValue","UseFormResult","form","useForm","options","$","_c","t0","fields","locales","formatError","onSubmit","t1","setOptions","state","subscribe","getState","t2","UseFormFieldResult","value","onChange","onBlur","errors","touched","useFormField","path","setValue","blur","t3","nested","t4","has","t5","_c"],"sources":["../../src/react/useForm.ts"],"sourcesContent":["import { useLayoutEffect, useState, useSyncExternalStore } from 'react';\n\nimport { type Form, type FormOptions, type FormState, createForm } from '../form/form';\nimport { selectErrors, selectValue } from '../form/selectors';\n\nexport interface UseFormResult extends FormState {\n /** The form, to change values, submit, reset or resolve a conflict. */\n form: Form;\n}\n\n/**\n * Creates a form for the life of the component. `fields`, `locales`, `formatError` and `onSubmit`\n * follow the latest render; initial values and the version don't: call `form.reset()`, or give\n * the component a new `key`, to start from another item.\n *\n * Read the returned state with the selectors (`selectErrors(state, path)`,\n * `selectVisible(state, field)`…), not with the form's reading methods, which go stale with the\n * React Compiler (see {@link Form}).\n */\nexport function useForm(options: FormOptions): UseFormResult {\n const [form] = useState(() => createForm(options));\n const { fields, locales, formatError, onSubmit } = options;\n useLayoutEffect(() => {\n form.setOptions({ fields, locales, formatError, onSubmit });\n });\n const state = useSyncExternalStore(form.subscribe, form.getState, form.getState);\n return { ...state, form };\n}\n\nexport interface UseFormFieldResult {\n value: unknown;\n onChange: (value: unknown) => void;\n onBlur: () => void;\n /** Errors at the path, and at nested paths (`title.fr` for `title`). */\n errors: string[];\n touched: boolean;\n}\n\n/** Props for a controlled field at a dot path of a form. */\nexport function useFormField(form: Form, path: string): UseFormFieldResult {\n const state = useSyncExternalStore(form.subscribe, form.getState, form.getState);\n return {\n value: selectValue(state, path),\n onChange: (value) => form.setValue(path, value),\n onBlur: () => form.blur(path),\n errors: selectErrors(state, path, { nested: true }),\n touched: state.touched.has(path),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,SAAOW,QAAAC,SAAA;CAAA,MAAAC,IAAAC,EAAA,EAAA;CAAA,IAAAC;CAAA,IAAAF,EAAA,OAAAD,SAAA;EACqBG,WAAMT,WAAWM,OAAO;EAACC,EAAA,KAAAD;EAAAC,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAjD,MAAA,CAAAH,QAAeT,SAASc,EAAyB;CACjD,MAAA,EAAAC,QAAAC,SAAAC,aAAAC,aAAmDP;CAAQ,IAAAQ;CAAA,IAAAP,EAAA,OAAAG,UAAAH,EAAA,OAAAH,QAAAG,EAAA,OAAAK,eAAAL,EAAA,OAAAI,WAAAJ,EAAA,OAAAM,UAAA;EAC3CC,WAAA;GACZV,KAAIW,WAAY;IAAAL;IAAAC;IAAAC;IAAAC;GAAyC,CAAC;EAAC;EAC9DN,EAAA,KAAAG;EAAAH,EAAA,KAAAH;EAAAG,EAAA,KAAAK;EAAAL,EAAA,KAAAI;EAAAJ,EAAA,KAAAM;EAAAN,EAAA,KAAAO;CAAA,OAAAA,KAAAP,EAAA;CAFDb,gBAAgBoB,EAEf;CACD,MAAAE,QAAcpB,qBAAqBQ,KAAIa,WAAYb,KAAIc,UAAWd,KAAIc,QAAS;CAAE,IAAAC;CAAA,IAAAZ,E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S;EAAAlB,EAAA,MAAAyB;CAAA,OAAAA,KAAAzB,EAAA;CAAA,IAAA2B;CAAA,IAAA3B,EAAA,QAAAE,MAAAF,EAAA,QAAAO,MAAAP,EAAA,QAAAY,MAAAZ,EAAA,QAAAuB,MAAAvB,EAAA,QAAAyB,IAAA;EAL7BE,KAAA;GAAAb,OACIZ;GAAwBa,UACrBR;GAAqCS,QACvCJ;GAAqBK,QACrBM;GAA2CL,SAC1CO;EACb;EAACzB,EAAA,MAAAE;EAAAF,EAAA,MAAAO;EAAAP,EAAA,MAAAY;EAAAZ,EAAA,MAAAuB;EAAAvB,EAAA,MAAAyB;EAAAzB,EAAA,MAAA2B;CAAA,OAAAA,KAAA3B,EAAA;CAAA,OANM2B;AAMN"}
@@ -1 +1 @@
1
- {"version":3,"file":"useList.js","names":["_c"],"sources":["../../src/react/useList.ts"],"sourcesContent":["import { useState, useSyncExternalStore } from 'react';\n\nimport { type List, type ListOptions, type ListState, createList } from '../list/list';\nimport { usePanneau } from './provider';\n\nexport interface UseListResult extends ListState {\n /** The list, to change the query and the selection. */\n list: List;\n}\n\n/**\n * Creates a list for the life of the component. Without a `router` option, the query is kept in\n * the router of the closest `PanneauProvider`, if any. Pass `router: null` to keep it in memory.\n */\nexport function useList(options: ListOptions = {}): UseListResult {\n const context = usePanneau();\n const [list] = useState(() =>\n createList({\n ...options,\n router: options.router === undefined ? context.router : options.router,\n }),\n );\n const state = useSyncExternalStore(list.subscribe, list.getState, list.getState);\n return { ...state, list };\n}\n"],"mappings":";;;;;;;;;AAcA,SAAO,QAAA,IAAA;CAAA,MAAA,IAAAA,EAAA,CAAA;CAAA,IAAA;CAAA,IAAA,EAAA,OAAA,IAAA;EAAiB,KAAA,OAAA,KAAA,IAAA,CAAwB,IAAxB;EAAyB,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAAzB,MAAA,UAAA;CACpB,MAAA,UAAgB,WAAW;CAAE,IAAA;CAAA,IAAA,EAAA,OAAA,WAAA,EAAA,OAAA,SAAA;EACL,WACpB,WAAW;GAAA,GACJ;GAAO,QACF,QAAO,WAAY,KAAA,IAAY,QAAO,SAAU,QAAO;EACnE,CAAC;EAAC,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAJN,MAAA,CAAA,QAAe,SAAS,EAKxB;CACA,MAAA,QAAc,qBAAqB,KAAI,WAAY,KAAI,UAAW,KAAI,QAAS;CAAE,IAAA;CAAA,IAAA,EAAA,OAAA,QAAA,EAAA,OAAA,OAAA;EAC1E,KAAA;GAAA,GAAK;GAAK;EAAO;EAAC,EAAA,KAAA;EAAA,EAAA,KAAA;EAAA,EAAA,KAAA;CAAA,OAAA,KAAA,EAAA;CAAA,OAAlB;AAAkB"}
1
+ {"version":3,"file":"useList.js","names":["useState","useSyncExternalStore","List","ListOptions","ListState","createList","usePanneau","UseListResult","list","useList","t0","$","_c","t1","undefined","options","context","t2","router","state","subscribe","getState","t3","_c"],"sources":["../../src/react/useList.ts"],"sourcesContent":["import { useState, useSyncExternalStore } from 'react';\n\nimport { type List, type ListOptions, type ListState, createList } from '../list/list';\nimport { usePanneau } from './provider';\n\nexport interface UseListResult extends ListState {\n /** The list, to change the query and the selection. */\n list: List;\n}\n\n/**\n * Creates a list for the life of the component. Without a `router` option, the query is kept in\n * the router of the closest `PanneauProvider`, if any. Pass `router: null` to keep it in memory.\n */\nexport function useList(options: ListOptions = {}): UseListResult {\n const context = usePanneau();\n const [list] = useState(() =>\n createList({\n ...options,\n router: options.router === undefined ? context.router : options.router,\n }),\n );\n const state = useSyncExternalStore(list.subscribe, list.getState, list.getState);\n return { ...state, list };\n}\n"],"mappings":";;;;;;;;;AAcA,SAAOS,QAAAC,IAAA;CAAA,MAAAC,IAAAC,EAAA,CAAA;CAAA,IAAAC;CAAA,IAAAF,EAAA,OAAAD,IAAA;EAAiBG,KAAAH,OAAAI,KAAAA,IAAA,CAAwB,IAAxBJ;EAAyBC,EAAA,KAAAD;EAAAC,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAzB,MAAAI,UAAAF;CACpB,MAAAG,UAAgBV,WAAW;CAAE,IAAAW;CAAA,IAAAN,EAAA,OAAAK,WAAAL,EAAA,OAAAI,SAAA;EACLE,WACpBZ,WAAW;GAAA,GACJU;GAAOG,QACFH,QAAOG,WAAYJ,KAAAA,IAAYE,QAAOE,SAAUH,QAAOG;EACnE,CAAC;EAACP,EAAA,KAAAK;EAAAL,EAAA,KAAAI;EAAAJ,EAAA,KAAAM;CAAA,OAAAA,KAAAN,EAAA;CAJN,MAAA,CAAAH,QAAeR,SAASiB,EAKxB;CACA,MAAAE,QAAclB,qBAAqBO,KAAIY,WAAYZ,KAAIa,UAAWb,KAAIa,QAAS;CAAE,IAAAC;CAAA,IAAAX,EAAA,OAAAH,QAAAG,EAAA,OAAAQ,OAAA;EAC1EG,KAAA;GAAA,GAAKH;GAAKX;EAAO;EAACG,EAAA,KAAAH;EAAAG,EAAA,KAAAQ;EAAAR,EAAA,KAAAW;CAAA,OAAAA,KAAAX,EAAA;CAAA,OAAlBW;AAAkB"}
@@ -1 +1 @@
1
- {"version":3,"file":"values.js","names":[],"sources":["../src/values.ts"],"sourcesContent":["/** Values of a form or an item, keyed by field name. */\nexport type Values = Record<string, unknown>;\n\nfunction isIndex(segment: string): boolean {\n return /^\\d+$/.test(segment);\n}\n\nfunction setIn(current: unknown, segments: string[], value: unknown): unknown {\n const [segment, ...rest] = segments;\n if (segment === undefined) {\n return value;\n }\n if (isIndex(segment)) {\n const array = Array.isArray(current) ? [...(current as unknown[])] : [];\n array[Number(segment)] = setIn(array[Number(segment)], rest, value);\n return array;\n }\n const record =\n current !== null && typeof current === 'object' && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : {};\n return { ...record, [segment]: setIn(record[segment], rest, value) };\n}\n\n/**\n * Returns a copy of `values` with `value` at a dot path (`title.fr`, `blocks.2.body`). Missing\n * objects and arrays are created: numeric segments create arrays.\n */\nexport function setValue<T extends Values>(values: T, path: string, value: unknown): T {\n if (path === '') {\n return value as T;\n }\n return setIn(values, path.split('.'), value) as T;\n}\n\n/** Deep equality of JSON-like values. */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => isEqual(item, b[index]));\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n return [...keys].every((key) => isEqual(left[key], right[key]));\n}\n\n/** Whether `path` is `parent` or inside it (`title.fr` is inside `title`). */\nexport function isPathWithin(path: string, parent: string): boolean {\n return parent === '' || path === parent || path.startsWith(`${parent}.`);\n}\n"],"mappings":";AAGA,SAAS,QAAQ,SAA0B;CACvC,OAAO,QAAQ,KAAK,OAAO;AAC/B;AAEA,SAAS,MAAM,SAAkB,UAAoB,OAAyB;CAC1E,MAAM,CAAC,SAAS,GAAG,QAAQ;CAC3B,IAAI,YAAY,KAAA,GACZ,OAAO;CAEX,IAAI,QAAQ,OAAO,GAAG;EAClB,MAAM,QAAQ,MAAM,QAAQ,OAAO,IAAI,CAAC,GAAI,OAAqB,IAAI,CAAA;EACrE,MAAM,OAAO,OAAO,KAAK,MAAM,MAAM,OAAO,OAAO,IAAI,MAAM,KAAK;EAClE,OAAO;CACX;CACA,MAAM,SACF,YAAY,QAAQ,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,OAAO,IAClE,UACD,CAAC;CACX,OAAO;EAAE,GAAG;GAAS,UAAU,MAAM,OAAO,UAAU,MAAM,KAAK;CAAE;AACvE;;;;;AAMA,SAAgB,SAA2B,QAAW,MAAc,OAAmB;CACnF,IAAI,SAAS,IACT,OAAO;CAEX,OAAO,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG,KAAK;AAC/C;;AAGA,SAAgB,QAAQ,GAAY,GAAqB;CACrD,IAAI,OAAO,GAAG,GAAG,CAAC,GACd,OAAO;CAEX,IAAI,MAAM,QAAQ,MAAM,QAAQ,OAAO,MAAM,YAAY,OAAO,MAAM,UAClE,OAAO;CAEX,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GACpC,OAAO;CAEX,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACnC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,MAAM,UAAU,QAAQ,MAAM,EAAE,MAAM,CAAC;CAEpF,MAAM,OAAO;CACb,MAAM,QAAQ;CAEd,OAAO,CAAC,mBAAG,IADM,IAAI,CAAC,GAAG,OAAO,KAAK,IAAI,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CACtD,CAAI,CAAC,CAAC,OAAO,QAAQ,QAAQ,KAAK,MAAM,MAAM,IAAI,CAAC;AAClE;;AAGA,SAAgB,aAAa,MAAc,QAAyB;CAChE,OAAO,WAAW,MAAM,SAAS,UAAU,KAAK,WAAW,GAAG,OAAM,EAAG;AAC3E"}
1
+ {"version":3,"file":"values.js","names":["Values","Record","isIndex","segment","test","setIn","current","segments","value","rest","undefined","array","Array","isArray","Number","record","setValue","values","T","path","split","isEqual","a","b","Object","is","length","every","item","index","left","right","keys","Set","key","isPathWithin","parent","startsWith"],"sources":["../src/values.ts"],"sourcesContent":["/** Values of a form or an item, keyed by field name. */\nexport type Values = Record<string, unknown>;\n\nfunction isIndex(segment: string): boolean {\n return /^\\d+$/.test(segment);\n}\n\nfunction setIn(current: unknown, segments: string[], value: unknown): unknown {\n const [segment, ...rest] = segments;\n if (segment === undefined) {\n return value;\n }\n if (isIndex(segment)) {\n const array = Array.isArray(current) ? [...(current as unknown[])] : [];\n array[Number(segment)] = setIn(array[Number(segment)], rest, value);\n return array;\n }\n const record =\n current !== null && typeof current === 'object' && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : {};\n return { ...record, [segment]: setIn(record[segment], rest, value) };\n}\n\n/**\n * Returns a copy of `values` with `value` at a dot path (`title.fr`, `blocks.2.body`). Missing\n * objects and arrays are created: numeric segments create arrays.\n */\nexport function setValue<T extends Values>(values: T, path: string, value: unknown): T {\n if (path === '') {\n return value as T;\n }\n return setIn(values, path.split('.'), value) as T;\n}\n\n/** Deep equality of JSON-like values. */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => isEqual(item, b[index]));\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n return [...keys].every((key) => isEqual(left[key], right[key]));\n}\n\n/** Whether `path` is `parent` or inside it (`title.fr` is inside `title`). */\nexport function isPathWithin(path: string, parent: string): boolean {\n return parent === '' || path === parent || path.startsWith(`${parent}.`);\n}\n"],"mappings":";AAGA,SAASE,QAAQC,SAA0B;CACvC,OAAO,QAAQC,KAAKD,OAAO;AAC/B;AAEA,SAASE,MAAMC,SAAkBC,UAAoBC,OAAyB;CAC1E,MAAM,CAACL,SAAS,GAAGM,QAAQF;CAC3B,IAAIJ,YAAYO,KAAAA,GACZ,OAAOF;CAEX,IAAIN,QAAQC,OAAO,GAAG;EAClB,MAAMQ,QAAQC,MAAMC,QAAQP,OAAO,IAAI,CAAC,GAAIA,OAAqB,IAAI,CAAA;EACrEK,MAAMG,OAAOX,OAAO,KAAKE,MAAMM,MAAMG,OAAOX,OAAO,IAAIM,MAAMD,KAAK;EAClE,OAAOG;CACX;CACA,MAAMI,SACFT,YAAY,QAAQ,OAAOA,YAAY,YAAY,CAACM,MAAMC,QAAQP,OAAO,IAClEA,UACD,CAAC;CACX,OAAO;EAAE,GAAGS;GAASZ,UAAUE,MAAMU,OAAOZ,UAAUM,MAAMD,KAAK;CAAE;AACvE;;;;;AAMA,SAAgBQ,SAA2BC,QAAWE,MAAcX,OAAmB;CACnF,IAAIW,SAAS,IACT,OAAOX;CAEX,OAAOH,MAAMY,QAAQE,KAAKC,MAAM,GAAG,GAAGZ,KAAK;AAC/C;;AAGA,SAAgBa,QAAQC,GAAYC,GAAqB;CACrD,IAAIC,OAAOC,GAAGH,GAAGC,CAAC,GACd,OAAO;CAEX,IAAID,MAAM,QAAQC,MAAM,QAAQ,OAAOD,MAAM,YAAY,OAAOC,MAAM,UAClE,OAAO;CAEX,IAAIX,MAAMC,QAAQS,CAAC,MAAMV,MAAMC,QAAQU,CAAC,GACpC,OAAO;CAEX,IAAIX,MAAMC,QAAQS,CAAC,KAAKV,MAAMC,QAAQU,CAAC,GACnC,OAAOD,EAAEI,WAAWH,EAAEG,UAAUJ,EAAEK,OAAOC,MAAMC,UAAUR,QAAQO,MAAML,EAAEM,MAAM,CAAC;CAEpF,MAAMC,OAAOR;CACb,MAAMS,QAAQR;CAEd,OAAO,CAAC,mBAAGS,IADMC,IAAI,CAAC,GAAGT,OAAOQ,KAAKF,IAAI,GAAG,GAAGN,OAAOQ,KAAKD,KAAK,CAAC,CACtDC,CAAI,CAAC,CAACL,OAAOO,QAAQb,QAAQS,KAAKI,MAAMH,MAAMG,IAAI,CAAC;AAClE;;AAGA,SAAgBC,aAAahB,MAAciB,QAAyB;CAChE,OAAOA,WAAW,MAAMjB,SAASiB,UAAUjB,KAAKkB,WAAW,GAAGD,OAAM,EAAG;AAC3E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panneau/core",
3
- "version": "5.0.0-alpha.5",
3
+ "version": "5.0.0-alpha.7",
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.5"
36
+ "@panneau/protocol": "5.0.0-alpha.7"
37
37
  }
38
38
  }