@marktiderman/genesis-core 2.14.0 → 2.15.0

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 (92) hide show
  1. package/dist/aggregate-y-qqJioF.d.ts +34 -0
  2. package/dist/{chunk-7PUFVNPB.js → chunk-2IGAUXYH.js} +5 -3
  3. package/dist/chunk-2IGAUXYH.js.map +1 -0
  4. package/dist/{chunk-KA3BUJ4H.js → chunk-42NVJJTT.js} +3 -3
  5. package/dist/{chunk-KA3BUJ4H.js.map → chunk-42NVJJTT.js.map} +1 -1
  6. package/dist/{chunk-JN47G4UE.js → chunk-7EFTWOMA.js} +56 -2
  7. package/dist/chunk-7EFTWOMA.js.map +1 -0
  8. package/dist/{chunk-S2VYJWB4.js → chunk-E3K2A3PK.js} +3 -3
  9. package/dist/{chunk-S2VYJWB4.js.map → chunk-E3K2A3PK.js.map} +1 -1
  10. package/dist/{chunk-SDAJSJNN.js → chunk-IYGVJFCV.js} +3 -3
  11. package/dist/{chunk-SDAJSJNN.js.map → chunk-IYGVJFCV.js.map} +1 -1
  12. package/dist/chunk-J54XXKQD.js +104 -0
  13. package/dist/chunk-J54XXKQD.js.map +1 -0
  14. package/dist/{chunk-OYDJGPDY.js → chunk-JFHRSG6G.js} +5 -5
  15. package/dist/{chunk-OYDJGPDY.js.map → chunk-JFHRSG6G.js.map} +1 -1
  16. package/dist/{chunk-UHOMTFBD.js → chunk-JTRRAVR4.js} +55 -3
  17. package/dist/chunk-JTRRAVR4.js.map +1 -0
  18. package/dist/{chunk-KV2HW4G4.js → chunk-LB6FMQQM.js} +11 -3
  19. package/dist/chunk-LB6FMQQM.js.map +1 -0
  20. package/dist/{chunk-G6GQPXQS.js → chunk-M5IX7C6U.js} +5 -5
  21. package/dist/{chunk-G6GQPXQS.js.map → chunk-M5IX7C6U.js.map} +1 -1
  22. package/dist/{chunk-AHFIS42U.js → chunk-NZP7YQHS.js} +5 -5
  23. package/dist/{chunk-AHFIS42U.js.map → chunk-NZP7YQHS.js.map} +1 -1
  24. package/dist/{chunk-DFABPMEQ.js → chunk-POUI7GAI.js} +5 -5
  25. package/dist/{chunk-DFABPMEQ.js.map → chunk-POUI7GAI.js.map} +1 -1
  26. package/dist/{chunk-NE2D74BP.js → chunk-QGWQ6LK3.js} +5 -5
  27. package/dist/{chunk-NE2D74BP.js.map → chunk-QGWQ6LK3.js.map} +1 -1
  28. package/dist/{chunk-2K4747KX.js → chunk-R3YXYVWF.js} +7 -2
  29. package/dist/chunk-R3YXYVWF.js.map +1 -0
  30. package/dist/{chunk-RFHUOXZC.js → chunk-SOO54YYY.js} +4 -4
  31. package/dist/{chunk-RFHUOXZC.js.map → chunk-SOO54YYY.js.map} +1 -1
  32. package/dist/{chunk-P3FHXRS2.js → chunk-TKK7D2ZT.js} +6 -6
  33. package/dist/{chunk-P3FHXRS2.js.map → chunk-TKK7D2ZT.js.map} +1 -1
  34. package/dist/{chunk-WDPM5TBO.js → chunk-UDSTWXXZ.js} +3 -3
  35. package/dist/{chunk-WDPM5TBO.js.map → chunk-UDSTWXXZ.js.map} +1 -1
  36. package/dist/chunk-XPBS5YE4.js +24 -0
  37. package/dist/chunk-XPBS5YE4.js.map +1 -0
  38. package/dist/csv.d.ts +1 -1
  39. package/dist/form-types.d.ts +1 -1
  40. package/dist/hooks/index.d.ts +4 -2
  41. package/dist/hooks/index.js +16 -14
  42. package/dist/hooks/mutation-mode.d.ts +1 -1
  43. package/dist/hooks/mutation-mode.js +5 -4
  44. package/dist/hooks/related-keys.d.ts +1 -1
  45. package/dist/hooks/use-aggregate.d.ts +25 -0
  46. package/dist/hooks/use-aggregate.js +10 -0
  47. package/dist/hooks/use-aggregate.js.map +1 -0
  48. package/dist/hooks/use-capabilities.d.ts +1 -1
  49. package/dist/hooks/use-capabilities.js +4 -2
  50. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  51. package/dist/hooks/use-infinite-resource.js +6 -4
  52. package/dist/hooks/use-link-options.d.ts +1 -1
  53. package/dist/hooks/use-link-options.js +8 -6
  54. package/dist/hooks/use-live.d.ts +1 -1
  55. package/dist/hooks/use-live.js +4 -2
  56. package/dist/hooks/use-one.d.ts +1 -1
  57. package/dist/hooks/use-one.js +6 -4
  58. package/dist/hooks/use-persisted-ui-state.js +4 -2
  59. package/dist/hooks/use-relation-label.d.ts +1 -1
  60. package/dist/hooks/use-relation-label.js +4 -2
  61. package/dist/hooks/use-resource-form.d.ts +1 -1
  62. package/dist/hooks/use-resource-form.js +8 -7
  63. package/dist/hooks/use-resource.d.ts +1 -1
  64. package/dist/hooks/use-resource.js +7 -6
  65. package/dist/hooks/use-write.d.ts +1 -1
  66. package/dist/index.d.ts +110 -6
  67. package/dist/index.js +125 -17
  68. package/dist/index.js.map +1 -1
  69. package/dist/navigation.d.ts +77 -1
  70. package/dist/navigation.js +32 -2
  71. package/dist/navigation.js.map +1 -1
  72. package/dist/provider/index.d.ts +12 -4
  73. package/dist/provider/index.js +3 -2
  74. package/dist/resource-view/index.d.ts +456 -166
  75. package/dist/resource-view/index.js +251 -5
  76. package/dist/resource-view/index.js.map +1 -1
  77. package/dist/schema/index.d.ts +3 -3
  78. package/dist/schema/index.js +1 -2
  79. package/dist/testing/index.d.ts +2 -2
  80. package/dist/{types-CtJxwoyv.d.ts → types-D4Bi_Iq8.d.ts} +76 -3
  81. package/dist/workspaces-BKhloJPK.d.ts +255 -0
  82. package/dist/workspaces.d.ts +2 -160
  83. package/dist/workspaces.js +1 -1
  84. package/dist/{write-outcome-Goy1v39G.d.ts → write-outcome-CHPT7Slm.d.ts} +1 -1
  85. package/package.json +1 -1
  86. package/dist/chunk-2K4747KX.js.map +0 -1
  87. package/dist/chunk-7PUFVNPB.js.map +0 -1
  88. package/dist/chunk-JN47G4UE.js.map +0 -1
  89. package/dist/chunk-KV2HW4G4.js.map +0 -1
  90. package/dist/chunk-UHOMTFBD.js.map +0 -1
  91. package/dist/chunk-YDMKMNDS.js +0 -8
  92. package/dist/chunk-YDMKMNDS.js.map +0 -1
@@ -1,11 +1,12 @@
1
- export { useResource } from '../chunk-P3FHXRS2.js';
1
+ export { useResource } from '../chunk-TKK7D2ZT.js';
2
2
  import '../chunk-7NUL32W7.js';
3
- import '../chunk-S2VYJWB4.js';
4
- import '../chunk-RFHUOXZC.js';
5
- import '../chunk-KA3BUJ4H.js';
3
+ import '../chunk-E3K2A3PK.js';
4
+ import '../chunk-SOO54YYY.js';
5
+ import '../chunk-42NVJJTT.js';
6
6
  import '../chunk-AJGVLF37.js';
7
- import '../chunk-7PUFVNPB.js';
8
- import '../chunk-2K4747KX.js';
7
+ import '../chunk-2IGAUXYH.js';
8
+ import '../chunk-R3YXYVWF.js';
9
+ import '../chunk-J54XXKQD.js';
9
10
  import '../chunk-4PTQYT5J.js';
10
11
  import '../chunk-AUVKRXRC.js';
11
12
  import '../chunk-NOPS5EIH.js';
@@ -1,5 +1,5 @@
1
1
  import { QueryClient, MutationOptions } from '@tanstack/react-query';
2
- import { I as InvalidationKey } from '../types-CtJxwoyv.js';
2
+ import { I as InvalidationKey } from '../types-D4Bi_Iq8.js';
3
3
 
4
4
  declare const WRITE_FAILED = "That didn't work. Try again.";
