@panneau/core 5.0.0-alpha.0 → 5.0.0-alpha.10

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.
Files changed (71) hide show
  1. package/README.md +2 -0
  2. package/dist/commands.d.ts +38 -0
  3. package/dist/commands.d.ts.map +1 -0
  4. package/dist/commands.js +22 -0
  5. package/dist/commands.js.map +1 -0
  6. package/dist/definition/abilities.d.ts +15 -4
  7. package/dist/definition/abilities.d.ts.map +1 -1
  8. package/dist/definition/abilities.js +18 -5
  9. package/dist/definition/abilities.js.map +1 -1
  10. package/dist/definition/form.d.ts +3 -2
  11. package/dist/definition/form.d.ts.map +1 -1
  12. package/dist/definition/form.js +24 -2
  13. package/dist/definition/form.js.map +1 -1
  14. package/dist/definition/itemActions.d.ts +53 -0
  15. package/dist/definition/itemActions.d.ts.map +1 -0
  16. package/dist/definition/itemActions.js +64 -0
  17. package/dist/definition/itemActions.js.map +1 -0
  18. package/dist/definition/list.d.ts +16 -0
  19. package/dist/definition/list.d.ts.map +1 -1
  20. package/dist/definition/list.js +64 -3
  21. package/dist/definition/list.js.map +1 -1
  22. package/dist/definition/resource.d.ts +2 -2
  23. package/dist/definition/resource.js +1 -1
  24. package/dist/definition/resource.js.map +1 -1
  25. package/dist/form/form.d.ts +9 -4
  26. package/dist/form/form.d.ts.map +1 -1
  27. package/dist/form/form.js +2 -1
  28. package/dist/form/form.js.map +1 -1
  29. package/dist/form/messages.d.ts.map +1 -1
  30. package/dist/form/messages.js +1 -0
  31. package/dist/form/messages.js.map +1 -1
  32. package/dist/form/problem.d.ts +2 -2
  33. package/dist/form/problem.d.ts.map +1 -1
  34. package/dist/form/problem.js +1 -1
  35. package/dist/form/problem.js.map +1 -1
  36. package/dist/form/selectors.d.ts +2 -2
  37. package/dist/form/selectors.d.ts.map +1 -1
  38. package/dist/form/selectors.js +1 -1
  39. package/dist/form/selectors.js.map +1 -1
  40. package/dist/form/store.d.ts +1 -1
  41. package/dist/form/store.js.map +1 -1
  42. package/dist/index.d.ts +20 -16
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +6 -3
  45. package/dist/list/list.d.ts +14 -3
  46. package/dist/list/list.d.ts.map +1 -1
  47. package/dist/list/list.js +39 -11
  48. package/dist/list/list.js.map +1 -1
  49. package/dist/list/router.js.map +1 -1
  50. package/dist/plugins.d.ts +22 -10
  51. package/dist/plugins.d.ts.map +1 -1
  52. package/dist/plugins.js +23 -3
  53. package/dist/plugins.js.map +1 -1
  54. package/dist/preview.d.ts +14 -0
  55. package/dist/preview.d.ts.map +1 -0
  56. package/dist/react/leaveGuards.d.ts +34 -0
  57. package/dist/react/leaveGuards.d.ts.map +1 -0
  58. package/dist/react/leaveGuards.js +84 -0
  59. package/dist/react/leaveGuards.js.map +1 -0
  60. package/dist/react/provider.d.ts +4 -4
  61. package/dist/react/provider.js +3 -1
  62. package/dist/react/provider.js.map +1 -1
  63. package/dist/react/useForm.d.ts +1 -1
  64. package/dist/react/useForm.js.map +1 -1
  65. package/dist/react/useList.d.ts +1 -1
  66. package/dist/react/useList.js.map +1 -1
  67. package/dist/values.d.ts +1 -1
  68. package/dist/values.d.ts.map +1 -1
  69. package/dist/values.js +5 -1
  70. package/dist/values.js.map +1 -1
  71. package/package.json +4 -4
package/dist/list/list.js CHANGED
@@ -1,18 +1,24 @@
1
1
  import { isEqual } from "../values.js";
2
- import { fromSearchParams, toSearchParams } from "@panneau/protocol";
2
+ import { fromSearchParams, isFilterRange, toSearchParams } from "@panneau/protocol/runtime";
3
3
  //#region src/list/list.ts
4
4
  var EMPTY_SELECTION = {
5
5
  mode: "ids",
6
6
  ids: []
7
7
  };