5
5
  interface UseWriteOptions<A, R> {
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- import { L as ListParams, b as Identifier } from './types-CtJxwoyv.js';
2
- export { A as ArrayFilter, c as AuditEntry, B as BaseRecord, d as BulkChange, e as BulkResult, C as CountMode, f as CreateParams, g as CreateResult, D as DataProvider, h as DataRow, i as DeleteParams, j as DeleteResult, k as FieldPermissions, l as FieldReference, F as FieldSchema, m as FieldType, n as FilterOperator, a as FilterParam, G as GetManyParams, o as GetManyResult, p as GetOneParams, q as GetOneResult, H as HistoryParams, r as ImportParams, I as InvalidationKey, s as ListResult, N as NullFilter, P as PaginationParam, t as ProviderCapabilities, R as RangeFilter, u as RecordComment, v as ResourceAccess, w as ResourceChangeEvent, x as ResourceContract, y as ResourceFormFieldDef, z as ResourceRelation, E as ResourceSchema, J as ResourceSummary, K as RowAction, M as RowFailure, O as RowOf, Q as ScalarFilter, T as SelectOption, S as SortParam, U as StorageType, V as SubscribeParams, X as UpdateParams, Y as UpdateResult, Z as VersionField, m as WidgetHint, W as WriteEvent, _ as defineResource } from './types-CtJxwoyv.js';
3
- export { D as DataWriteError, a as DataWriteErrorOptions, N as NO_ROWS_MATCHED, W as WriteOutcome, i as isDataWriteError } from './write-outcome-Goy1v39G.js';
1
+ import { c as ListParams, d as Identifier } from './types-D4Bi_Iq8.js';
2
+ export { i as AggregateMetric, A as AggregateParams, b as AggregateResult, k as ArrayFilter, h as AuditEntry, B as BaseRecord, l as BulkChange, m as BulkResult, C as ControlHint, n as CountMode, o as CreateParams, p as CreateResult, D as DataProvider, j as DataRow, q as DeleteParams, r as DeleteResult, s as FieldPermissions, e as FieldReference, F as FieldSchema, t as FieldType, u as FilterOperator, a as FilterParam, G as GetManyParams, v as GetManyResult, w as GetOneParams, x as GetOneResult, H as HistoryParams, y as ImportParams, I as InvalidationKey, L as ListResult, N as NullFilter, z as PaginationParam, P as ProviderCapabilities, E as RangeFilter, J as RecordComment, K as ResourceAccess, g as ResourceChangeEvent, M as ResourceContract, R as ResourceFormFieldDef, O as ResourceRelation, Q as ResourceSchema, T as ResourceSummary, U as RowAction, V as RowFailure, X as RowOf, Y as ScalarFilter, Z as SelectOption, S as SortParam, _ as StorageType, f as SubscribeParams, $ as UpdateParams, a0 as UpdateResult, a1 as VersionField, a2 as WidgetHint, W as WriteEvent, a3 as defineResource, a4 as fieldControl } from './types-D4Bi_Iq8.js';
3
+ export { R as ResolveAggregateOptions, a as aggregateProblems, r as resolveAggregate, t as toAggregateValues } from './aggregate-y-qqJioF.js';
4
+ export { D as DataWriteError, a as DataWriteErrorOptions, N as NO_ROWS_MATCHED, W as WriteOutcome, i as isDataWriteError } from './write-outcome-CHPT7Slm.js';
4
5
  export { CallRpcOptions, CreateOrAdoptOptions, CreateOrAdoptResult, DEFAULT_RPC_MESSAGES, DataProviderRoot, DataProviderRootProps, GenesisProvider, GenesisProviderProps, MockProviderOptions, PostgrestFieldErrors, RPC_FAILED, RpcClient, SupabaseClient, SupabaseClientInput, SupabaseProviderOptions, SupabaseRealtimeChannel, SupabaseRealtimePayload, SupabaseResourceConfig, SupabaseUpdateContext, SupabaseWriteContext, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode } from './provider/index.js';
5
6
  export { D as DataReadError, a as DataReadErrorOptions, R as ReadOutcome, i as isDataReadError, r as readFailureMessage } from './read-outcome-BnboMYOV.js';
6
7
  export { S as StorageAdapter } from './types-DKcxHXxq.js';
7
8
  export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './storage/index.js';
8
9
  export { UpdateOptions, UseResourceOptions, UseResourceReturn, useResource } from './hooks/use-resource.js';
9
10
  export { UseOneOptions, useOne } from './hooks/use-one.js';
11
+ export { UseAggregateOptions, useAggregate } from './hooks/use-aggregate.js';
10
12
  export { UseRelationLabelOptions, loadRelationLabel, relationNamingField, useRelationLabel } from './hooks/use-relation-label.js';
11
13
  export { LinkOption, LinkTarget, UseLinkOptionsOptions, UseLinkOptionsReturn, useLinkOptions } from './hooks/use-link-options.js';
12
14
  export { InfinitePageParam, UseInfiniteResourceOptions, UseInfiniteResourceReturn, useInfiniteResource } from './hooks/use-infinite-resource.js';
@@ -28,10 +30,12 @@ import { Query } from '@tanstack/react-query';
28
30
  export { isSafeUrl, normalizeLinkUrl } from './urls.js';
29
31
  export { ClassifiedError, ClassifyErrorOptions, ErrorKind, ErrorMessages, ErrorReportContext, ErrorReporter, classifyError, defaultErrorReporter, errorMessages, getErrorReporter, reportError, setErrorReporter } from './errors.js';
30
32
  export { titleCase } from './utils.js';
31
- import 'react';
33
+ import { A as AppearancePreferenceValues, R as ResolvedAppearancePreferences, a as AppearancePreferenceLayers, b as Appearance, D as Density } from './workspaces-BKhloJPK.js';
34
+ export { c as APPEARANCES, d as AppearancePreferenceSource, e as DENSITIES, G as GENESIS_APPEARANCE_DEFAULTS, i as isAppearance, f as isDensity, r as resolveAppearancePreferences, t as toAppearancePreferenceValues } from './workspaces-BKhloJPK.js';
35
+ import * as react from 'react';
36
+ import { ReactNode } from 'react';
32
37
  import './types-CsKSAKqs.js';
33
38
  import './dates.js';
34
- import './workspaces.js';
35
39
  import 'react-hook-form';
36
40
 
37
41
  /** Who and when a key is for. `viewer` is required; null means signed out. */
@@ -102,6 +106,106 @@ declare function resourceKeys(resource: string): {
102
106
  detailsOf: (id: Identifier | null | undefined) => readonly [string, "detail", Identifier | null | undefined];
103
107
  detail: (id: Identifier | null | undefined, select?: string) => readonly [string, "detail", Identifier | null | undefined, string | undefined];
104
108
  infinite: (params: unknown) => readonly [string, "infinite", unknown];
109
+ /** Totals over a list (`useAggregate`): any write to the resource makes them stale. */
110
+ aggregate: (params: unknown) => readonly [string, "aggregate", unknown];
105
111
  };
106
112
 
107
- export { Identifier, type KeyFilter, type KeyScope, ListParams, type QueryKeys, type ScopedKey, defineQueryKeys, resourceKeys };
113
+ /**
114
+ * Where a person's appearance preferences are kept: an adapter an app backs with its own server
115
+ * table (a `profiles` row, say), so the choice follows the person. `read` may be async; return
116
+ * null when the person has chosen nothing. `subscribe` (optional) reports a change made elsewhere.
117
+ *
118
+ * @stability Beta
119
+ */
120
+ interface AppearancePreferencesStore {
121
+ read(): AppearancePreferenceValues | null | undefined | Promise<AppearancePreferenceValues | null | undefined>;
122
+ write(values: AppearancePreferenceValues): void | Promise<void>;
123
+ subscribe?(onChange: (values: AppearancePreferenceValues | null) => void): () => void;
124
+ }
125
+ /** What `defineAppearancePreferences` accepts. */
126
+ interface AppearancePreferencesDefinition {
127
+ /** Where the person's choice is kept beyond this device. Unset: the device only. */
128
+ store?: AppearancePreferencesStore;
129
+ /** The device copy's storage key (`useStorage()`). Default `genesis-appearance`. */
130
+ storageKey?: string;
131
+ /** Values the app fixes: nobody below can change them. */
132
+ lock?: AppearancePreferenceValues;
133
+ }
134
+ /** A defined appearance-preferences setup. */
135
+ interface AppearancePreferences {
136
+ readonly store?: AppearancePreferencesStore;
137
+ readonly storageKey: string;
138
+ readonly lock: Readonly<AppearancePreferenceValues>;
139
+ }
140
+ /**
141
+ * Declare where a person's appearance and density are kept and what the app locks. Checks the
142
+ * lock and returns it frozen; throws on a value that isn't an appearance or a density.
143
+ *
144
+ * ```ts
145
+ * export const appearance = defineAppearancePreferences({
146
+ * store: {
147
+ * read: () => api.myPreferences(), // { appearance: "dark", density: "compact" }
148
+ * write: (values) => api.saveMyPreferences(values),
149
+ * },
150
+ * lock: { density: "comfortable" },
151
+ * });
152
+ * ```
153
+ *
154
+ * @stability Beta
155
+ */
156
+ declare function defineAppearancePreferences(definition?: AppearancePreferencesDefinition): AppearancePreferences;
157
+ /** What `useAppearancePreferences` returns. */
158
+ interface UseAppearancePreferencesReturn extends ResolvedAppearancePreferences {
159
+ /** The person's own choice (the store's, else this device's), before the order is applied. */
160
+ person: AppearancePreferenceValues;
161
+ /** Which values the app has locked. */
162
+ locked: {
163
+ appearance: boolean;
164
+ density: boolean;
165
+ };
166
+ /**
167
+ * Every layer as given, for a component with a default of its own to put in the order
168
+ * (`AppShell` puts its `options.density` under the theme's).
169
+ */
170
+ layers: AppearancePreferenceLayers;
171
+ /** False until the store's first read has answered. */
172
+ ready: boolean;
173
+ /** Save the person's appearance (`undefined` clears it back to the defaults). Ignored when locked. */
174
+ setAppearance(appearance: Appearance | undefined): void;
175
+ /** Save the person's density (`undefined` clears it). Ignored when locked. */
176
+ setDensity(density: Density | undefined): void;
177
+ }
178
+ interface AppearancePreferencesProviderProps {
179
+ /** From `defineAppearancePreferences`. Default: this device only, nothing locked. */
180
+ preferences?: AppearancePreferences;
181
+ /** The active organization's defaults (`resolveWorkspaceAppearance(workspace)`). */
182
+ organization?: AppearancePreferenceValues | undefined;
183
+ /** The app theme's defaults. */
184
+ theme?: AppearancePreferenceValues | undefined;
185
+ children: ReactNode;
186
+ }
187
+ /**
188
+ * Serves a person's appearance and density to the tree, resolved in the written order. Reads the
189
+ * store once on mount (and on its `subscribe`), keeps a copy on the device, and writes both when
190
+ * the person changes a value.
191
+ *
192
+ * @stability Beta
193
+ */
194
+ declare function AppearancePreferencesProvider({ preferences, organization, theme, children }: AppearancePreferencesProviderProps): react.JSX.Element;
195
+ /**
196
+ * The person's appearance and density, resolved, with setters. Throws outside an
197
+ * `AppearancePreferencesProvider`; a component that works with or without one reads
198
+ * `useOptionalAppearancePreferences`.
199
+ *
200
+ * @stability Beta
201
+ */
202
+ declare function useAppearancePreferences(): UseAppearancePreferencesReturn;
203
+ /**
204
+ * Like `useAppearancePreferences`, but null outside a provider: for a component (a shell, a
205
+ * theme provider) that keeps its own behaviour when an app hasn't set preferences up.
206
+ *
207
+ * @stability Beta
208
+ */
209
+ declare function useOptionalAppearancePreferences(): UseAppearancePreferencesReturn | null;
210
+
211
+ export { Appearance, AppearancePreferenceLayers, AppearancePreferenceValues, type AppearancePreferences, type AppearancePreferencesDefinition, AppearancePreferencesProvider, type AppearancePreferencesProviderProps, type AppearancePreferencesStore, Density, Identifier, type KeyFilter, type KeyScope, ListParams, type QueryKeys, ResolvedAppearancePreferences, type ScopedKey, type UseAppearancePreferencesReturn, defineAppearancePreferences, defineQueryKeys, resourceKeys, useAppearancePreferences, useOptionalAppearancePreferences };
package/dist/index.js CHANGED
@@ -1,38 +1,146 @@
1
- export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider } from './chunk-JN47G4UE.js';
2
- export { defineResource } from './chunk-YDMKMNDS.js';
3
- export { decodeRecordKey, encodeRecordKey, keyFields } from './chunk-KV2HW4G4.js';
1
+ export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider } from './chunk-7EFTWOMA.js';
2
+ export { decodeRecordKey, defineResource, encodeRecordKey, fieldControl, keyFields } from './chunk-LB6FMQQM.js';
4
3
  import './chunk-XCX2TRBL.js';
5
- export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-AHFIS42U.js';
4
+ export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-NZP7YQHS.js';
6
5
  export { NO_VIEWER } from './chunk-OZYF55E3.js';
7
- export { usePersistedUiState } from './chunk-SDAJSJNN.js';
8
- export { blankValues, buildArrayItemDefaults, useResourceForm } from './chunk-OYDJGPDY.js';
6
+ import { usePersistedUiState } from './chunk-IYGVJFCV.js';
7
+ export { usePersistedUiState } from './chunk-IYGVJFCV.js';
8
+ export { blankValues, buildArrayItemDefaults, useResourceForm } from './chunk-JFHRSG6G.js';
9
9
  export { writeConflict } from './chunk-LKRJB632.js';
10
- export { useResource } from './chunk-P3FHXRS2.js';
10
+ export { useOne } from './chunk-QGWQ6LK3.js';
11
+ export { useResource } from './chunk-TKK7D2ZT.js';
11
12
  export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from './chunk-RVWKVD5Q.js';
12
13
  export { useWizard } from './chunk-7KOLYF27.js';
13
14
  export { WRITE_FAILED, useWrite } from './chunk-NQFIAULD.js';
14
15
  import './chunk-7NUL32W7.js';
16
+ export { useAggregate } from './chunk-XPBS5YE4.js';
15
17
  export { useDraft } from './chunk-YZV3Z6ZA.js';
16
- export { useLinkOptions } from './chunk-DFABPMEQ.js';
17
- export { loadRelationLabel, relationNamingField, useRelationLabel } from './chunk-WDPM5TBO.js';
18
- export { useInfiniteResource } from './chunk-G6GQPXQS.js';
19
- export { useOne } from './chunk-NE2D74BP.js';
20
- export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation } from './chunk-S2VYJWB4.js';
21
- import './chunk-UHOMTFBD.js';
18
+ export { useLinkOptions } from './chunk-POUI7GAI.js';
19
+ export { loadRelationLabel, relationNamingField, useRelationLabel } from './chunk-UDSTWXXZ.js';
20
+ export { useInfiniteResource } from './chunk-M5IX7C6U.js';
21
+ export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation } from './chunk-E3K2A3PK.js';
22
+ import { isAppearance, APPEARANCES, isDensity, DENSITIES, toAppearancePreferenceValues, resolveAppearancePreferences } from './chunk-JTRRAVR4.js';
23
+ export { APPEARANCES, DENSITIES, GENESIS_APPEARANCE_DEFAULTS, isAppearance, isDensity, resolveAppearancePreferences, toAppearancePreferenceValues } from './chunk-JTRRAVR4.js';
22
24
  export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from './chunk-5ASUMG6K.js';
23
- export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './chunk-RFHUOXZC.js';
24
- export { useCapabilities } from './chunk-KA3BUJ4H.js';
25
+ export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './chunk-SOO54YYY.js';
26
+ export { useCapabilities } from './chunk-42NVJJTT.js';
25
27
  import './chunk-AJGVLF37.js';
26
- export { defineQueryKeys, resourceKeys } from './chunk-7PUFVNPB.js';
27
- export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from './chunk-2K4747KX.js';
28
+ export { defineQueryKeys, resourceKeys } from './chunk-2IGAUXYH.js';
29
+ export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from './chunk-R3YXYVWF.js';
30
+ export { aggregateProblems, resolveAggregate, toAggregateValues } from './chunk-J54XXKQD.js';
28
31
  export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './chunk-4PTQYT5J.js';
29
32
  import './chunk-AUVKRXRC.js';
30
33
  import './chunk-WXENWPWP.js';
34
+ import { reportError } from './chunk-NOPS5EIH.js';
31
35
  export { classifyError, defaultErrorReporter, errorMessages, fieldErrorsFromPostgrest, getErrorReporter, readOutcomeFromCode, reportError, setErrorReporter, toDataWriteError, writeOutcomeFromCode } from './chunk-NOPS5EIH.js';
32
36
  export { DataReadError, isDataReadError, readFailureMessage } from './chunk-HUNGCTRA.js';
33
37
  export { titleCase } from './chunk-RYEXWQFD.js';
34
38
  export { DataWriteError, NO_ROWS_MATCHED, isDataWriteError } from './chunk-WLDSIQJ2.js';
35
39
  import './chunk-65SXNHWE.js';
36
40
  export { isSafeUrl, normalizeLinkUrl } from './chunk-YDDPFSQ6.js';
41
+ import { createContext, useState, useRef, useEffect, useMemo, useCallback, useContext } from 'react';
42
+ import { jsx } from 'react/jsx-runtime';
43
+
44
+ function defineAppearancePreferences(definition = {}) {
45
+ const problems = [];
46
+ const lock = definition.lock ?? {};
47
+ if (lock.appearance !== void 0 && !isAppearance(lock.appearance)) problems.push(`lock.appearance: one of ${APPEARANCES.join(", ")}`);
48
+ if (lock.density !== void 0 && !isDensity(lock.density)) problems.push(`lock.density: one of ${DENSITIES.join(", ")}`);
49
+ if (definition.store && (typeof definition.store.read !== "function" || typeof definition.store.write !== "function"))
50
+ problems.push("store: an object with read() and write()");
51
+ if (definition.storageKey !== void 0 && (typeof definition.storageKey !== "string" || !definition.storageKey.trim()))
52
+ problems.push("storageKey: a non-empty string");
53
+ if (problems.length) throw new Error(`defineAppearancePreferences: ${problems.join("; ")}`);
54
+ return Object.freeze({
55
+ ...definition.store ? { store: definition.store } : {},
56
+ storageKey: definition.storageKey ?? "genesis-appearance",
57
+ lock: Object.freeze(toAppearancePreferenceValues(lock))
58
+ });
59
+ }
60
+ var AppearancePreferencesContext = createContext(null);
61
+ var FORMAT = {
62
+ parse: (raw) => {
63
+ try {
64
+ return toAppearancePreferenceValues(JSON.parse(raw));
65
+ } catch {
66
+ return void 0;
67
+ }
68
+ }
69
+ };
70
+ var NONE = {};
71
+ var DEVICE_ONLY = defineAppearancePreferences();
72
+ function AppearancePreferencesProvider({ preferences = DEVICE_ONLY, organization, theme, children }) {
73
+ const { store, storageKey, lock } = preferences;
74
+ const [device, setDevice] = usePersistedUiState(storageKey, NONE, FORMAT);
75
+ const [stored, setStored] = useState(void 0);
76
+ const [ready, setReady] = useState(!store);
77
+ const latestStore = useRef(store);
78
+ latestStore.current = store;
79
+ useEffect(() => {
80
+ if (!store) return;
81
+ let active = true;
82
+ Promise.resolve().then(() => store.read()).then(
83
+ (values) => {
84
+ if (!active) return;
85
+ setStored(values ? toAppearancePreferenceValues(values) : null);
86
+ setReady(true);
87
+ },
88
+ (error) => {
89
+ reportError(error, "core:appearance-preferences");
90
+ if (active) setReady(true);
91
+ }
92
+ );
93
+ const unsubscribe = store.subscribe?.((values) => {
94
+ if (active) setStored(values ? toAppearancePreferenceValues(values) : null);
95
+ });
96
+ return () => {
97
+ active = false;
98
+ unsubscribe?.();
99
+ };
100
+ }, [store]);
101
+ const person = useMemo(() => ({ ...device, ...stored ?? {} }), [device, stored]);
102
+ const save = useCallback(
103
+ (patch) => {
104
+ const next = toAppearancePreferenceValues({ ...person, ...patch });
105
+ setDevice(Object.keys(next).length ? next : void 0);
106
+ if (latestStore.current) {
107
+ setStored(next);
108
+ void Promise.resolve().then(() => latestStore.current?.write(next)).catch((error) => {
109
+ reportError(error, "core:appearance-preferences");
110
+ });
111
+ }
112
+ },
113
+ [person, setDevice]
114
+ );
115
+ const value = useMemo(() => {
116
+ const layers = { lock, person, organization, theme };
117
+ const resolved = resolveAppearancePreferences(layers);
118
+ const locked = { appearance: lock.appearance !== void 0, density: lock.density !== void 0 };
119
+ return {
120
+ ...resolved,
121
+ person,
122
+ locked,
123
+ layers,
124
+ ready,
125
+ setAppearance: (appearance) => {
126
+ if (!locked.appearance) save({ appearance });
127
+ },
128
+ setDensity: (density) => {
129
+ if (!locked.density) save({ density });
130
+ }
131
+ };
132
+ }, [lock, person, organization, theme, ready, save]);
133
+ return /* @__PURE__ */ jsx(AppearancePreferencesContext.Provider, { value, children });
134
+ }
135
+ function useAppearancePreferences() {
136
+ const value = useContext(AppearancePreferencesContext);
137
+ if (!value) throw new Error("useAppearancePreferences: no AppearancePreferencesProvider above this component.");
138
+ return value;
139
+ }
140
+ function useOptionalAppearancePreferences() {
141
+ return useContext(AppearancePreferencesContext);
142
+ }
143
+
144
+ export { AppearancePreferencesProvider, defineAppearancePreferences, useAppearancePreferences, useOptionalAppearancePreferences };
37
145
  //# sourceMappingURL=index.js.map