8
- var LIST_PARAM = /^(page|perPage|sort|q|fields|filter\[.+)$/;
8
+ /** Back to the first page: page 1, or no cursor. */
9
+ var FIRST_PAGE = {
10
+ page: 1,
11
+ cursor: void 0
12
+ };
13
+ var LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|filter\[.+)$/;
9
14
  /** Removes the values that are the defaults, so the URL only keeps what the user changed. */
10
15
  function normalize(query, defaults) {
11
16
  const result = {};
12
17
  if (query.page !== void 0 && query.page > 1) result.page = query.page;
13
18
  if (query.perPage !== void 0 && query.perPage !== defaults.perPage) result.perPage = query.perPage;
19
+ if (query.cursor !== void 0 && query.cursor !== "") result.cursor = query.cursor;
14
20
  if (query.sort !== void 0 && !isEqual(query.sort, defaults.sort)) result.sort = [...query.sort];
15
- const filter = Object.fromEntries(Object.entries(query.filter ?? {}).filter(([, value]) => value !== "" && !(Array.isArray(value) && value.length === 0)));
21
+ const filter = Object.fromEntries(Object.entries(query.filter ?? {}).filter(([, value]) => value !== "" && !(Array.isArray(value) && value.length === 0) && !(isFilterRange(value) && Object.keys(value).length === 0)));
16
22
  if (Object.keys(filter).length > 0) result.filter = filter;
17
23
  if (query.q !== void 0 && query.q !== "") result.q = query.q;
18
24
  if (query.fields !== void 0) result.fields = query.fields;
@@ -28,10 +34,12 @@ function createList(options = {}) {
28
34
  const readRouter = () => router !== null ? normalize(fromSearchParams(new URLSearchParams(router.getSearch())), defaults) : {};
29
35
  let params = router !== null ? readRouter() : normalize(options.query ?? {}, defaults);
30
36
  let selection = EMPTY_SELECTION;
37
+ let trail = [];
38
+ const cursors = options.list?.pagination === "cursor";
31
39
  const compute = () => ({
32
40
  query: {
33
41
  ...params,
34
- page: params.page ?? 1,
42
+ ...cursors ? {} : { page: params.page ?? 1 },
35
43
  perPage: params.perPage ?? defaults.perPage,
36
44
  ...params.sort !== void 0 || defaults.sort.length > 0 ? { sort: params.sort ?? defaults.sort } : {}
37
45
  },
@@ -55,6 +63,9 @@ function createList(options = {}) {
55
63
  const normalized = normalize(next, defaults);
56
64
  if (isEqual(normalized, params)) return;
57
65
  const scopeChanged = !isEqual(normalized.filter, params.filter) || normalized.q !== params.q;
66
+ const { cursor: _next, ...nextQuery } = normalized;
67
+ const { cursor: _current, ...currentQuery } = params;
68
+ if (!isEqual(nextQuery, currentQuery)) trail = [];
58
69
  params = normalized;
59
70
  if (scopeChanged) selection = EMPTY_SELECTION;
60
71
  writeRouter(replace);
@@ -95,33 +106,50 @@ function createList(options = {}) {
95
106
  ...params,
96
107
  page
97
108
  }),
109
+ nextPage(cursor) {
110
+ const current = params.cursor ?? null;
111
+ setParams({
112
+ ...params,
113
+ cursor
114
+ });
115
+ trail = [...trail, current];
116
+ },
117
+ previousPage(cursor) {
118
+ const back = cursor !== void 0 ? cursor : trail.at(-1) ?? null;
119
+ const rest = trail.slice(0, -1);
120
+ setParams({
121
+ ...params,
122
+ cursor: back ?? void 0
123
+ });
124
+ trail = rest;
125
+ },
98
126
  setPerPage: (perPage) => setParams({
99
127
  ...params,
100
128
  perPage,
101
- page: 1
129
+ ...FIRST_PAGE
102
130
  }),
103
131
  setSort: (sort) => setParams({
104
132
  ...params,
105
133
  sort: [...sort],
106
- page: 1
134
+ ...FIRST_PAGE
107
135
  }),
108
136
  toggleSort(field) {
109
137
  const sort = state.query.sort ?? [];
110
138
  if (sort[0] === field) setParams({
111
139
  ...params,
112
140
  sort: [`-${field}`],
113
- page: 1
141
+ ...FIRST_PAGE
114
142
  });
115
143
  else if (sort[0] === `-${field}` && params.sort !== void 0) {
116
144
  const { sort: _sort, ...rest } = params;
117
145
  setParams({
118
146
  ...rest,
119
- page: 1
147
+ ...FIRST_PAGE
120
148
  });
121
149
  } else setParams({
122
150
  ...params,
123
151
  sort: [field],
124
- page: 1
152
+ ...FIRST_PAGE
125
153
  });
126
154
  },
127
155
  setFilter(id, value) {
@@ -132,13 +160,13 @@ function createList(options = {}) {
132
160
  ...filter,
133
161
  [id]: value
134
162
  },
135
- page: 1
163
+ ...FIRST_PAGE
136
164
  });
137
165
  },
138
166
  setSearch: (q) => setParams({
139
167
  ...params,
140
168
  q,
141
- page: 1
169
+ ...FIRST_PAGE
142
170
  }, { replace: true }),
143
171
  resetQuery: () => setParams({}),
144
172
  select(ids) {
@@ -1 +1 @@
1
- {"version":3,"file":"list.js","names":[],"sources":["../../src/list/list.ts"],"sourcesContent":["import {\n type FilterValue,\n type ListQuery,\n type Selection,\n fromSearchParams,\n toSearchParams,\n} from '@panneau/protocol';\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]) => value !== '' && !(Array.isArray(value) && 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":";;;AA0EA,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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":"list.js","names":["FilterValue","ListQuery","Selection","fromSearchParams","isFilterRange","toSearchParams","ResolvedList","isEqual","Router","ListSelection","mode","ids","except","ListState","query","selection","ListDefaults","perPage","sort","ListOptions","list","defaults","router","List","getState","subscribe","listener","setPage","page","nextPage","cursor","previousPage","setPerPage","setSort","toggleSort","field","setFilter","id","value","setSearch","q","resetQuery","select","deselect","toggle","selectAllMatching","clearSelection","isSelected","getSelectedCount","total","getSelection","EMPTY_SELECTION","FIRST_PAGE","undefined","LIST_PARAM","normalize","Required","result","filter","Object","fromEntries","entries","Array","isArray","length","keys","fields","createList","options","defaultSort","readRouter","URLSearchParams","getSearch","params","trail","cursors","pagination","compute","state","listeners","Set","notify","forEach","writeRouter","replace","search","key","test","delete","append","next","toString","setParams","normalized","scopeChanged","_next","nextQuery","_current","currentQuery","setSelection","unsubscribeRouter","onRouterChange","add","size","current","back","at","rest","slice","_sort","_removed","includes","Math","max","Record"],"sources":["../../src/list/list.ts"],"sourcesContent":["import type { FilterValue, ListQuery, Selection } from '@panneau/protocol';\nimport { fromSearchParams, isFilterRange, toSearchParams } from '@panneau/protocol/runtime';\n\nimport type { ResolvedList } from '../definition/list';\nimport { isEqual } from '../values';\nimport type { Router } from './router';\n\n/**\n * Selected items: some ids, or every item matching the list query (filters and search) except\n * some ids. \"All matching\" covers the items of every page.\n */\nexport type ListSelection =\n { mode: 'ids'; ids: readonly string[] } | { mode: 'all'; except: readonly string[] };\n\nexport interface ListState {\n /** The query to fetch: the list's defaults, overridden by the current state. */\n query: ListQuery;\n selection: ListSelection;\n}\n\nexport interface ListDefaults {\n perPage?: number;\n /** Default sort, as `sort` query values (`['-published_at']`). */\n sort?: string[];\n}\n\nexport interface ListOptions {\n /** A resolved list, for the defaults (`perPage`, `defaultSort`). */\n list?: ResolvedList;\n /** Defaults, over those of `list`. Default values are not written to the URL. */\n defaults?: ListDefaults;\n /** The starting query, when there is no router. */\n query?: ListQuery;\n /** Keeps the query in the URL. The router's query string wins over `query`. */\n router?: Router | null;\n}\n\n/** A headless list: query and selection. React components use `useList()`. */\nexport interface List {\n getState(): ListState;\n subscribe(listener: () => void): () => void;\n setPage(page: number): void;\n /**\n * In a list paged with cursors: goes to the page of `nextCursor`, and remembers the cursor of\n * the page it leaves, for `previousPage()`.\n */\n nextPage(cursor: string): void;\n /**\n * In a list paged with cursors: goes back a page, to `previousCursor` when the backend gives\n * one (`null` for the first page), or else to the page it came from. Without either, it goes\n * to the first page.\n */\n previousPage(cursor?: string | null): void;\n /** Sets the page size, and goes back to the first page. */\n setPerPage(perPage: number): void;\n /** Sets the sort (`['-published_at', 'title']`), and goes back to the first page. */\n setSort(sort: readonly string[]): void;\n /** Sorts by a field: ascending, then descending, then back to the default sort. */\n toggleSort(field: string): void;\n /** Sets or removes (`undefined`) a filter, goes back to the first page, and clears the selection. */\n setFilter(id: string, value: FilterValue | undefined): void;\n /** Sets the search, goes back to the first page, and clears the selection. */\n setSearch(q: string): void;\n /** Removes the page, filters, search and sort: back to the defaults. */\n resetQuery(): void;\n /** Adds ids to the selection (removes them from the exceptions in \"all matching\" mode). */\n select(ids: readonly string[]): void;\n /** Removes ids from the selection (adds them to the exceptions in \"all matching\" mode). */\n deselect(ids: readonly string[]): void;\n toggle(id: string): void;\n /** Selects every item matching the query, on every page. */\n selectAllMatching(): void;\n clearSelection(): void;\n isSelected(id: string): boolean;\n /** How many items are selected, given the total of the list. */\n getSelectedCount(total: number): number;\n /** The selection to send with an action, or `null` when nothing is selected. */\n getSelection(): Selection | null;\n}\n\nconst EMPTY_SELECTION: ListSelection = { mode: 'ids', ids: [] };\n/** Back to the first page: page 1, or no cursor. */\nconst FIRST_PAGE = { page: 1, cursor: undefined };\nconst LIST_PARAM = /^(page|perPage|cursor|sort|q|fields|filter\\[.+)$/;\n\n/** Removes the values that are the defaults, so the URL only keeps what the user changed. */\nfunction normalize(query: ListQuery, defaults: Required<ListDefaults>): ListQuery {\n const result: ListQuery = {};\n if (query.page !== undefined && query.page > 1) {\n result.page = query.page;\n }\n if (query.perPage !== undefined && query.perPage !== defaults.perPage) {\n result.perPage = query.perPage;\n }\n if (query.cursor !== undefined && query.cursor !== '') {\n result.cursor = query.cursor;\n }\n if (query.sort !== undefined && !isEqual(query.sort, defaults.sort)) {\n result.sort = [...query.sort];\n }\n const filter = Object.fromEntries(\n Object.entries(query.filter ?? {}).filter(\n ([, value]) =>\n value !== '' &&\n !(Array.isArray(value) && value.length === 0) &&\n !(isFilterRange(value) && Object.keys(value).length === 0),\n ),\n );\n if (Object.keys(filter).length > 0) {\n result.filter = filter;\n }\n if (query.q !== undefined && query.q !== '') {\n result.q = query.q;\n }\n if (query.fields !== undefined) {\n result.fields = query.fields;\n }\n return result;\n}\n\n/** Creates a headless list. */\nexport function createList(options: ListOptions = {}): List {\n const defaults: Required<ListDefaults> = {\n perPage: options.defaults?.perPage ?? options.list?.perPage ?? 20,\n sort: options.defaults?.sort ?? options.list?.defaultSort ?? [],\n };\n const router = options.router ?? null;\n const readRouter = (): ListQuery =>\n router !== null\n ? normalize(fromSearchParams(new URLSearchParams(router.getSearch())), defaults)\n : {};\n\n let params: ListQuery =\n router !== null ? readRouter() : normalize(options.query ?? {}, defaults);\n let selection: ListSelection = EMPTY_SELECTION;\n // The cursors of the pages before this one, as `nextPage()` followed them.\n let trail: (string | null)[] = [];\n\n // A list paged with cursors has no page numbers: its query has a cursor, after the first page.\n const cursors = options.list?.pagination === 'cursor';\n const compute = (): ListState => ({\n query: {\n ...params,\n ...(cursors ? {} : { page: params.page ?? 1 }),\n perPage: params.perPage ?? defaults.perPage,\n ...(params.sort !== undefined || defaults.sort.length > 0\n ? { sort: params.sort ?? defaults.sort }\n : {}),\n },\n selection,\n });\n\n let state = compute();\n const listeners = new Set<() => void>();\n const notify = () => {\n state = compute();\n listeners.forEach((listener) => listener());\n };\n\n const writeRouter = (replace: boolean) => {\n if (router === null) {\n return;\n }\n const search = new URLSearchParams(router.getSearch());\n [...search.keys()]\n .filter((key) => LIST_PARAM.test(key))\n .forEach((key) => search.delete(key));\n toSearchParams(params).forEach((value, key) => search.append(key, value));\n const next = search.toString();\n if (next !== router.getSearch()) {\n router.setSearch(next, { replace });\n }\n };\n\n const setParams = (next: ListQuery, { replace = false } = {}) => {\n const normalized = normalize(next, defaults);\n if (isEqual(normalized, params)) {\n return;\n }\n const scopeChanged =\n !isEqual(normalized.filter, params.filter) || normalized.q !== params.q;\n // Another query starts its pages over.\n const { cursor: _next, ...nextQuery } = normalized;\n const { cursor: _current, ...currentQuery } = params;\n if (!isEqual(nextQuery, currentQuery)) {\n trail = [];\n }\n params = normalized;\n if (scopeChanged) {\n selection = EMPTY_SELECTION;\n }\n writeRouter(replace);\n notify();\n };\n\n const setSelection = (next: ListSelection) => {\n selection = next;\n notify();\n };\n\n let unsubscribeRouter: (() => void) | null = null;\n const onRouterChange = () => {\n const next = readRouter();\n if (isEqual(next, params)) {\n return;\n }\n if (!isEqual(next.filter, params.filter) || next.q !== params.q) {\n selection = EMPTY_SELECTION;\n }\n params = next;\n notify();\n };\n\n const list: List = {\n getState() {\n if (router !== null && unsubscribeRouter === null) {\n onRouterChange();\n }\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n if (router !== null && unsubscribeRouter === null) {\n unsubscribeRouter = router.subscribe(onRouterChange);\n onRouterChange();\n }\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0 && unsubscribeRouter !== null) {\n unsubscribeRouter();\n unsubscribeRouter = null;\n }\n };\n },\n setPage: (page) => setParams({ ...params, page }),\n nextPage(cursor) {\n const current = params.cursor ?? null;\n setParams({ ...params, cursor });\n trail = [...trail, current];\n },\n previousPage(cursor) {\n const back = cursor !== undefined ? cursor : (trail.at(-1) ?? null);\n const rest = trail.slice(0, -1);\n setParams({ ...params, cursor: back ?? undefined });\n trail = rest;\n },\n setPerPage: (perPage) => setParams({ ...params, perPage, ...FIRST_PAGE }),\n setSort: (sort) => setParams({ ...params, sort: [...sort], ...FIRST_PAGE }),\n toggleSort(field) {\n const sort = state.query.sort ?? [];\n if (sort[0] === field) {\n setParams({ ...params, sort: [`-${field}`], ...FIRST_PAGE });\n } else if (sort[0] === `-${field}` && params.sort !== undefined) {\n const { sort: _sort, ...rest } = params;\n setParams({ ...rest, ...FIRST_PAGE });\n } else {\n setParams({ ...params, sort: [field], ...FIRST_PAGE });\n }\n },\n setFilter(id, value) {\n const { [id]: _removed, ...filter } = params.filter ?? {};\n setParams({\n ...params,\n filter: value === undefined ? filter : { ...filter, [id]: value },\n ...FIRST_PAGE,\n });\n },\n setSearch: (q) => setParams({ ...params, q, ...FIRST_PAGE }, { replace: true }),\n resetQuery: () => setParams({}),\n select(ids) {\n if (selection.mode === 'all') {\n setSelection({\n mode: 'all',\n except: selection.except.filter((id) => !ids.includes(id)),\n });\n } else {\n setSelection({ mode: 'ids', ids: [...new Set([...selection.ids, ...ids])] });\n }\n },\n deselect(ids) {\n if (selection.mode === 'all') {\n setSelection({ mode: 'all', except: [...new Set([...selection.except, ...ids])] });\n } else {\n setSelection({ mode: 'ids', ids: selection.ids.filter((id) => !ids.includes(id)) });\n }\n },\n toggle(id) {\n if (list.isSelected(id)) {\n list.deselect([id]);\n } else {\n list.select([id]);\n }\n },\n selectAllMatching: () => setSelection({ mode: 'all', except: [] }),\n clearSelection: () => setSelection(EMPTY_SELECTION),\n isSelected: (id) =>\n selection.mode === 'all' ? !selection.except.includes(id) : selection.ids.includes(id),\n getSelectedCount: (total) =>\n selection.mode === 'all'\n ? Math.max(0, total - selection.except.length)\n : selection.ids.length,\n getSelection() {\n if (selection.mode === 'ids') {\n return selection.ids.length > 0 ? { ids: [...selection.ids] } : null;\n }\n const query: { filter?: Record<string, unknown>; q?: string } = {};\n if (params.filter !== undefined) {\n query.filter = params.filter;\n }\n if (params.q !== undefined) {\n query.q = params.q;\n }\n return selection.except.length > 0\n ? { query, except: [...selection.except] }\n : { query };\n },\n };\n return list;\n}\n"],"mappings":";;;AAgFA,IAAMmD,kBAAiC;CAAEzC,MAAM;CAAOC,KAAK,CAAA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D,aAAahD,eAAe;EAClDJ,aAAaV,OACTtB,UAAUL,SAAS,QAAQ,CAACK,UAAUH,OAAOmG,SAAS1E,EAAE,IAAItB,UAAUJ,IAAIoG,SAAS1E,EAAE;EACzFW,mBAAmBC,UACflC,UAAUL,SAAS,QACbsG,KAAKC,IAAI,GAAGhE,QAAQlC,UAAUH,OAAOoD,MAAM,IAC3CjD,UAAUJ,IAAIqD;EACxBd,eAAe;GACX,IAAInC,UAAUL,SAAS,OACnB,OAAOK,UAAUJ,IAAIqD,SAAS,IAAI,EAAErD,KAAK,CAAC,GAAGI,UAAUJ,GAAG,EAAE,IAAI;GAEpE,MAAMG,QAA0D,CAAC;GACjE,IAAI2D,OAAOf,WAAWL,KAAAA,GAClBvC,MAAM4C,SAASe,OAAOf;GAE1B,IAAIe,OAAOjC,MAAMa,KAAAA,GACbvC,MAAM0B,IAAIiC,OAAOjC;GAErB,OAAOzB,UAAUH,OAAOoD,SAAS,IAC3B;IAAElD;IAAOF,QAAQ,CAAC,GAAGG,UAAUH,MAAM;GAAE,IACvC,EAAEE,MAAM;EAClB;CACJ;CACA,OAAOM;AACX"}
@@ -1 +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 subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"],"mappings":";;AAcA,SAAgB,oBAAoB,SAAiB,QAAgB;CACjE,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAe,UAAU,SAAS,aAAa,SAAS,CAAC;CAC/D,OAAO;EACH,iBAAiB,OAAO,SAAS,OAAO,QAAQ,OAAO,EAAE;EACzD,UAAU,QAAQ,EAAE,UAAU,UAAU,CAAC,GAAG;GACxC,MAAM,MAAM,GAAG,OAAO,SAAS,WAAW,WAAW,KAAK,IAAI,WAAW,KAAK,OAAO,SAAS;GAC9F,IAAI,SACA,OAAO,QAAQ,aAAa,OAAO,QAAQ,OAAO,IAAI,GAAG;QAEzD,OAAO,QAAQ,UAAU,OAAO,QAAQ,OAAO,IAAI,GAAG;GAE1D,OAAO;EACX;EACA,UAAU,UAAU;GAChB,UAAU,IAAI,QAAQ;GACtB,OAAO,iBAAiB,YAAY,QAAQ;GAC5C,aAAa;IACT,UAAU,OAAO,QAAQ;IACzB,OAAO,oBAAoB,YAAY,QAAQ;GACnD;EACJ;CACJ;AACJ;;AAWA,SAAgB,mBAAmB,gBAAgB,IAAkB;CACjE,MAAM,UAAU,CAAC,aAAa;CAC9B,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAe,UAAU,SAAS,aAAa,SAAS,CAAC;CAC/D,OAAO;EACH;EACA,iBAAiB,QAAQ,GAAG,EAAE,KAAK;EACnC,OAAO;GACH,IAAI,QAAQ,SAAS,GAAG;IACpB,QAAQ,IAAI;IACZ,OAAO;GACX;EACJ;EACA,UAAU,QAAQ,EAAE,UAAU,UAAU,CAAC,GAAG;GACxC,IAAI,SACA,QAAQ,QAAQ,SAAS,KAAK;QAE9B,QAAQ,KAAK,MAAM;GAEvB,OAAO;EACX;EACA,UAAU,UAAU;GAChB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACT,UAAU,OAAO,QAAQ;GAC7B;EACJ;CACJ;AACJ"}
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"}
package/dist/plugins.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import type { ComponentType } from 'react';
2
+ import type { DefinitionTheme, Theme } from '@panneau/protocol';
3
+ import type { CommandSource } from './commands.js';
4
+ /** A theme of `@panneau/ui`, as plain data: what plugins register (decision 0024). */
5
+ export type { Theme };
2
6
  /**
3
7
  * A component provided by a plugin. Its props are defined by the package that renders it (fields,
4
8
  * lists, app), so the registry stores it as given.
@@ -10,14 +14,6 @@ export type Messages = Record<string, string>;
10
14
  export type MessagesLoader = Messages | (() => Promise<Messages | {
11
15
  default: Messages;
12
16
  }>);
13
- /** A theme: design tokens (CSS variables without `--`), with optional dark scheme overrides. */
14
- export interface Theme {
15
- label?: string;
16
- /** Tokens of the light scheme, or of both schemes without `dark`: `{ 'panneau-color-accent': '#05f' }`. */
17
- tokens: Record<string, string>;
18
- /** Tokens that change in the dark scheme. */
19
- dark?: Record<string, string>;
20
- }
21
17
  /** What a plugin adds to Panneau. Every part is keyed by the name the definition uses. */
22
18
  export interface PanneauPlugin {
23
19
  /** Unique id of the plugin. */
@@ -36,13 +32,20 @@ export interface PanneauPlugin {
36
32
  widgets?: Record<string, PluginComponent>;
37
33
  /** Layout node components, for `component` nodes of form layouts. */
38
34
  components?: Record<string, PluginComponent>;
35
+ /**
36
+ * Previews of items, by name, for resources whose `features.preview` is a `component`
37
+ * (`{ "mode": "component", "component": "page" }`). They get `PreviewProps`.
38
+ */
39
+ previews?: Record<string, PluginComponent>;
40
+ /** Commands of the "Go to…" palette, or a function that makes them for the definition. */
41
+ commands?: CommandSource;
39
42
  /** UI messages, by locale. Messages of later plugins override earlier ones. */
40
43
  locales?: Record<string, MessagesLoader>;
41
- /** Themes, by id. */
44
+ /** Themes, by id, that the theme of the definition can extend. */
42
45
  themes?: Record<string, Theme>;
43
46
  }
44
47
  /** The kinds of components a plugin can provide. */
45
- export type PluginComponentKind = 'fields' | 'displays' | 'listLayouts' | 'actions' | 'pages' | 'widgets' | 'components';
48
+ export type PluginComponentKind = 'fields' | 'displays' | 'listLayouts' | 'actions' | 'pages' | 'widgets' | 'components' | 'previews';
46
49
  /** Everything the plugins provide, merged. A later plugin overrides an earlier one. */
47
50
  export interface PluginRegistry {
48
51
  /** The plugins, in order. */
@@ -54,6 +57,9 @@ export interface PluginRegistry {
54
57
  pages: ReadonlyMap<string, PluginComponent>;
55
58
  widgets: ReadonlyMap<string, PluginComponent>;
56
59
  components: ReadonlyMap<string, PluginComponent>;
60
+ previews: ReadonlyMap<string, PluginComponent>;
61
+ /** The commands of the plugins, in plugin order: `getCommands()` makes them. */
62
+ commands: readonly CommandSource[];
57
63
  /** Message loaders of each locale, in plugin order. */
58
64
  locales: ReadonlyMap<string, readonly MessagesLoader[]>;
59
65
  themes: ReadonlyMap<string, Theme>;
@@ -70,4 +76,10 @@ export declare function createPluginRegistry(plugins: readonly PanneauPlugin[]):
70
76
  * regional locale (`fr-CA`) falls back to its language (`fr`) for missing messages.
71
77
  */
72
78
  export declare function loadMessages(registry: PluginRegistry, locale: string): Promise<Messages>;
79
+ /**
80
+ * The theme of the admin: the themes of plugins that the definition's theme extends, in order, then
81
+ * the definition's own tokens, tones and variants. An id no plugin registers is skipped, with a
82
+ * warning.
83
+ */
84
+ export declare function resolveTheme(theme: DefinitionTheme | undefined, themes: ReadonlyMap<string, Theme>): Theme;
73
85
  //# sourceMappingURL=plugins.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAE3C;;;GAGG;AAEH,MAAM,MAAM,eAAe,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;AAEjD,oDAAoD;AACpD,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE9C,kFAAkF;AAClF,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,CAAC,MAAM,OAAO,CAAC,QAAQ,GAAG;IAAE,OAAO,EAAE,QAAQ,CAAA;CAAE,CAAC,CAAC,CAAC;AAE1F,gGAAgG;AAChG,MAAM,WAAW,KAAK;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2GAA2G;IAC3G,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,0FAA0F;AAC1F,MAAM,WAAW,aAAa;IAC1B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,C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E,eAAe,CAAC,CAAC;IAC/C,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAClD,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC9C,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC5C,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC9C,UAAU,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACjD,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC/C,gFAAgF;IAChF,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IACnC,uDAAuD;IACvD,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,CAAC,CAAC;IACxD,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;CACtC;AAED,6EAA6E;AAC7E,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAEjE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,SAAS,aAAa,EAAE,GAAG,cAAc,CA6BtF;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkB9F;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CACxB,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,GACnC,KAAK,CAWP"}
package/dist/plugins.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { mergeThemes } from "@panneau/protocol/runtime";
1
2
  //#region src/plugins.ts
2
3
  var COMPONENT_KINDS = [
3
4
  "fields",
@@ -6,7 +7,8 @@ var COMPONENT_KINDS = [
6
7
  "actions",
7
8
  "pages",
8
9
  "widgets",
9
- "components"
10
+ "components",
11
+ "previews"
10
12
  ];
11
13
  /** Declares a plugin. It returns the plugin as is, with its type checked. */
12
14
  function definePlugin(plugin) {
@@ -31,7 +33,8 @@ function createPluginRegistry(plugins) {
31
33
  plugins: [...plugins],
32
34
  ...components,
33
35
  locales,
34
- themes: new Map(plugins.flatMap((plugin) => Object.entries(plugin.themes ?? {})))
36
+ themes: new Map(plugins.flatMap((plugin) => Object.entries(plugin.themes ?? {}))),
37
+ commands: plugins.flatMap((plugin) => plugin.commands !== void 0 ? [plugin.commands] : [])
35
38
  };
36
39
  }
37
40
  /**
@@ -48,7 +51,24 @@ async function loadMessages(registry, locale) {
48
51
  }));
49
52
  return Object.assign({}, ...loaded);
50
53
  }
54
+ /**
55
+ * The theme of the admin: the themes of plugins that the definition's theme extends, in order, then
56
+ * the definition's own tokens, tones and variants. An id no plugin registers is skipped, with a
57
+ * warning.
58
+ */
59
+ function resolveTheme(theme, themes) {
60
+ const { colorScheme: _colorScheme, extends: ids, ...own } = theme ?? {};
61
+ const extended = (typeof ids === "string" ? [ids] : ids ?? []).flatMap((id) => {
62
+ const found = themes.get(id);
63
+ if (found === void 0) {
64
+ console.warn(`[panneau] No plugin registers the theme "${id}".`);
65
+ return [];
66
+ }
67
+ return [found];
68
+ });
69
+ return mergeThemes(...extended, own);
70
+ }
51
71
  //#endregion
52
- export { createPluginRegistry, definePlugin, loadMessages };
72
+ export { createPluginRegistry, definePlugin, loadMessages, resolveTheme };
53
73
 
54
74
  //# sourceMappingURL=plugins.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.js","names":[],"sources":["../src/plugins.ts"],"sourcesContent":["import type { ComponentType } from 'react';\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/** A theme: design tokens (CSS variables without `--`), with optional dark scheme overrides. */\nexport interface Theme {\n label?: string;\n /** Tokens of the light scheme, or of both schemes without `dark`: `{ 'panneau-color-accent': '#05f' }`. */\n tokens: Record<string, string>;\n /** Tokens that change in the dark scheme. */\n dark?: Record<string, string>;\n}\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 /** UI messages, by locale. Messages of later plugins override earlier ones. */\n locales?: Record<string, MessagesLoader>;\n /** Themes, by id. */\n themes?: Record<string, Theme>;\n}\n\n/** The kinds of components a plugin can provide. */\nexport type PluginComponentKind =\n 'fields' | 'displays' | 'listLayouts' | 'actions' | 'pages' | 'widgets' | 'components';\n\nconst COMPONENT_KINDS: PluginComponentKind[] = [\n 'fields',\n 'displays',\n 'listLayouts',\n 'actions',\n 'pages',\n 'widgets',\n 'components',\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 /** 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 };\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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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"}
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,OAAOM,QAAQd,OAAOW,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3E,CACL;CACA,MAAMnB,0BAAU,IAAIoB,IAA8B;CAClDf,QAAQO,SAASJ,WACbQ,OAAOM,QAAQd,OAAOR,WAAW,CAAC,CAAC,CAAC,CAACY,SAAS,CAACW,QAAQC,YAAY;EAC/DxB,QAAQyB,IAAIF,QAAQ,CAAC,GAAIvB,QAAQ0B,IAAIH,MAAM,KAAK,CAAA,GAAKC,MAAM,CAAC;CAChE,CAAC,CACL;CACA,OAAO;EACHnB,SAAS,CAAC,GAAGA,OAAO;EACpB,GAAGR;EACHG;EACAC,QAAQ,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14 @@
1
+ import type { Item, Resource } from '@panneau/protocol';
2
+ /**
3
+ * Props of a preview component (the `previews` of a plugin), for a resource whose
4
+ * `features.preview` is `{ "mode": "component", "component": "<name>" }`. It renders the item as
5
+ * the site would, or anything richer than its values: blocks, partials, charts.
6
+ */
7
+ export interface PreviewProps {
8
+ /** The item: as saved, or with the unsaved values of a form. */
9
+ item: Item;
10
+ resource: Resource;
11
+ /** The locale of the content to show, for localized values. */
12
+ locale: string;
13
+ }
14
+ //# sourceMappingURL=preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAExD;;;;GAIG;AACH,MAAM,WAAW,YAAY;IACzB,gEAAgE;IAChE,IAAI,EAAE,IAAI,CAAC;IACX,QAAQ,EAAE,QAAQ,CAAC;IACnB,+DAA+D;IAC/D,MAAM,EAAE,MAAM,CAAC;CAClB"}
@@ -0,0 +1,34 @@
1
+ import { type ReactNode } from 'react';
2
+ /** Asks whether the user may leave: resolves `true` to leave, `false` to stay. */
3
+ export type LeaveGuard = () => Promise<boolean>;
4
+ /**
5
+ * What guards in-app navigation: forms with unsaved changes add a guard while they are dirty,
6
+ * and the router asks them before it leaves the page.
7
+ */
8
+ export interface LeaveGuards {
9
+ /** Adds a guard. Returns a function that removes it. */
10
+ add(guard: LeaveGuard): () => void;
11
+ /** Whether a guard would ask: leaving now needs a confirmation. */
12
+ isBlocking(): boolean;
13
+ /** Asks each guard in turn. Resolves `true` when every one lets the user leave. */
14
+ confirmLeave(): Promise<boolean>;
15
+ }
16
+ /** Creates the guards of an app, for `LeaveGuardsProvider`. */
17
+ export declare function createLeaveGuards(): LeaveGuards;
18
+ export interface LeaveGuardsProviderProps {
19
+ guards: LeaveGuards;
20
+ children?: ReactNode;
21
+ }
22
+ /**
23
+ * Gives the guards of the app's router to the forms below it, so that leaving a page with unsaved
24
+ * changes asks first. Without it, forms only guard closing and reloading the page.
25
+ */
26
+ export declare function LeaveGuardsProvider({ guards, children }: LeaveGuardsProviderProps): import("react").JSX.Element;
27
+ /** The guards of the closest `LeaveGuardsProvider`, or `null`. */
28
+ export declare function useLeaveGuards(): LeaveGuards | null;
29
+ /**
30
+ * Adds `guard` to the guards of the closest `LeaveGuardsProvider` while `active` is true, such
31
+ * as while a form has unsaved changes. The latest `guard` is the one asked.
32
+ */
33
+ export declare function useLeaveGuard(active: boolean, guard: LeaveGuard): void;
34
+ //# sourceMappingURL=leaveGuards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leaveGuards.d.ts","sourceRoot":"","sources":["../../src/react/leaveGuards.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAyC,MAAM,OAAO,CAAC;AAE9E,kFAAkF;AAClF,MAAM,MAAM,UAAU,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;AAEhD;;;GAGG;AACH,MAAM,WAAW,WAAW;IACxB,wDAAwD;IACxD,GAAG,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,IAAI,CAAC;IACnC,mEAAmE;IACnE,UAAU,IAAI,OAAO,CAAC;IACtB,mFAAmF;IACnF,YAAY,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CACpC;AAED,+DAA+D;AAC/D,wBAAgB,iBAAiB,IAAI,WAAW,CAmB/C;AAID,MAAM,WAAW,wBAAwB;IACrC,MAAM,EAAE,WAAW,CAAC;IACpB,QAAQ,CAAC,EAAE,SAAS,CAAC;CACxB;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,wBAAwB,+BAEjF;AAED,kEAAkE;AAClE,wBAAgB,cAAc,IAAI,WAAW,GAAG,IAAI,CAEnD;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI,CAYtE"}
@@ -0,0 +1,84 @@
1
+ import { c } from "react/compiler-runtime";
2
+ import { createContext, use, useEffect, useRef } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ //#region src/react/leaveGuards.tsx
5
+ /** Creates the guards of an app, for `LeaveGuardsProvider`. */
6
+ function createLeaveGuards() {
7
+ const guards = /* @__PURE__ */ new Set();
8
+ return {
9
+ add(guard) {
10
+ guards.add(guard);
11
+ return () => {
12
+ guards.delete(guard);
13
+ };
14
+ },
15
+ isBlocking: () => guards.size > 0,
16
+ async confirmLeave() {
17
+ for (const guard of [...guards]) if (!await guard()) return false;
18
+ return true;
19
+ }
20
+ };
21
+ }
22
+ var LeaveGuardsContext = createContext(null);
23
+ /**
24
+ * Gives the guards of the app's router to the forms below it, so that leaving a page with unsaved
25
+ * changes asks first. Without it, forms only guard closing and reloading the page.
26
+ */
27
+ function LeaveGuardsProvider(t0) {
28
+ const $ = c(3);
29
+ const { guards, children } = t0;
30
+ let t1;
31
+ if ($[0] !== children || $[1] !== guards) {
32
+ t1 = /* @__PURE__ */ jsx(LeaveGuardsContext, {
33
+ value: guards,
34
+ children
35
+ });
36
+ $[0] = children;
37
+ $[1] = guards;
38
+ $[2] = t1;
39
+ } else t1 = $[2];
40
+ return t1;
41
+ }
42
+ /** The guards of the closest `LeaveGuardsProvider`, or `null`. */
43
+ function useLeaveGuards() {
44
+ return use(LeaveGuardsContext);
45
+ }
46
+ /**
47
+ * Adds `guard` to the guards of the closest `LeaveGuardsProvider` while `active` is true, such
48
+ * as while a form has unsaved changes. The latest `guard` is the one asked.
49
+ */
50
+ function useLeaveGuard(active, guard) {
51
+ const $ = c(6);
52
+ const guards = useLeaveGuards();
53
+ const latest = useRef(guard);
54
+ let t0;
55
+ if ($[0] !== guard) {
56
+ t0 = () => {
57
+ latest.current = guard;
58
+ };
59
+ $[0] = guard;
60
+ $[1] = t0;
61
+ } else t0 = $[1];
62
+ useEffect(t0);
63
+ let t1;
64
+ let t2;
65
+ if ($[2] !== active || $[3] !== guards) {
66
+ t1 = () => {
67
+ if (!active || guards === null) return;
68
+ return guards.add(() => latest.current());
69
+ };
70
+ t2 = [active, guards];
71
+ $[2] = active;
72
+ $[3] = guards;
73
+ $[4] = t1;
74
+ $[5] = t2;
75
+ } else {
76
+ t1 = $[4];
77
+ t2 = $[5];
78
+ }
79
+ useEffect(t1, t2);
80
+ }
81
+ //#endregion
82
+ export { LeaveGuardsProvider, createLeaveGuards, useLeaveGuard, useLeaveGuards };
83
+
84
+ //# sourceMappingURL=leaveGuards.js.map
@@ -0,0 +1 @@
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;AACJ;AAEA,IAAMQ,qBAAqBhB,cAAkC,IAAI;;;;;AAWjE,SAAOmB,oBAAAC,IAAA;CAAA,MAAAC,IAAAC,EAAA,CAAA;CAA6B,MAAA,EAAAV,QAAAM,aAAAE;CAA8C,IAAAG;CAAA,IAAAF,EAAA,OAAAH,YAAAG,EAAA,OAAAT,QAAA;EACvEW,KAAA,oBAAC,oBAAD;GAA2BX,OAAAA;GAASM;EAAjB,CAAA;EAA+CG,EAAA,KAAAH;EAAAG,EAAA,KAAAT;EAAAS,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAAlEE;AAAkE;;AAI7E,SAAgBC,iBAAqC;CACjD,OAAOvB,IAAIe,kBAAkB;AACjC;;;;;AAMA,SAAOS,cAAAC,QAAAlB,OAAA;CAAA,MAAAa,IAAAC,EAAA,CAAA;CACH,MAAAV,SAAeY,eAAe;CAC9B,MAAAG,SAAexB,OAAOK,KAAK;CAAE,IAAAY;CAAA,IAAAC,EAAA,OAAAb,OAAA;EACnBY,WAAA;GACNO,OAAMC,UAAWpB;EAAH;EACjBa,EAAA,KAAAb;EAAAa,EAAA,KAAAD;CAAA,OAAAA,KAAAC,EAAA;CAFDnB,UAAUkB,EAET;CAAC,IAAAG;CAAA,IAAAM;CAAA,IAAAR,EAAA,OAAAK,UAAAL,EAAA,OAAAT,QAAA;EACQW,WAAA;GACN,IAAI,CAACG,UAAUd,WAAW,MAAI;GAE7B,OACMA,OAAML,UAAWoB,OAAMC,QAAS,CAAC;EAAC;EAC1CC,KAAA,CAACH,QAAQd,MAAM;EAACS,EAAA,KAAAK;EAAAL,EAAA,KAAAT;EAAAS,EAAA,KAAAE;EAAAF,EAAA,KAAAQ;CAAA,OAAA;EAAAN,KAAAF,EAAA;EAAAQ,KAAAR,EAAA;CAAA;CALnBnB,UAAUqB,IAKPM,EAAgB;AAAC"}
@@ -1,9 +1,9 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import type { Definition } from '@panneau/protocol';
3
- import { type ResolveFormOptions } from '../definition/form';
4
- import { type ResolvedResource } from '../definition/resource';
5
- import type { Router } from '../list/router';
6
- import { type PanneauPlugin, type PluginRegistry } from '../plugins';
3
+ import { type ResolveFormOptions } from '../definition/form.js';
4
+ import { type ResolvedResource } from '../definition/resource.js';
5
+ import type { Router } from '../list/router.js';
6
+ import { type PanneauPlugin, type PluginRegistry } from '../plugins.js';
7
7
  /** What `PanneauProvider` gives to the hooks below it. */
8
8
  export interface PanneauContextValue {
9
9
  plugins: PluginRegistry;
@@ -9,7 +9,9 @@ var PanneauContext = createContext(null);
9
9
  * Provides plugins, the definition and the router to the hooks of `@panneau/core`. 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 = {