38
146
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
1
+ {"version":3,"sources":["../src/appearance.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFO,SAAS,2BAAA,CAA4B,UAAA,GAA8C,EAAC,EAA0B;AACnH,EAAA,MAAM,WAAqB,EAAC;AAC5B,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,IAAA,IAAQ,EAAC;AACjC,EAAA,IAAI,IAAA,CAAK,UAAA,KAAe,MAAA,IAAa,CAAC,aAAa,IAAA,CAAK,UAAU,CAAA,EAAG,QAAA,CAAS,KAAK,CAAA,wBAAA,EAA2B,WAAA,CAAY,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AACtI,EAAA,IAAI,IAAA,CAAK,OAAA,KAAY,MAAA,IAAa,CAAC,UAAU,IAAA,CAAK,OAAO,CAAA,EAAG,QAAA,CAAS,KAAK,CAAA,qBAAA,EAAwB,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AACxH,EAAA,IAAI,UAAA,CAAW,KAAA,KAAU,OAAO,UAAA,CAAW,KAAA,CAAM,SAAS,UAAA,IAAc,OAAO,UAAA,CAAW,KAAA,CAAM,KAAA,KAAU,UAAA,CAAA;AACxG,IAAA,QAAA,CAAS,KAAK,0CAA0C,CAAA;AAC1D,EAAA,IAAI,UAAA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CAAA;AAAA,MACvC;AAAA,KACF;AAAA,EACF,CAAA,EAAG,CAAC,IAAA,EAAM,MAAA,EAAQ,cAAc,KAAA,EAAO,KAAA,EAAO,IAAI,CAAC,CAAA;AAEnD,EAAA,uBAAO,GAAA,CAAC,4BAAA,CAA6B,QAAA,EAA7B,EAAsC,OAAe,QAAA,EAAS,CAAA;AACxE;AASO,SAAS,wBAAA,GAA2D;AACzE,EAAA,MAAM,KAAA,GAAQ,WAAW,4BAA4B,CAAA;AACrD,EAAA,IAAI,CAAC,KAAA,EAAO,MAAM,IAAI,MAAM,kFAAkF,CAAA;AAC9G,EAAA,OAAO,KAAA;AACT;AAQO,SAAS,gCAAA,GAA0E;AACxF,EAAA,OAAO,WAAW,4BAA4B,CAAA;AAChD","file":"index.js","sourcesContent":["\"use client\";\n/**\n * Appearance preferences (ADR 0024): who sets a person's appearance (light, dark or system) and\n * density (compact, comfortable, spacious).\n *\n * Both are the person's. An app can lock either one; an organization can set a default for its\n * people; an app theme sets the default under that; Genesis's own default is last:\n *\n * app lock > person > organization default > theme default > Genesis default\n *\n * `resolveAppearancePreferences` is that order as a pure function. `defineAppearancePreferences`\n * declares an app's lock, defaults and where a person's choice is kept: a store (an adapter the\n * app backs with its own server table, so the choice follows the person to every device), with\n * the device's storage (`useStorage()`) as a copy and the fallback. `AppearancePreferencesProvider`\n * serves it to the tree: genesis-ui's `AppearanceProvider` (light and dark) and `AppShell`\n * (density) read it when it is there, and work as before when it isn't.\n *\n * Brand is not here: an organization sets its brand (`WorkspaceTheme.brand`), and the app sets\n * the theme per area.\n */\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { usePersistedUiState } from \"./hooks/use-persisted-ui-state\";\nimport { reportError } from \"./errors\";\nimport {\n APPEARANCES,\n DENSITIES,\n isAppearance,\n isDensity,\n resolveAppearancePreferences,\n toAppearancePreferenceValues,\n type Appearance,\n type AppearancePreferenceLayers,\n type AppearancePreferenceValues,\n type Density,\n type ResolvedAppearancePreferences,\n} from \"./appearance-values\";\n\n/**\n * Where a person's appearance preferences are kept: an adapter an app backs with its own server\n * table (a `profiles` row, say), so the choice follows the person. `read` may be async; return\n * null when the person has chosen nothing. `subscribe` (optional) reports a change made elsewhere.\n *\n * @stability Beta\n */\nexport interface AppearancePreferencesStore {\n read(): AppearancePreferenceValues | null | undefined | Promise<AppearancePreferenceValues | null | undefined>;\n write(values: AppearancePreferenceValues): void | Promise<void>;\n subscribe?(onChange: (values: AppearancePreferenceValues | null) => void): () => void;\n}\n\n/** What `defineAppearancePreferences` accepts. */\nexport interface AppearancePreferencesDefinition {\n /** Where the person's choice is kept beyond this device. Unset: the device only. */\n store?: AppearancePreferencesStore;\n /** The device copy's storage key (`useStorage()`). Default `genesis-appearance`. */\n storageKey?: string;\n /** Values the app fixes: nobody below can change them. */\n lock?: AppearancePreferenceValues;\n}\n\n/** A defined appearance-preferences setup. */\nexport interface AppearancePreferences {\n readonly store?: AppearancePreferencesStore;\n readonly storageKey: string;\n readonly lock: Readonly<AppearancePreferenceValues>;\n}\n\n/**\n * Declare where a person's appearance and density are kept and what the app locks. Checks the\n * lock and returns it frozen; throws on a value that isn't an appearance or a density.\n *\n * ```ts\n * export const appearance = defineAppearancePreferences({\n * store: {\n * read: () => api.myPreferences(), // { appearance: \"dark\", density: \"compact\" }\n * write: (values) => api.saveMyPreferences(values),\n * },\n * lock: { density: \"comfortable\" },\n * });\n * ```\n *\n * @stability Beta\n */\nexport function defineAppearancePreferences(definition: AppearancePreferencesDefinition = {}): AppearancePreferences {\n const problems: string[] = [];\n const lock = definition.lock ?? {};\n if (lock.appearance !== undefined && !isAppearance(lock.appearance)) problems.push(`lock.appearance: one of ${APPEARANCES.join(\", \")}`);\n if (lock.density !== undefined && !isDensity(lock.density)) problems.push(`lock.density: one of ${DENSITIES.join(\", \")}`);\n if (definition.store && (typeof definition.store.read !== \"function\" || typeof definition.store.write !== \"function\"))\n problems.push(\"store: an object with read() and write()\");\n if (definition.storageKey !== undefined && (typeof definition.storageKey !== \"string\" || !definition.storageKey.trim()))\n problems.push(\"storageKey: a non-empty string\");\n if (problems.length) throw new Error(`defineAppearancePreferences: ${problems.join(\"; \")}`);\n return Object.freeze({\n ...(definition.store ? { store: definition.store } : {}),\n storageKey: definition.storageKey ?? \"genesis-appearance\",\n lock: Object.freeze(toAppearancePreferenceValues(lock)),\n });\n}\n\n/** What `useAppearancePreferences` returns. */\nexport interface UseAppearancePreferencesReturn extends ResolvedAppearancePreferences {\n /** The person's own choice (the store's, else this device's), before the order is applied. */\n person: AppearancePreferenceValues;\n /** Which values the app has locked. */\n locked: { appearance: boolean; density: boolean };\n /**\n * Every layer as given, for a component with a default of its own to put in the order\n * (`AppShell` puts its `options.density` under the theme's).\n */\n layers: AppearancePreferenceLayers;\n /** False until the store's first read has answered. */\n ready: boolean;\n /** Save the person's appearance (`undefined` clears it back to the defaults). Ignored when locked. */\n setAppearance(appearance: Appearance | undefined): void;\n /** Save the person's density (`undefined` clears it). Ignored when locked. */\n setDensity(density: Density | undefined): void;\n}\n\nconst AppearancePreferencesContext = createContext<UseAppearancePreferencesReturn | null>(null);\n\nconst FORMAT = {\n parse: (raw: string) => {\n try {\n return toAppearancePreferenceValues(JSON.parse(raw));\n } catch {\n return undefined;\n }\n },\n};\nconst NONE: AppearancePreferenceValues = {};\n\nexport interface AppearancePreferencesProviderProps {\n /** From `defineAppearancePreferences`. Default: this device only, nothing locked. */\n preferences?: AppearancePreferences;\n /** The active organization's defaults (`resolveWorkspaceAppearance(workspace)`). */\n organization?: AppearancePreferenceValues | undefined;\n /** The app theme's defaults. */\n theme?: AppearancePreferenceValues | undefined;\n children: ReactNode;\n}\n\nconst DEVICE_ONLY = defineAppearancePreferences();\n\n/**\n * Serves a person's appearance and density to the tree, resolved in the written order. Reads the\n * store once on mount (and on its `subscribe`), keeps a copy on the device, and writes both when\n * the person changes a value.\n *\n * @stability Beta\n */\nexport function AppearancePreferencesProvider({ preferences = DEVICE_ONLY, organization, theme, children }: AppearancePreferencesProviderProps) {\n const { store, storageKey, lock } = preferences;\n const [device, setDevice] = usePersistedUiState<AppearancePreferenceValues>(storageKey, NONE, FORMAT);\n const [stored, setStored] = useState<AppearancePreferenceValues | null | undefined>(undefined);\n const [ready, setReady] = useState(!store);\n const latestStore = useRef(store);\n latestStore.current = store;\n\n useEffect(() => {\n if (!store) return;\n let active = true;\n Promise.resolve()\n .then(() => store.read())\n .then(\n (values) => {\n if (!active) return;\n setStored(values ? toAppearancePreferenceValues(values) : null);\n setReady(true);\n },\n (error: unknown) => {\n // A store that can't be read leaves the device's copy in charge.\n reportError(error, \"core:appearance-preferences\");\n if (active) setReady(true);\n },\n );\n const unsubscribe = store.subscribe?.((values) => {\n if (active) setStored(values ? toAppearancePreferenceValues(values) : null);\n });\n return () => {\n active = false;\n unsubscribe?.();\n };\n }, [store]);\n\n // The store's answer is the person's choice; the device's copy fills in until it comes, and\n // when there is no store.\n const person = useMemo<AppearancePreferenceValues>(() => ({ ...device, ...(stored ?? {}) }), [device, stored]);\n\n const save = useCallback(\n (patch: AppearancePreferenceValues) => {\n // An undefined value in the patch clears that key: the spread sets it, and the check drops it.\n const next = toAppearancePreferenceValues({ ...person, ...patch });\n setDevice(Object.keys(next).length ? next : undefined);\n if (latestStore.current) {\n setStored(next);\n void Promise.resolve()\n .then(() => latestStore.current?.write(next))\n .catch((error: unknown) => {\n reportError(error, \"core:appearance-preferences\");\n });\n }\n },\n [person, setDevice],\n );\n\n const value = useMemo<UseAppearancePreferencesReturn>(() => {\n const layers: AppearancePreferenceLayers = { lock, person, organization, theme };\n const resolved = resolveAppearancePreferences(layers);\n const locked = { appearance: lock.appearance !== undefined, density: lock.density !== undefined };\n return {\n ...resolved,\n person,\n locked,\n layers,\n ready,\n setAppearance: (appearance) => {\n if (!locked.appearance) save({ appearance });\n },\n setDensity: (density) => {\n if (!locked.density) save({ density });\n },\n };\n }, [lock, person, organization, theme, ready, save]);\n\n return <AppearancePreferencesContext.Provider value={value}>{children}</AppearancePreferencesContext.Provider>;\n}\n\n/**\n * The person's appearance and density, resolved, with setters. Throws outside an\n * `AppearancePreferencesProvider`; a component that works with or without one reads\n * `useOptionalAppearancePreferences`.\n *\n * @stability Beta\n */\nexport function useAppearancePreferences(): UseAppearancePreferencesReturn {\n const value = useContext(AppearancePreferencesContext);\n if (!value) throw new Error(\"useAppearancePreferences: no AppearancePreferencesProvider above this component.\");\n return value;\n}\n\n/**\n * Like `useAppearancePreferences`, but null outside a provider: for a component (a shell, a\n * theme provider) that keeps its own behaviour when an app hasn't set preferences up.\n *\n * @stability Beta\n */\nexport function useOptionalAppearancePreferences(): UseAppearancePreferencesReturn | null {\n return useContext(AppearancePreferencesContext);\n}\n"]}
@@ -67,6 +67,29 @@ interface NavigationNode<T> {
67
67
  * @stability Beta
68
68
  */
69
69
  subNav?: "section" | "tabs" | "sidebar" | "off";
70
+ /**
71
+ * The zone this node and its descendants sit in (ADR 0003): a kind of work
72
+ * the viewer enters (their own work, training, admin). A descendant that
73
+ * names no zone of its own is in its nearest ancestor's; a node with none
74
+ * above it is global (settings, messages, help). `resolveNavigation`
75
+ * reports the current zone as `zone`, so an app can key a theme on it;
76
+ * `resolveNavigationZones` groups the tree by zone.
77
+ *
78
+ * @stability Beta
79
+ */
80
+ zone?: string;
81
+ }
82
+ /**
83
+ * One zone of an app's navigation (ADR 0003 §1): an ordered entry with an id
84
+ * the tree's `zone` names, a label and an optional icon (the app's own icon
85
+ * type, `I`).
86
+ *
87
+ * @stability Beta
88
+ */
89
+ interface NavigationZone<I = unknown> {
90
+ id: string;
91
+ label: string;
92
+ icon?: I;
70
93
  }
71
94
  /**
72
95
  * Result of {@link resolveNavigation}. `current`, `parent` and every `trail`
@@ -86,6 +109,14 @@ interface ResolvedNavigation<T> {
86
109
  trail: NavigationNode<T>[];
87
110
  /** Params captured by `current.path`, URL-decoded. */
88
111
  params: Record<string, string>;
112
+ /**
113
+ * The zone the location is in: the `zone` of the nearest node in `trail`
114
+ * that names one, so a page opened from a zone's list keeps that zone
115
+ * through its logical parents. `undefined` on a global page.
116
+ *
117
+ * @stability Beta
118
+ */
119
+ zone?: string;
89
120
  }
90
121
  /**
91
122
  * Resolve where `pathname` sits in a logical navigation tree. Pure: it never
@@ -104,6 +135,51 @@ interface ResolvedNavigation<T> {
104
135
  * @stability Beta
105
136
  */
106
137
  declare function resolveNavigation<T>(tree: NavigationNode<T>, pathname: string): ResolvedNavigation<T>;
138
+ /**
139
+ * Result of {@link resolveNavigationZones}.
140
+ *
141
+ * @stability Beta
142
+ */
143
+ interface ResolvedNavigationZones<T, I = unknown> {
144
+ /** The tree resolved against the location, as `resolveNavigation` returns it. */
145
+ navigation: ResolvedNavigation<T>;
146
+ /** The zone the location is in (`navigation.zone`'s entry), or `undefined` on a global page or the roll-up. */
147
+ zone?: NavigationZone<I>;
148
+ /**
149
+ * The zones that have a page, in the order given, each with the top nodes
150
+ * of its pages (a node whose parent is in another zone or none). A zone
151
+ * with no page in the tree is left out: filter the tree for the viewer
152
+ * first, and access decides which zones show (ADR 0003 §1).
153
+ */
154
+ zones: Array<{
155
+ zone: NavigationZone<I>;
156
+ nodes: NavigationNode<T>[];
157
+ }>;
158
+ /** The root's children in no zone: pages shown in every zone (settings, messages, help). */
159
+ global: NavigationNode<T>[];
160
+ /** The roll-up page above the zones, when `options.rollUp` names one that is in the tree. */
161
+ rollUp?: NavigationNode<T>;
162
+ }
163
+ /**
164
+ * Lay an app's zones over its navigation tree (ADR 0003 §1 and §4): which zone
165
+ * the location is in, each zone's pages, the global pages and the roll-up.
166
+ * Pure, so web and native shells use the same answer; an app with no zones
167
+ * gets every top page in `global` and no `zone`.
168
+ *
169
+ * ```ts
170
+ * const { zone } = resolveNavigationZones(tree, pathname, { zones: ZONES });
171
+ * const theme = THEMES[zone?.id ?? "home"]; // a theme per zone
172
+ * ```
173
+ *
174
+ * A zone id the tree names but `zones` doesn't list is ignored (its pages
175
+ * read as global), so a stale id never invents a zone.
176
+ *
177
+ * @stability Beta
178
+ */
179
+ declare function resolveNavigationZones<T, I = unknown>(tree: NavigationNode<T>, pathname: string, options?: {
180
+ zones: readonly NavigationZone<I>[];
181
+ rollUp?: string;
182
+ }): ResolvedNavigationZones<T, I>;
107
183
  /**
108
184
  * Most slots a phone bottom tab bar shows before the rest go under "More".
109
185
  *
@@ -122,4 +198,4 @@ declare function splitTabBarItems<T>(items: readonly T[], max?: number): {
122
198
  more: T[];
123
199
  };
124
200
 
125
- export { type IsPathActiveOptions, type NavigationNode, type ResolvedNavigation, TAB_BAR_MAX, isPathActive, resolveNavigation, splitTabBarItems };
201
+ export { type IsPathActiveOptions, type NavigationNode, type NavigationZone, type ResolvedNavigation, type ResolvedNavigationZones, TAB_BAR_MAX, isPathActive, resolveNavigation, resolveNavigationZones, splitTabBarItems };
@@ -92,12 +92,42 @@ function resolveNavigation(tree, pathname) {
92
92
  });
93
93
  const trail = winner.trail.map(interpolate);
94
94
  const current = trail[trail.length - 1];
95
+ const zone = [...trail].reverse().find((node) => node.zone !== void 0)?.zone;
95
96
  return {
96
97
  current,
97
98
  parent: trail.length > 1 ? trail[trail.length - 2] : void 0,
98
99
  items: current.items,
99
100
  trail,
100
- params
101
+ params,
102
+ ...zone !== void 0 ? { zone } : {}
103
+ };
104
+ }
105
+ function resolveNavigationZones(tree, pathname, options = { zones: [] }) {
106
+ const known = new Map(options.zones.map((z) => [z.id, z]));
107
+ const effective = (own, inherited) => own !== void 0 && known.has(own) ? own : inherited;
108
+ const byZone = /* @__PURE__ */ new Map();
109
+ const global = [];
110
+ let rollUp;
111
+ const visit = (node, parentZone, depth) => {
112
+ const zone = effective(node.zone, parentZone);
113
+ if (depth > 0 && options.rollUp !== void 0 && node.id === options.rollUp) rollUp = node;
114
+ else if (depth > 0 && zone !== void 0 && zone !== parentZone) {
115
+ const list = byZone.get(zone) ?? [];
116
+ list.push(node);
117
+ byZone.set(zone, list);
118
+ } else if (depth === 1 && zone === void 0) global.push(node);
119
+ for (const child of node.children ?? []) visit(child, zone, depth + 1);
120
+ };
121
+ visit(tree, effective(tree.zone, void 0), 0);
122
+ const navigation = resolveNavigation(tree, pathname);
123
+ const currentId = [...navigation.trail].reverse().find((node) => node.zone !== void 0 && known.has(node.zone))?.zone;
124
+ const current = currentId !== void 0 ? known.get(currentId) : void 0;
125
+ return {
126
+ navigation,
127
+ ...current ? { zone: current } : {},
128
+ zones: options.zones.filter((z) => byZone.has(z.id)).map((zone) => ({ zone, nodes: byZone.get(zone.id) })),
129
+ global,
130
+ ...rollUp ? { rollUp } : {}
101
131
  };
102
132
  }
103
133
  var TAB_BAR_MAX = 5;
@@ -107,6 +137,6 @@ function splitTabBarItems(items, max = TAB_BAR_MAX) {
107
137
  return { shown: items.slice(0, slots - 1), more: items.slice(slots - 1) };
108
138
  }
109
139
 
110
- export { TAB_BAR_MAX, isPathActive, resolveNavigation, splitTabBarItems };
140
+ export { TAB_BAR_MAX, isPathActive, resolveNavigation, resolveNavigationZones, splitTabBarItems };
111
141
  //# sourceMappingURL=navigation.js.map
112
142
  //# sourceMappingURL=navigation.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/navigation.ts"],"names":["trail"],"mappings":";AAOA,SAAS,oBAAoB,IAAA,EAAsB;AACjD,EAAA,IAAI,MAAM,IAAA,CAAK,MAAA;AACf,EAAA,OAAO,MAAM,CAAA,IAAK,IAAA,CAAK,WAAW,GAAA,GAAM,CAAC,MAAM,EAAA,EAAI,GAAA,EAAA;AACnD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA;AAC1B;AAMA,SAAS,UAAU,IAAA,EAA8D;AAC/E,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC/B,EAAA,MAAM,OAAO,MAAA,KAAW,EAAA,GAAK,KAAK,IAAA,CAAK,KAAA,CAAM,SAAS,CAAC,CAAA;AACvD,EAAA,MAAM,aAAa,MAAA,KAAW,EAAA,GAAK,OAAO,IAAA,C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,MAAA,EAAQ,MAAM,MAAA,GAAS,CAAA,GAAI,MAAM,KAAA,CAAM,MAAA,GAAS,CAAC,CAAA,GAAI,MAAA;AAAA,IACrD,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,KAAA;AAAA,IACA;AAAA,GACF;AACF;AAOO,IAAM,WAAA,GAAc;AASpB,SAAS,gBAAA,CAAoB,KAAA,EAAqB,GAAA,GAAc,WAAA,EAAwC;AAC7G,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,GAAG,CAAA;AAC7B,EAAA,IAAI,KAAA,CAAM,MAAA,IAAU,KAAA,EAAO,OAAO,EAAE,KAAA,EAAO,CAAC,GAAG,KAAK,CAAA,EAAG,IAAA,EAAM,EAAC,EAAE;AAChE,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,KAAA,GAAQ,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,CAAM,KAAA,CAAM,KAAA,GAAQ,CAAC,CAAA,EAAE;AAC1E","file":"navigation.js","sourcesContent":["/**\n * Router-free, DOM-free navigation: the logical navigation tree and the\n * active-path matcher, shared by the web app shell and native shells.\n * `resolveNavigation` never reads browser history or `window`.\n */\n\n/** `path` without its trailing slashes, in one linear pass (a regex can backtrack on many slashes). */\nfunction trimTrailingSlashes(path: string): string {\n let end = path.length;\n while (end > 0 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n}\n\n/**\n * Split a href into its path (trailing slash dropped, except for `/`), query\n * (no `?`) and hash (no `#`).\n */\nfunction splitHref(href: string): { path: string; search: string; hash: string } {\n const hashAt = href.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : href.slice(hashAt + 1);\n const beforeHash = hashAt === -1 ? href : href.slice(0, hashAt);\n const searchAt = beforeHash.indexOf(\"?\");\n const rawPath = searchAt === -1 ? beforeHash : beforeHash.slice(0, searchAt);\n return {\n path: rawPath.length > 1 ? trimTrailingSlashes(rawPath) || \"/\" : rawPath,\n search: searchAt === -1 ? \"\" : beforeHash.slice(searchAt + 1),\n hash,\n };\n}\n\n/**\n * Options for {@link isPathActive}.\n *\n * @stability Beta\n */\nexport interface IsPathActiveOptions {\n /** Require an exact path match instead of a prefix match (like `NavLink end`). */\n end?: boolean;\n}\n\n/**\n * Default active-path matcher, mirroring React Router's `NavLink` (prefix\n * match, with `/` treated as exact). Consumers can override via an `isActive`\n * prop where components accept one.\n *\n * `activePath` may carry a query and hash (`pathname + search + hash`). An\n * item whose `to` has neither compares against the path part only, exactly as\n * before. An item that opts in by putting a query or hash in its `to`\n * (`/admin?tab=users`, `/settings#profile`) is active only when the path\n * matches exactly AND every query param it names has the same value in\n * `activePath` (extra params such as `&page=2` are ignored) AND, if it names a\n * hash, the hash is equal.\n *\n * @stability Beta\n */\nexport function isPathActive(\n to: string,\n activePath?: string,\n options?: IsPathActiveOptions,\n): boolean {\n if (activePath == null) return false;\n if (to === activePath) return true;\n const target = splitHref(to);\n const current = splitHref(activePath);\n\n if (!target.search && !target.hash) {\n if (target.path === current.path) return true;\n if (options?.end) return false;\n return target.path !== \"/\" && current.path.startsWith(target.path + \"/\");\n }\n\n if (target.path !== current.path) return false;\n if (target.hash && target.hash !== current.hash) return false;\n if (target.search) {\n const want = new URLSearchParams(target.search);\n const have = new URLSearchParams(current.search);\n for (const key of new Set(want.keys())) {\n const wanted = want.getAll(key);\n const had = have.getAll(key);\n if (!wanted.every((value) => had.includes(value))) return false;\n }\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Hierarchical navigation resolver\n// ---------------------------------------------------------------------------\n\n/**\n * One node of a logical navigation hierarchy. `path` is a route pattern whose\n * segments are either static (`clients`) or named params (`$clientId`). A\n * node's place in the tree is its LOGICAL parent, which need not share its URL\n * prefix — `/clients/$clientId` can sit under `/dashboard`.\n *\n * @stability Beta\n */\nexport interface NavigationNode<T> {\n id: string;\n path: string;\n label: string;\n /** Contextual nav items to show while this node is current. */\n items: T[];\n children?: NavigationNode<T>[];\n /**\n * Ask the app shell to open its desktop sidebar collapsed (icon rail) while\n * this node, or a descendant that doesn't set its own value, is current.\n * The nearest node in the resolved trail that sets it wins, so\n * `defaultCollapsed: false` on a child re-opens it under a collapsed\n * parent. Only a default: once the user has toggled the sidebar, their\n * choice wins everywhere. `AppShell` reads it; `resolveNavigation` copies\n * it through untouched.\n *\n * @stability Beta\n */\n defaultCollapsed?: boolean;\n /**\n * How the app shell shows this node's `items` (its child pages, e.g. a\n * form's Questions / Logic / Responses / Settings). `\"tabs\"` (across the\n * top of the content) or `\"sidebar\"` (nested under the active item) turn\n * shell sub-navigation on, which also gives phones a back item plus the\n * children in the bottom bar. `\"section\"` is the legacy rendering (the\n * shell's default) and `\"off\"` hides them. The nearest node in the trail\n * that sets it wins over the shell's `options.subNav`.\n *\n * @stability Beta\n */\n subNav?: \"section\" | \"tabs\" | \"sidebar\" | \"off\";\n}\n\n/**\n * Result of {@link resolveNavigation}. `current`, `parent` and every `trail`\n * entry are shallow copies of their tree nodes with `path` interpolated from\n * `params` (a param the URL did not supply stays as `$name`).\n *\n * @stability Beta\n */\nexport interface ResolvedNavigation<T> {\n /** The best-matching node — the root when nothing else matches. */\n current: NavigationNode<T>;\n /** `current`'s logical parent, for an \"up\" / back-to-parent link. */\n parent?: NavigationNode<T>;\n /** `current.items`. */\n items: T[];\n /** Root → `current`, inclusive. */\n trail: NavigationNode<T>[];\n /** Params captured by `current.path`, URL-decoded. */\n params: Record<string, string>;\n}\n\nfunction pathSegments(path: string): string[] {\n return splitHref(path).path.split(\"/\").filter(Boolean);\n}\n\nfunction decodeSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\n/**\n * Resolve where `pathname` sits in a logical navigation tree. Pure: it never\n * reads browser history or `window`.\n *\n * A node matches when its pattern matches a leading run of WHOLE path\n * segments (`/my` matches `/my/tasks`, never `/my-other`). Among matches the\n * winner is decided by positional specificity: at the first position where\n * one pattern is static and the other a `$param`, the static one wins (so\n * `/clients/new` beats `/clients/$clientId` whatever the sibling order, and\n * `/my` beats `/$space/tasks` for `/my/tasks`). Otherwise the pattern matching\n * more segments wins, then the deeper tree node.\n * Non-matching nodes are still searched, so a match keeps its logical\n * ancestors even when their URLs differ.\n *\n * @stability Beta\n */\nexport function resolveNavigation<T>(\n tree: NavigationNode<T>,\n pathname: string,\n): ResolvedNavigation<T> {\n // Compare decoded forms on both sides, so `/caf%C3%A9` matches a `/café`\n // node (and an encoded pattern matches a decoded pathname).\n const segments = pathSegments(pathname).map(decodeSegment);\n\n type Match = { trail: NavigationNode<T>[]; pattern: string[] };\n const matches = (pattern: string[]) =>\n pattern.length <= segments.length &&\n pattern.every(\n (part, i) => part.startsWith(\"$\") || decodeSegment(part) === segments[i],\n );\n\n // > 0 when `a` should win over `b`.\n // Positional specificity, as TanStack Router and React Router rank routes:\n // walking left to right, the first position where one pattern is static and\n // the other a `$param` decides. Only then does the longer match win.\n const compare = (a: Match, b: Match): number => {\n const shared = Math.min(a.pattern.length, b.pattern.length);\n for (let i = 0; i < shared; i++) {\n const aParam = a.pattern[i]!.startsWith(\"$\");\n const bParam = b.pattern[i]!.startsWith(\"$\");\n if (aParam !== bParam) return aParam ? -1 : 1;\n }\n if (a.pattern.length !== b.pattern.length) {\n return a.pattern.length - b.pattern.length;\n }\n return a.trail.length - b.trail.length;\n };\n\n let best: Match | undefined;\n const visit = (node: NavigationNode<T>, ancestors: NavigationNode<T>[]) => {\n const trail = [...ancestors, node];\n const pattern = pathSegments(node.path);\n if (matches(pattern)) {\n const candidate = { trail, pattern };\n if (!best || compare(candidate, best) > 0) best = candidate;\n }\n for (const child of node.children ?? []) visit(child, trail);\n };\n visit(tree, []);\n\n const winner: Match = best ?? { trail: [tree], pattern: [] };\n const params: Record<string, string> = {};\n winner.pattern.forEach((part, i) => {\n if (part.startsWith(\"$\")) params[part.slice(1)] = segments[i]!;\n });\n\n const interpolate = (node: NavigationNode<T>): NavigationNode<T> => ({\n ...node,\n path: node.path\n .split(\"/\")\n .map((part) => {\n if (!part.startsWith(\"$\")) return part;\n const value = params[part.slice(1)];\n return value == null ? part : encodeURIComponent(value);\n })\n .join(\"/\"),\n });\n\n const trail = winner.trail.map(interpolate);\n const current = trail[trail.length - 1]!;\n return {\n current,\n parent: trail.length > 1 ? trail[trail.length - 2] : undefined,\n items: current.items,\n trail,\n params,\n };\n}\n\n/**\n * Most slots a phone bottom tab bar shows before the rest go under \"More\".\n *\n * @stability Beta\n */\nexport const TAB_BAR_MAX = 5;\n\n/**\n * A phone bottom tab bar's split: up to `max` items fit; beyond that, the first `max - 1` show\n * and the rest go under \"More\" in the last slot. Pure, so the web `TabBar`, AppShell's phone\n * bottom nav and genesis-ui-native's `NativeTabBar` all split the same way.\n *\n * @stability Beta\n */\nexport function splitTabBarItems<T>(items: readonly T[], max: number = TAB_BAR_MAX): { shown: T[]; more: T[] } {\n const slots = Math.max(1, max);\n if (items.length <= slots) return { shown: [...items], more: [] };\n return { shown: items.slice(0, slots - 1), more: items.slice(slots - 1) };\n}\n"]}
1
+ {"version":3,"sources":["../src/navigation.ts"],"names":["trail"],"mappings":";AAOA,SAAS,oBAAoB,IAAA,EAAsB;AACjD,EAAA,IAAI,MAAM,IAAA,CAAK,MAAA;AACf,EAAA,OAAO,MAAM,CAAA,IAAK,IAAA,CAAK,WAAW,GAAA,GAAM,CAAC,MAAM,EAAA,EAAI,GAAA,EAAA;AACnD,EAAA,OAAO,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA;AAC1B;AAMA,SAAS,UAAU,IAAA,EAA8D;AAC/E,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC/B,EAAA,MAAM,OAAO,MAAA,KAAW,EAAA,GAAK,KAAK,IAAA,CAAK,KAAA,CAAM,SAAS,CAAC,CAAA;AACvD,EAAA,MAAM,aAAa,MAAA,KAAW,EAAA,GAAK,OAAO,IAAA,CAAK,KAAA,C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AC1G,MAAA;AAAA,IACA,GAAI,MAAA,GAAS,EAAE,MAAA,KAAW;AAAC,GAC7B;AACF;AAOO,IAAM,WAAA,GAAc;AASpB,SAAS,gBAAA,CAAoB,KAAA,EAAqB,GAAA,GAAc,WAAA,EAAwC;AAC7G,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,GAAG,CAAA;AAC7B,EAAA,IAAI,KAAA,CAAM,MAAA,IAAU,KAAA,EAAO,OAAO,EAAE,KAAA,EAAO,CAAC,GAAG,KAAK,CAAA,EAAG,IAAA,EAAM,EAAC,EAAE;AAChE,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,KAAA,GAAQ,CAAC,CAAA,EAAG,IAAA,EAAM,KAAA,CAAM,KAAA,CAAM,KAAA,GAAQ,CAAC,CAAA,EAAE;AAC1E","file":"navigation.js","sourcesContent":["/**\n * Router-free, DOM-free navigation: the logical navigation tree and the\n * active-path matcher, shared by the web app shell and native shells.\n * `resolveNavigation` never reads browser history or `window`.\n */\n\n/** `path` without its trailing slashes, in one linear pass (a regex can backtrack on many slashes). */\nfunction trimTrailingSlashes(path: string): string {\n let end = path.length;\n while (end > 0 && path.charCodeAt(end - 1) === 47) end--;\n return path.slice(0, end);\n}\n\n/**\n * Split a href into its path (trailing slash dropped, except for `/`), query\n * (no `?`) and hash (no `#`).\n */\nfunction splitHref(href: string): { path: string; search: string; hash: string } {\n const hashAt = href.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : href.slice(hashAt + 1);\n const beforeHash = hashAt === -1 ? href : href.slice(0, hashAt);\n const searchAt = beforeHash.indexOf(\"?\");\n const rawPath = searchAt === -1 ? beforeHash : beforeHash.slice(0, searchAt);\n return {\n path: rawPath.length > 1 ? trimTrailingSlashes(rawPath) || \"/\" : rawPath,\n search: searchAt === -1 ? \"\" : beforeHash.slice(searchAt + 1),\n hash,\n };\n}\n\n/**\n * Options for {@link isPathActive}.\n *\n * @stability Beta\n */\nexport interface IsPathActiveOptions {\n /** Require an exact path match instead of a prefix match (like `NavLink end`). */\n end?: boolean;\n}\n\n/**\n * Default active-path matcher, mirroring React Router's `NavLink` (prefix\n * match, with `/` treated as exact). Consumers can override via an `isActive`\n * prop where components accept one.\n *\n * `activePath` may carry a query and hash (`pathname + search + hash`). An\n * item whose `to` has neither compares against the path part only, exactly as\n * before. An item that opts in by putting a query or hash in its `to`\n * (`/admin?tab=users`, `/settings#profile`) is active only when the path\n * matches exactly AND every query param it names has the same value in\n * `activePath` (extra params such as `&page=2` are ignored) AND, if it names a\n * hash, the hash is equal.\n *\n * @stability Beta\n */\nexport function isPathActive(\n to: string,\n activePath?: string,\n options?: IsPathActiveOptions,\n): boolean {\n if (activePath == null) return false;\n if (to === activePath) return true;\n const target = splitHref(to);\n const current = splitHref(activePath);\n\n if (!target.search && !target.hash) {\n if (target.path === current.path) return true;\n if (options?.end) return false;\n return target.path !== \"/\" && current.path.startsWith(target.path + \"/\");\n }\n\n if (target.path !== current.path) return false;\n if (target.hash && target.hash !== current.hash) return false;\n if (target.search) {\n const want = new URLSearchParams(target.search);\n const have = new URLSearchParams(current.search);\n for (const key of new Set(want.keys())) {\n const wanted = want.getAll(key);\n const had = have.getAll(key);\n if (!wanted.every((value) => had.includes(value))) return false;\n }\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Hierarchical navigation resolver\n// ---------------------------------------------------------------------------\n\n/**\n * One node of a logical navigation hierarchy. `path` is a route pattern whose\n * segments are either static (`clients`) or named params (`$clientId`). A\n * node's place in the tree is its LOGICAL parent, which need not share its URL\n * prefix — `/clients/$clientId` can sit under `/dashboard`.\n *\n * @stability Beta\n */\nexport interface NavigationNode<T> {\n id: string;\n path: string;\n label: string;\n /** Contextual nav items to show while this node is current. */\n items: T[];\n children?: NavigationNode<T>[];\n /**\n * Ask the app shell to open its desktop sidebar collapsed (icon rail) while\n * this node, or a descendant that doesn't set its own value, is current.\n * The nearest node in the resolved trail that sets it wins, so\n * `defaultCollapsed: false` on a child re-opens it under a collapsed\n * parent. Only a default: once the user has toggled the sidebar, their\n * choice wins everywhere. `AppShell` reads it; `resolveNavigation` copies\n * it through untouched.\n *\n * @stability Beta\n */\n defaultCollapsed?: boolean;\n /**\n * How the app shell shows this node's `items` (its child pages, e.g. a\n * form's Questions / Logic / Responses / Settings). `\"tabs\"` (across the\n * top of the content) or `\"sidebar\"` (nested under the active item) turn\n * shell sub-navigation on, which also gives phones a back item plus the\n * children in the bottom bar. `\"section\"` is the legacy rendering (the\n * shell's default) and `\"off\"` hides them. The nearest node in the trail\n * that sets it wins over the shell's `options.subNav`.\n *\n * @stability Beta\n */\n subNav?: \"section\" | \"tabs\" | \"sidebar\" | \"off\";\n /**\n * The zone this node and its descendants sit in (ADR 0003): a kind of work\n * the viewer enters (their own work, training, admin). A descendant that\n * names no zone of its own is in its nearest ancestor's; a node with none\n * above it is global (settings, messages, help). `resolveNavigation`\n * reports the current zone as `zone`, so an app can key a theme on it;\n * `resolveNavigationZones` groups the tree by zone.\n *\n * @stability Beta\n */\n zone?: string;\n}\n\n/**\n * One zone of an app's navigation (ADR 0003 §1): an ordered entry with an id\n * the tree's `zone` names, a label and an optional icon (the app's own icon\n * type, `I`).\n *\n * @stability Beta\n */\nexport interface NavigationZone<I = unknown> {\n id: string;\n label: string;\n icon?: I;\n}\n\n/**\n * Result of {@link resolveNavigation}. `current`, `parent` and every `trail`\n * entry are shallow copies of their tree nodes with `path` interpolated from\n * `params` (a param the URL did not supply stays as `$name`).\n *\n * @stability Beta\n */\nexport interface ResolvedNavigation<T> {\n /** The best-matching node — the root when nothing else matches. */\n current: NavigationNode<T>;\n /** `current`'s logical parent, for an \"up\" / back-to-parent link. */\n parent?: NavigationNode<T>;\n /** `current.items`. */\n items: T[];\n /** Root → `current`, inclusive. */\n trail: NavigationNode<T>[];\n /** Params captured by `current.path`, URL-decoded. */\n params: Record<string, string>;\n /**\n * The zone the location is in: the `zone` of the nearest node in `trail`\n * that names one, so a page opened from a zone's list keeps that zone\n * through its logical parents. `undefined` on a global page.\n *\n * @stability Beta\n */\n zone?: string;\n}\n\nfunction pathSegments(path: string): string[] {\n return splitHref(path).path.split(\"/\").filter(Boolean);\n}\n\nfunction decodeSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\n/**\n * Resolve where `pathname` sits in a logical navigation tree. Pure: it never\n * reads browser history or `window`.\n *\n * A node matches when its pattern matches a leading run of WHOLE path\n * segments (`/my` matches `/my/tasks`, never `/my-other`). Among matches the\n * winner is decided by positional specificity: at the first position where\n * one pattern is static and the other a `$param`, the static one wins (so\n * `/clients/new` beats `/clients/$clientId` whatever the sibling order, and\n * `/my` beats `/$space/tasks` for `/my/tasks`). Otherwise the pattern matching\n * more segments wins, then the deeper tree node.\n * Non-matching nodes are still searched, so a match keeps its logical\n * ancestors even when their URLs differ.\n *\n * @stability Beta\n */\nexport function resolveNavigation<T>(\n tree: NavigationNode<T>,\n pathname: string,\n): ResolvedNavigation<T> {\n // Compare decoded forms on both sides, so `/caf%C3%A9` matches a `/café`\n // node (and an encoded pattern matches a decoded pathname).\n const segments = pathSegments(pathname).map(decodeSegment);\n\n type Match = { trail: NavigationNode<T>[]; pattern: string[] };\n const matches = (pattern: string[]) =>\n pattern.length <= segments.length &&\n pattern.every(\n (part, i) => part.startsWith(\"$\") || decodeSegment(part) === segments[i],\n );\n\n // > 0 when `a` should win over `b`.\n // Positional specificity, as TanStack Router and React Router rank routes:\n // walking left to right, the first position where one pattern is static and\n // the other a `$param` decides. Only then does the longer match win.\n const compare = (a: Match, b: Match): number => {\n const shared = Math.min(a.pattern.length, b.pattern.length);\n for (let i = 0; i < shared; i++) {\n const aParam = a.pattern[i]!.startsWith(\"$\");\n const bParam = b.pattern[i]!.startsWith(\"$\");\n if (aParam !== bParam) return aParam ? -1 : 1;\n }\n if (a.pattern.length !== b.pattern.length) {\n return a.pattern.length - b.pattern.length;\n }\n return a.trail.length - b.trail.length;\n };\n\n let best: Match | undefined;\n const visit = (node: NavigationNode<T>, ancestors: NavigationNode<T>[]) => {\n const trail = [...ancestors, node];\n const pattern = pathSegments(node.path);\n if (matches(pattern)) {\n const candidate = { trail, pattern };\n if (!best || compare(candidate, best) > 0) best = candidate;\n }\n for (const child of node.children ?? []) visit(child, trail);\n };\n visit(tree, []);\n\n const winner: Match = best ?? { trail: [tree], pattern: [] };\n const params: Record<string, string> = {};\n winner.pattern.forEach((part, i) => {\n if (part.startsWith(\"$\")) params[part.slice(1)] = segments[i]!;\n });\n\n const interpolate = (node: NavigationNode<T>): NavigationNode<T> => ({\n ...node,\n path: node.path\n .split(\"/\")\n .map((part) => {\n if (!part.startsWith(\"$\")) return part;\n const value = params[part.slice(1)];\n return value == null ? part : encodeURIComponent(value);\n })\n .join(\"/\"),\n });\n\n const trail = winner.trail.map(interpolate);\n const current = trail[trail.length - 1]!;\n const zone = [...trail].reverse().find((node) => node.zone !== undefined)?.zone;\n return {\n current,\n parent: trail.length > 1 ? trail[trail.length - 2] : undefined,\n items: current.items,\n trail,\n params,\n ...(zone !== undefined ? { zone } : {}),\n };\n}\n\n/**\n * Result of {@link resolveNavigationZones}.\n *\n * @stability Beta\n */\nexport interface ResolvedNavigationZones<T, I = unknown> {\n /** The tree resolved against the location, as `resolveNavigation` returns it. */\n navigation: ResolvedNavigation<T>;\n /** The zone the location is in (`navigation.zone`'s entry), or `undefined` on a global page or the roll-up. */\n zone?: NavigationZone<I>;\n /**\n * The zones that have a page, in the order given, each with the top nodes\n * of its pages (a node whose parent is in another zone or none). A zone\n * with no page in the tree is left out: filter the tree for the viewer\n * first, and access decides which zones show (ADR 0003 §1).\n */\n zones: Array<{ zone: NavigationZone<I>; nodes: NavigationNode<T>[] }>;\n /** The root's children in no zone: pages shown in every zone (settings, messages, help). */\n global: NavigationNode<T>[];\n /** The roll-up page above the zones, when `options.rollUp` names one that is in the tree. */\n rollUp?: NavigationNode<T>;\n}\n\n/**\n * Lay an app's zones over its navigation tree (ADR 0003 §1 and §4): which zone\n * the location is in, each zone's pages, the global pages and the roll-up.\n * Pure, so web and native shells use the same answer; an app with no zones\n * gets every top page in `global` and no `zone`.\n *\n * ```ts\n * const { zone } = resolveNavigationZones(tree, pathname, { zones: ZONES });\n * const theme = THEMES[zone?.id ?? \"home\"]; // a theme per zone\n * ```\n *\n * A zone id the tree names but `zones` doesn't list is ignored (its pages\n * read as global), so a stale id never invents a zone.\n *\n * @stability Beta\n */\nexport function resolveNavigationZones<T, I = unknown>(\n tree: NavigationNode<T>,\n pathname: string,\n options: { zones: readonly NavigationZone<I>[]; rollUp?: string } = { zones: [] },\n): ResolvedNavigationZones<T, I> {\n const known = new Map(options.zones.map((z) => [z.id, z] as const));\n const effective = (own: string | undefined, inherited: string | undefined) =>\n own !== undefined && known.has(own) ? own : inherited;\n const byZone = new Map<string, NavigationNode<T>[]>();\n const global: NavigationNode<T>[] = [];\n let rollUp: NavigationNode<T> | undefined;\n const visit = (node: NavigationNode<T>, parentZone: string | undefined, depth: number) => {\n const zone = effective(node.zone, parentZone);\n if (depth > 0 && options.rollUp !== undefined && node.id === options.rollUp) rollUp = node;\n else if (depth > 0 && zone !== undefined && zone !== parentZone) {\n const list = byZone.get(zone) ?? [];\n list.push(node);\n byZone.set(zone, list);\n } else if (depth === 1 && zone === undefined) global.push(node);\n for (const child of node.children ?? []) visit(child, zone, depth + 1);\n };\n visit(tree, effective(tree.zone, undefined), 0);\n const navigation = resolveNavigation(tree, pathname);\n const currentId = [...navigation.trail].reverse().find((node) => node.zone !== undefined && known.has(node.zone))?.zone;\n const current = currentId !== undefined ? known.get(currentId) : undefined;\n return {\n navigation,\n ...(current ? { zone: current } : {}),\n zones: options.zones.filter((z) => byZone.has(z.id)).map((zone) => ({ zone, nodes: byZone.get(zone.id)! })),\n global,\n ...(rollUp ? { rollUp } : {}),\n };\n}\n\n/**\n * Most slots a phone bottom tab bar shows before the rest go under \"More\".\n *\n * @stability Beta\n */\nexport const TAB_BAR_MAX = 5;\n\n/**\n * A phone bottom tab bar's split: up to `max` items fit; beyond that, the first `max - 1` show\n * and the rest go under \"More\" in the last slot. Pure, so the web `TabBar`, AppShell's phone\n * bottom nav and genesis-ui-native's `NativeTabBar` all split the same way.\n *\n * @stability Beta\n */\nexport function splitTabBarItems<T>(items: readonly T[], max: number = TAB_BAR_MAX): { shown: T[]; more: T[] } {\n const slots = Math.max(1, max);\n if (items.length <= slots) return { shown: [...items], more: [] };\n return { shown: items.slice(0, slots - 1), more: items.slice(slots - 1) };\n}\n"]}