@marktiderman/genesis-core 2.15.0 → 2.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{aggregate-y-qqJioF.d.ts → aggregate-Y5IJ5aPn.d.ts} +1 -1
- package/dist/{chunk-TKK7D2ZT.js → chunk-ALLWIK62.js} +3 -3
- package/dist/{chunk-TKK7D2ZT.js.map → chunk-ALLWIK62.js.map} +1 -1
- package/dist/{chunk-JTRRAVR4.js → chunk-APFXV6FZ.js} +18 -12
- package/dist/chunk-APFXV6FZ.js.map +1 -0
- package/dist/chunk-BDPRWVFW.js +17 -0
- package/dist/chunk-BDPRWVFW.js.map +1 -0
- package/dist/{chunk-JFHRSG6G.js → chunk-FXPODKCK.js} +3 -3
- package/dist/{chunk-JFHRSG6G.js.map → chunk-FXPODKCK.js.map} +1 -1
- package/dist/{chunk-YZV3Z6ZA.js → chunk-SQLM5CIJ.js} +3 -3
- package/dist/{chunk-YZV3Z6ZA.js.map → chunk-SQLM5CIJ.js.map} +1 -1
- package/dist/{chunk-NZP7YQHS.js → chunk-ZYOJWU62.js} +4 -4
- package/dist/{chunk-NZP7YQHS.js.map → chunk-ZYOJWU62.js.map} +1 -1
- package/dist/csv.d.ts +1 -1
- package/dist/form-types.d.ts +1 -1
- package/dist/headless/index.d.ts +334 -0
- package/dist/headless/index.js +490 -0
- package/dist/headless/index.js.map +1 -0
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +11 -10
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-aggregate.d.ts +2 -2
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-draft.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +3 -3
- package/dist/hooks/use-resource.d.ts +1 -1
- package/dist/hooks/use-resource.js +3 -3
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +12 -11
- package/dist/index.js.map +1 -1
- package/dist/provider/index.d.ts +5 -5
- package/dist/resource-view/index.d.ts +1 -1
- package/dist/schema/index.d.ts +3 -3
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-D4Bi_Iq8.d.ts → types-BriIV4e_.d.ts} +2 -0
- package/dist/{workspaces-BKhloJPK.d.ts → workspaces-CxpiFu2-.d.ts} +9 -1
- package/dist/workspaces.d.ts +1 -1
- package/dist/workspaces.js +2 -1
- package/dist/{write-outcome-CHPT7Slm.d.ts → write-outcome-CkQXgtJq.d.ts} +1 -1
- package/package.json +14 -4
- package/dist/chunk-JTRRAVR4.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AggregateParams, D as DataProvider, b as AggregateResult, i as AggregateMetric } from './types-
|
|
1
|
+
import { A as AggregateParams, D as DataProvider, b as AggregateResult, i as AggregateMetric } from './types-BriIV4e_.js';
|
|
2
2
|
|
|
3
3
|
type Row = Record<string, unknown>;
|
|
4
4
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { invalidateResource, executeWrite, cachedRecord } from './chunk-SOO54YYY.js';
|
|
1
2
|
import { relatedKeys } from './chunk-7NUL32W7.js';
|
|
2
3
|
import { useLiveInvalidation } from './chunk-E3K2A3PK.js';
|
|
3
|
-
import { invalidateResource, executeWrite, cachedRecord } from './chunk-SOO54YYY.js';
|
|
4
4
|
import { resourceKeys } from './chunk-2IGAUXYH.js';
|
|
5
5
|
import { useDataProvider } from './chunk-R3YXYVWF.js';
|
|
6
6
|
import { isDataWriteError, DataWriteError, NO_ROWS_MATCHED } from './chunk-WLDSIQJ2.js';
|
|
@@ -222,5 +222,5 @@ function useResource(resource, options = {}) {
|
|
|
222
222
|
}
|
|
223
223
|
|
|
224
224
|
export { useResource };
|
|
225
|
-
//# sourceMappingURL=chunk-
|
|
226
|
-
//# sourceMappingURL=chunk-
|
|
225
|
+
//# sourceMappingURL=chunk-ALLWIK62.js.map
|
|
226
|
+
//# sourceMappingURL=chunk-ALLWIK62.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-resource.ts"],"names":["keepPreviousData","keepPreviousPlaceholder","options"],"mappings":";;;;;;;;;AA0JA,SAAS,gBAAgB,OAAA,EAAwD;AAC/E,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACV,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM;AACjB,MAAA,MAAM,SAAkC,EAAC;AACzC,MAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAK,EAAG;AACvC,QAAA,MAAA,CAAO,GAAG,CAAA,GAAK,CAAA,CAAyC,GAAG,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC;AAAA,GACH;AACF;AAMO,SAAS,WAAA,CACd,QAAA,EACA,OAAA,GAAiC,EAAC,EACZ;AACtB,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA,GAAiB,EAAA;AAAA,IACjB,WAAA,GAAc,CAAA;AAAA,IACd,aAAA,GAAgB,EAAA;AAAA,IAChB,MAAA;AAAA,IACA,YAAA,EAAc,kBAAA;AAAA,IACd,OAAA,GAAU,IAAA;AAAA,IACV,WAAA;AAAA,sBACAA,kBAAA,GAAmB,KAAA;AAAA,IACnB,IAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA,GAAe,aAAA;AAAA,IACf,WAAA;AAAA,IAC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ACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-TKK7D2ZT.js","sourcesContent":["import { useState, useCallback, useMemo } from \"react\";\nimport {\n keepPreviousData as keepPreviousPlaceholder,\n useQuery,\n useMutation,\n useQueryClient,\n type UseQueryResult,\n type UseMutationResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n Identifier,\n SortParam,\n FilterParam,\n ListParams,\n ListResult,\n InvalidationKey,\n WriteEvent,\n} from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\nimport { DataWriteError, isDataWriteError, NO_ROWS_MATCHED } from \"../schema/write-outcome\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceOptions<T> extends MutationModeOptions {\n defaultSort?: SortParam;\n /**\n * Re-synced whenever its value changes (deep-equal, order-independent),\n * not just its identity — safe to pass a scope/audience-derived array that\n * changes across renders. This only covers CHANGES on an already-mounted\n * hook, though: if this starts `undefined` while the real value resolves\n * asynchronously, gate `enabled` on that same readiness signal too — the\n * hook cannot tell \"no defaultFilters intended\" apart from \"not resolved\n * yet,\" so an ungated hook's very first fetch can still run unscoped.\n */\n defaultFilters?: FilterParam[];\n defaultPerPage?: number;\n /** The page to start on (from 1), e.g. restored from the URL. Default 1. */\n defaultPage?: number;\n /** The search to start with, e.g. restored from the URL. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Fields to search across when setSearch is called. Required for server-side search. */\n searchFields?: string[];\n /** Disable auto-fetching. */\n enabled?: boolean;\n /**\n * Other query keys to invalidate after a create, update or delete, on top\n * of `[resource]` and the provider's own `invalidates` (e.g. `[[\"me\"]]`\n * when a write changes the signed-in user's roles).\n */\n invalidates?: InvalidationKey[];\n /**\n * While the next page / sort / search is loading, keep returning the\n * previous result (`list.isPlaceholderData` is true meanwhile) instead of\n * dropping to `undefined`. A paged list then stays on screen between pages\n * rather than flashing a skeleton. Default false.\n */\n keepPreviousData?: boolean;\n /**\n * Keep the list current while mounted: subscribe to the provider's change\n * events (`DataProvider.subscribe`) and refetch this resource's cached\n * reads (lists and records) when it reports one, once per burst of\n * events. Events are hints: rows always come from the provider's normal\n * read. Pending optimistic and undoable writes stay applied over the\n * refetch. Needs a provider that serves `subscribe` for the resource\n * (`capabilities(resource).realtime`); otherwise it does nothing. Off by\n * default.\n */\n live?: boolean | LiveOptions;\n /**\n * After the write commits, with the provider's row. In `optimistic` and\n * `undoable` modes that is after `create` / `update` / `remove` have\n * already resolved.\n */\n onCreateSuccess?: (data: T) => void;\n onUpdateSuccess?: (data: T) => void;\n onDeleteSuccess?: () => void;\n /**\n * A write failed. In `optimistic` and `undoable` modes this is the only\n * place a failure is reported (the cache has already been put back), so\n * show it to the user here.\n */\n onError?: (error: Error) => void;\n}\n\n/** What `update` can take beside the change. */\nexport interface UpdateOptions {\n /**\n * Check the write against this version instead of the cached row's: \"keep mine\" after a\n * conflict, at the version the conflict reported (`WriteConflict.currentVersion`). A version\n * already chained for the row wins over it: a write sent while an earlier write of the same row\n * is still in flight is checked against the version that one commits (as\n * `ExecuteWriteArgs.expectedVersion`). The write\n * still goes through the resource's write path (queued behind any other write of the row, its\n * committed version recorded), so a move made right after it is checked against it.\n */\n expectedVersion?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Return type\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceReturn<T> {\n /** TanStack Query result for the list query. */\n list: UseQueryResult<ListResult<T>>;\n /** Current list params (pagination, sort, filters, search). */\n params: ListParams;\n setSort: (sort: SortParam | undefined) => void;\n setFilters: (filters: FilterParam[]) => void;\n setPage: (page: number) => void;\n setPerPage: (perPage: number) => void;\n setSearch: (query: string) => void;\n /**\n * Create a new record. Returns the created item. In `optimistic` and\n * `undoable` modes it resolves at once with the values given (no `id` yet;\n * `onCreateSuccess` gets the stored row).\n */\n create: (data: Partial<T>) => Promise<T>;\n /**\n * Update an existing record by id. Returns the updated item. In\n * `optimistic` and `undoable` modes it resolves at once with the cached\n * row merged with `data`.\n */\n update: (id: Identifier, data: Partial<T>, options?: UpdateOptions) => Promise<T>;\n /** Delete a record by id. Resolves at once in `optimistic` / `undoable` modes. */\n remove: (id: Identifier) => Promise<void>;\n /** True when any mutation is in-flight. */\n isMutating: boolean;\n createMutation: UseMutationResult<T, Error, Partial<T>>;\n updateMutation: UseMutationResult<T, Error, { id: Identifier; data: Partial<T>; options?: UpdateOptions }>;\n deleteMutation: UseMutationResult<void, Error, Identifier>;\n}\n\n// ---------------------------------------------------------------------------\n// Filter identity — a deep-equality key independent of object-key order, so\n// a caller that rebuilds the same logical filters via a differently-ordered\n// spread (e.g. `{...base, operator: \"eq\"}` vs `{operator: \"eq\", ...base}`)\n// doesn't trip a spurious resync + pagination reset on an unrelated rerender.\n// ---------------------------------------------------------------------------\n\nfunction stableFilterKey(filters: FilterParam[] | undefined): string | undefined {\n if (!filters) return undefined;\n return JSON.stringify(\n filters.map((f) => {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(f).sort()) {\n sorted[key] = (f as unknown as Record<string, unknown>)[key];\n }\n return sorted;\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseResourceOptions<T> = {},\n): UseResourceReturn<T> {\n const {\n defaultSort,\n defaultFilters,\n defaultPerPage = 25,\n defaultPage = 1,\n defaultSearch = \"\",\n select,\n searchFields: searchFieldsOption,\n enabled = true,\n invalidates,\n keepPreviousData = false,\n live,\n onCreateSuccess,\n onUpdateSuccess,\n onDeleteSuccess,\n onError,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n } = options;\n\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n\n // -------------------------------------------------------------------------\n // State\n // -------------------------------------------------------------------------\n\n const [sort, setSortRaw] = useState<SortParam | undefined>(defaultSort);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [page, setPage] = useState(Math.max(1, Math.floor(defaultPage)));\n const [perPage, setPerPageRaw] = useState(defaultPerPage);\n const [searchQuery, setSearchQuery] = useState(defaultSearch);\n\n // `defaultFilters` often resolves asynchronously — a caller's scope/audience\n // (team, project, ...) can still be loading on first render, so the array\n // it passes in changes value (not just identity) after mount, and may later\n // clear back to undefined (e.g. the scope itself is cleared). Re-syncing\n // here, during render rather than in an effect, means `filters` is already\n // correct by the time `params`/`list` below compute for this pass — no\n // stray unscoped fetch on the frame before an effect would have caught up.\n //\n // This only closes the gap for `defaultFilters` CHANGING across renders on\n // an already-mounted, already-enabled hook (e.g. a scope switch). It cannot\n // help the very first render: `filters` still seeds from whatever\n // `defaultFilters` is on mount, and `undefined` here is genuinely ambiguous\n // between \"this caller never uses defaultFilters\" (in which case forcing a\n // fetch to wait would break it forever) and \"the real value hasn't resolved\n // yet.\" A caller in the second case MUST also gate `enabled` on that same\n // readiness signal for its very first fetch to be correctly scoped — this\n // hook has no way to tell the two cases apart on its own.\n const defaultFiltersKey = stableFilterKey(defaultFilters);\n const [syncedFiltersKey, setSyncedFiltersKey] = useState(defaultFiltersKey);\n if (defaultFiltersKey !== syncedFiltersKey) {\n setSyncedFiltersKey(defaultFiltersKey);\n setFiltersRaw(defaultFilters ?? []);\n setPage(1);\n }\n\n const setSort = useCallback((s: SortParam | undefined) => {\n setSortRaw(s);\n setPage(1);\n }, []);\n\n const setFilters = useCallback((f: FilterParam[]) => {\n setFiltersRaw(f);\n setPage(1);\n }, []);\n\n const setPerPage = useCallback((value: number) => {\n setPerPageRaw(value);\n setPage(1);\n }, []);\n\n const setSearch = useCallback((query: string) => {\n setSearchQuery(query);\n setPage(1);\n }, []);\n\n // -------------------------------------------------------------------------\n // Params\n // -------------------------------------------------------------------------\n\n const params = useMemo<ListParams>(() => {\n const p: ListParams = {\n pagination: { page, perPage },\n sort,\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (searchQuery && searchFieldsOption && searchFieldsOption.length > 0) {\n p.search = { query: searchQuery, fields: searchFieldsOption };\n }\n return p;\n }, [page, perPage, sort, filters, select, searchQuery, searchFieldsOption]);\n\n // -------------------------------------------------------------------------\n // List query\n // -------------------------------------------------------------------------\n\n const listQueryKey = useMemo(\n () => resourceKeys(resource).list(params),\n [resource, params],\n );\n\n const list = useQuery<ListResult<T>>({\n queryKey: listQueryKey,\n queryFn: () => provider.getList<T>(resource, params),\n enabled,\n placeholderData: keepPreviousData ? keepPreviousPlaceholder : undefined,\n });\n\n // Every cached read of the resource: its lists, and the records a peek or\n // detail page shows from it.\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // -------------------------------------------------------------------------\n // Mutations\n // -------------------------------------------------------------------------\n\n const invalidateAfter = useCallback(\n (event: WriteEvent) => {\n // Pending optimistic/undoable patches are re-applied to the refetch.\n void invalidateResource(queryClient, resource);\n for (const queryKey of relatedKeys(provider, event, invalidates)) {\n void queryClient.invalidateQueries({ queryKey: [...queryKey] });\n }\n },\n [queryClient, resource, provider, invalidates],\n );\n\n const defaultOnError = useCallback(\n (error: Error) => {\n // A conflict is an outcome the caller shows (a conflict sheet), not a failure to log.\n if (isDataWriteError(error) && error.outcome === \"conflict\" && error.current) return;\n console.error(`[useResource] ${resource} mutation failed:`, error.message);\n },\n [resource],\n );\n const reportError = onError ?? defaultOnError;\n\n const modeArgs = {\n queryClient,\n provider,\n resource,\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n failedLater: reportError,\n };\n\n const createMutation = useMutation<T, Error, Partial<T>>({\n mutationFn: async (data) => {\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"create\",\n data: data as Record<string, unknown>,\n send: async ({ keepalive }) => {\n const result = await provider.create<T>(resource, { data, ...(keepalive ? { keepalive } : {}) });\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"create\", id: record.id, record });\n onCreateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\" ? outcome.record : (data as T);\n },\n onError: reportError,\n });\n\n const updateMutation = useMutation<\n T,\n Error,\n { id: Identifier; data: Partial<T>; options?: UpdateOptions }\n >({\n mutationFn: async ({ id, data, options }) => {\n const before = cachedRecord(queryClient, resource, id);\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"update\",\n id,\n data: data as Record<string, unknown>,\n ...(options?.expectedVersion !== undefined ? { expectedVersion: options.expectedVersion } : {}),\n send: async (ctx) => {\n const result = await provider.update<T>(resource, {\n id,\n data: (ctx.data ?? data) as Partial<T>,\n ...(ctx.keepalive ? { keepalive: true } : {}),\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n // A write that matched no rows didn't save, whatever provider says so this way: it fails\n // here, before it counts as committed, so it never reads as a silent success.\n if (result.data === null || result.data === undefined) {\n throw new DataWriteError(\"forbidden\", \"This change wasn't saved: no row matched it.\", { code: NO_ROWS_MATCHED });\n }\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"update\", id, record });\n onUpdateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\"\n ? outcome.record\n : ({ ...(before ?? {}), ...data, id: before?.id ?? id } as T);\n },\n onError: reportError,\n });\n\n const deleteMutation = useMutation<void, Error, Identifier>({\n mutationFn: async (id) => {\n await executeWrite<void>({\n ...modeArgs,\n kind: \"delete\",\n id,\n send: async ({ keepalive, expectedVersion }) => {\n const result = await provider.deleteOne(resource, {\n id,\n ...(keepalive ? { keepalive } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n });\n return { record: undefined, audit: result?.audit };\n },\n committed: () => {\n invalidateAfter({ resource, kind: \"delete\", id });\n onDeleteSuccess?.();\n },\n });\n },\n onError: reportError,\n });\n\n // -------------------------------------------------------------------------\n // Convenience wrappers\n // -------------------------------------------------------------------------\n\n const create = useCallback(\n (data: Partial<T>) => createMutation.mutateAsync(data),\n [createMutation],\n );\n\n const update = useCallback(\n (id: Identifier, data: Partial<T>, options?: UpdateOptions) =>\n updateMutation.mutateAsync(options ? { id, data, options } : { id, data }),\n [updateMutation],\n );\n\n const remove = useCallback(\n (id: Identifier) => deleteMutation.mutateAsync(id),\n [deleteMutation],\n );\n\n const isMutating =\n createMutation.isPending ||\n updateMutation.isPending ||\n deleteMutation.isPending;\n\n return {\n list,\n params,\n setSort,\n setFilters,\n setPage,\n setPerPage,\n setSearch,\n create,\n update,\n remove,\n isMutating,\n createMutation,\n updateMutation,\n deleteMutation,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-resource.ts"],"names":["keepPreviousData","keepPreviousPlaceholder","options"],"mappings":";;;;;;;;;AA0JA,SAAS,gBAAgB,OAAA,EAAwD;AAC/E,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACV,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM;AACjB,MAAA,MAAM,SAAkC,EAAC;AACzC,MAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAK,EAAG;AACvC,QAAA,MAAA,CAAO,GAAG,CAAA,GAAK,CAAA,CAAyC,GAAG,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC;AAAA,GACH;AACF;AAMO,SAAS,WAAA,CACd,Q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EAAgB,IAAA,EAAkBA,QAAAA,KACjC,cAAA,CAAe,YAAYA,QAAAA,GAAU,EAAE,EAAA,EAAI,IAAA,EAAM,SAAAA,QAAAA,EAAQ,GAAI,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,IAC3E,CAAC,cAAc;AAAA,GACjB;AAEA,EAAA,MAAM,MAAA,GAAS,WAAA;AAAA,IACb,CAAC,EAAA,KAAmB,cAAA,CAAe,WAAA,CAAY,EAAE,CAAA;AAAA,IACjD,CAAC,cAAc;AAAA,GACjB;AAEA,EAAA,MAAM,UAAA,GACJ,cAAA,CAAe,SAAA,IACf,cAAA,CAAe,aACf,cAAA,CAAe,SAAA;AAEjB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-ALLWIK62.js","sourcesContent":["import { useState, useCallback, useMemo } from \"react\";\nimport {\n keepPreviousData as keepPreviousPlaceholder,\n useQuery,\n useMutation,\n useQueryClient,\n type UseQueryResult,\n type UseMutationResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n Identifier,\n SortParam,\n FilterParam,\n ListParams,\n ListResult,\n InvalidationKey,\n WriteEvent,\n} from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\nimport { DataWriteError, isDataWriteError, NO_ROWS_MATCHED } from \"../schema/write-outcome\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceOptions<T> extends MutationModeOptions {\n defaultSort?: SortParam;\n /**\n * Re-synced whenever its value changes (deep-equal, order-independent),\n * not just its identity — safe to pass a scope/audience-derived array that\n * changes across renders. This only covers CHANGES on an already-mounted\n * hook, though: if this starts `undefined` while the real value resolves\n * asynchronously, gate `enabled` on that same readiness signal too — the\n * hook cannot tell \"no defaultFilters intended\" apart from \"not resolved\n * yet,\" so an ungated hook's very first fetch can still run unscoped.\n */\n defaultFilters?: FilterParam[];\n defaultPerPage?: number;\n /** The page to start on (from 1), e.g. restored from the URL. Default 1. */\n defaultPage?: number;\n /** The search to start with, e.g. restored from the URL. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Fields to search across when setSearch is called. Required for server-side search. */\n searchFields?: string[];\n /** Disable auto-fetching. */\n enabled?: boolean;\n /**\n * Other query keys to invalidate after a create, update or delete, on top\n * of `[resource]` and the provider's own `invalidates` (e.g. `[[\"me\"]]`\n * when a write changes the signed-in user's roles).\n */\n invalidates?: InvalidationKey[];\n /**\n * While the next page / sort / search is loading, keep returning the\n * previous result (`list.isPlaceholderData` is true meanwhile) instead of\n * dropping to `undefined`. A paged list then stays on screen between pages\n * rather than flashing a skeleton. Default false.\n */\n keepPreviousData?: boolean;\n /**\n * Keep the list current while mounted: subscribe to the provider's change\n * events (`DataProvider.subscribe`) and refetch this resource's cached\n * reads (lists and records) when it reports one, once per burst of\n * events. Events are hints: rows always come from the provider's normal\n * read. Pending optimistic and undoable writes stay applied over the\n * refetch. Needs a provider that serves `subscribe` for the resource\n * (`capabilities(resource).realtime`); otherwise it does nothing. Off by\n * default.\n */\n live?: boolean | LiveOptions;\n /**\n * After the write commits, with the provider's row. In `optimistic` and\n * `undoable` modes that is after `create` / `update` / `remove` have\n * already resolved.\n */\n onCreateSuccess?: (data: T) => void;\n onUpdateSuccess?: (data: T) => void;\n onDeleteSuccess?: () => void;\n /**\n * A write failed. In `optimistic` and `undoable` modes this is the only\n * place a failure is reported (the cache has already been put back), so\n * show it to the user here.\n */\n onError?: (error: Error) => void;\n}\n\n/** What `update` can take beside the change. */\nexport interface UpdateOptions {\n /**\n * Check the write against this version instead of the cached row's: \"keep mine\" after a\n * conflict, at the version the conflict reported (`WriteConflict.currentVersion`). A version\n * already chained for the row wins over it: a write sent while an earlier write of the same row\n * is still in flight is checked against the version that one commits (as\n * `ExecuteWriteArgs.expectedVersion`). The write\n * still goes through the resource's write path (queued behind any other write of the row, its\n * committed version recorded), so a move made right after it is checked against it.\n */\n expectedVersion?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Return type\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceReturn<T> {\n /** TanStack Query result for the list query. */\n list: UseQueryResult<ListResult<T>>;\n /** Current list params (pagination, sort, filters, search). */\n params: ListParams;\n setSort: (sort: SortParam | undefined) => void;\n setFilters: (filters: FilterParam[]) => void;\n setPage: (page: number) => void;\n setPerPage: (perPage: number) => void;\n setSearch: (query: string) => void;\n /**\n * Create a new record. Returns the created item. In `optimistic` and\n * `undoable` modes it resolves at once with the values given (no `id` yet;\n * `onCreateSuccess` gets the stored row).\n */\n create: (data: Partial<T>) => Promise<T>;\n /**\n * Update an existing record by id. Returns the updated item. In\n * `optimistic` and `undoable` modes it resolves at once with the cached\n * row merged with `data`.\n */\n update: (id: Identifier, data: Partial<T>, options?: UpdateOptions) => Promise<T>;\n /** Delete a record by id. Resolves at once in `optimistic` / `undoable` modes. */\n remove: (id: Identifier) => Promise<void>;\n /** True when any mutation is in-flight. */\n isMutating: boolean;\n createMutation: UseMutationResult<T, Error, Partial<T>>;\n updateMutation: UseMutationResult<T, Error, { id: Identifier; data: Partial<T>; options?: UpdateOptions }>;\n deleteMutation: UseMutationResult<void, Error, Identifier>;\n}\n\n// ---------------------------------------------------------------------------\n// Filter identity — a deep-equality key independent of object-key order, so\n// a caller that rebuilds the same logical filters via a differently-ordered\n// spread (e.g. `{...base, operator: \"eq\"}` vs `{operator: \"eq\", ...base}`)\n// doesn't trip a spurious resync + pagination reset on an unrelated rerender.\n// ---------------------------------------------------------------------------\n\nfunction stableFilterKey(filters: FilterParam[] | undefined): string | undefined {\n if (!filters) return undefined;\n return JSON.stringify(\n filters.map((f) => {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(f).sort()) {\n sorted[key] = (f as unknown as Record<string, unknown>)[key];\n }\n return sorted;\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseResourceOptions<T> = {},\n): UseResourceReturn<T> {\n const {\n defaultSort,\n defaultFilters,\n defaultPerPage = 25,\n defaultPage = 1,\n defaultSearch = \"\",\n select,\n searchFields: searchFieldsOption,\n enabled = true,\n invalidates,\n keepPreviousData = false,\n live,\n onCreateSuccess,\n onUpdateSuccess,\n onDeleteSuccess,\n onError,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n } = options;\n\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n\n // -------------------------------------------------------------------------\n // State\n // -------------------------------------------------------------------------\n\n const [sort, setSortRaw] = useState<SortParam | undefined>(defaultSort);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [page, setPage] = useState(Math.max(1, Math.floor(defaultPage)));\n const [perPage, setPerPageRaw] = useState(defaultPerPage);\n const [searchQuery, setSearchQuery] = useState(defaultSearch);\n\n // `defaultFilters` often resolves asynchronously — a caller's scope/audience\n // (team, project, ...) can still be loading on first render, so the array\n // it passes in changes value (not just identity) after mount, and may later\n // clear back to undefined (e.g. the scope itself is cleared). Re-syncing\n // here, during render rather than in an effect, means `filters` is already\n // correct by the time `params`/`list` below compute for this pass — no\n // stray unscoped fetch on the frame before an effect would have caught up.\n //\n // This only closes the gap for `defaultFilters` CHANGING across renders on\n // an already-mounted, already-enabled hook (e.g. a scope switch). It cannot\n // help the very first render: `filters` still seeds from whatever\n // `defaultFilters` is on mount, and `undefined` here is genuinely ambiguous\n // between \"this caller never uses defaultFilters\" (in which case forcing a\n // fetch to wait would break it forever) and \"the real value hasn't resolved\n // yet.\" A caller in the second case MUST also gate `enabled` on that same\n // readiness signal for its very first fetch to be correctly scoped — this\n // hook has no way to tell the two cases apart on its own.\n const defaultFiltersKey = stableFilterKey(defaultFilters);\n const [syncedFiltersKey, setSyncedFiltersKey] = useState(defaultFiltersKey);\n if (defaultFiltersKey !== syncedFiltersKey) {\n setSyncedFiltersKey(defaultFiltersKey);\n setFiltersRaw(defaultFilters ?? []);\n setPage(1);\n }\n\n const setSort = useCallback((s: SortParam | undefined) => {\n setSortRaw(s);\n setPage(1);\n }, []);\n\n const setFilters = useCallback((f: FilterParam[]) => {\n setFiltersRaw(f);\n setPage(1);\n }, []);\n\n const setPerPage = useCallback((value: number) => {\n setPerPageRaw(value);\n setPage(1);\n }, []);\n\n const setSearch = useCallback((query: string) => {\n setSearchQuery(query);\n setPage(1);\n }, []);\n\n // -------------------------------------------------------------------------\n // Params\n // -------------------------------------------------------------------------\n\n const params = useMemo<ListParams>(() => {\n const p: ListParams = {\n pagination: { page, perPage },\n sort,\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (searchQuery && searchFieldsOption && searchFieldsOption.length > 0) {\n p.search = { query: searchQuery, fields: searchFieldsOption };\n }\n return p;\n }, [page, perPage, sort, filters, select, searchQuery, searchFieldsOption]);\n\n // -------------------------------------------------------------------------\n // List query\n // -------------------------------------------------------------------------\n\n const listQueryKey = useMemo(\n () => resourceKeys(resource).list(params),\n [resource, params],\n );\n\n const list = useQuery<ListResult<T>>({\n queryKey: listQueryKey,\n queryFn: () => provider.getList<T>(resource, params),\n enabled,\n placeholderData: keepPreviousData ? keepPreviousPlaceholder : undefined,\n });\n\n // Every cached read of the resource: its lists, and the records a peek or\n // detail page shows from it.\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // -------------------------------------------------------------------------\n // Mutations\n // -------------------------------------------------------------------------\n\n const invalidateAfter = useCallback(\n (event: WriteEvent) => {\n // Pending optimistic/undoable patches are re-applied to the refetch.\n void invalidateResource(queryClient, resource);\n for (const queryKey of relatedKeys(provider, event, invalidates)) {\n void queryClient.invalidateQueries({ queryKey: [...queryKey] });\n }\n },\n [queryClient, resource, provider, invalidates],\n );\n\n const defaultOnError = useCallback(\n (error: Error) => {\n // A conflict is an outcome the caller shows (a conflict sheet), not a failure to log.\n if (isDataWriteError(error) && error.outcome === \"conflict\" && error.current) return;\n console.error(`[useResource] ${resource} mutation failed:`, error.message);\n },\n [resource],\n );\n const reportError = onError ?? defaultOnError;\n\n const modeArgs = {\n queryClient,\n provider,\n resource,\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n failedLater: reportError,\n };\n\n const createMutation = useMutation<T, Error, Partial<T>>({\n mutationFn: async (data) => {\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"create\",\n data: data as Record<string, unknown>,\n send: async ({ keepalive }) => {\n const result = await provider.create<T>(resource, { data, ...(keepalive ? { keepalive } : {}) });\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"create\", id: record.id, record });\n onCreateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\" ? outcome.record : (data as T);\n },\n onError: reportError,\n });\n\n const updateMutation = useMutation<\n T,\n Error,\n { id: Identifier; data: Partial<T>; options?: UpdateOptions }\n >({\n mutationFn: async ({ id, data, options }) => {\n const before = cachedRecord(queryClient, resource, id);\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"update\",\n id,\n data: data as Record<string, unknown>,\n ...(options?.expectedVersion !== undefined ? { expectedVersion: options.expectedVersion } : {}),\n send: async (ctx) => {\n const result = await provider.update<T>(resource, {\n id,\n data: (ctx.data ?? data) as Partial<T>,\n ...(ctx.keepalive ? { keepalive: true } : {}),\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n // A write that matched no rows didn't save, whatever provider says so this way: it fails\n // here, before it counts as committed, so it never reads as a silent success.\n if (result.data === null || result.data === undefined) {\n throw new DataWriteError(\"forbidden\", \"This change wasn't saved: no row matched it.\", { code: NO_ROWS_MATCHED });\n }\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"update\", id, record });\n onUpdateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\"\n ? outcome.record\n : ({ ...(before ?? {}), ...data, id: before?.id ?? id } as T);\n },\n onError: reportError,\n });\n\n const deleteMutation = useMutation<void, Error, Identifier>({\n mutationFn: async (id) => {\n await executeWrite<void>({\n ...modeArgs,\n kind: \"delete\",\n id,\n send: async ({ keepalive, expectedVersion }) => {\n const result = await provider.deleteOne(resource, {\n id,\n ...(keepalive ? { keepalive } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n });\n return { record: undefined, audit: result?.audit };\n },\n committed: () => {\n invalidateAfter({ resource, kind: \"delete\", id });\n onDeleteSuccess?.();\n },\n });\n },\n onError: reportError,\n });\n\n // -------------------------------------------------------------------------\n // Convenience wrappers\n // -------------------------------------------------------------------------\n\n const create = useCallback(\n (data: Partial<T>) => createMutation.mutateAsync(data),\n [createMutation],\n );\n\n const update = useCallback(\n (id: Identifier, data: Partial<T>, options?: UpdateOptions) =>\n updateMutation.mutateAsync(options ? { id, data, options } : { id, data }),\n [updateMutation],\n );\n\n const remove = useCallback(\n (id: Identifier) => deleteMutation.mutateAsync(id),\n [deleteMutation],\n );\n\n const isMutating =\n createMutation.isPending ||\n updateMutation.isPending ||\n deleteMutation.isPending;\n\n return {\n list,\n params,\n setSort,\n setFilters,\n setPage,\n setPerPage,\n setSearch,\n create,\n update,\n remove,\n isMutating,\n createMutation,\n updateMutation,\n deleteMutation,\n };\n}\n"]}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { matchesQuery } from './chunk-BDPRWVFW.js';
|
|
2
|
+
|
|
1
3
|
// src/appearance-values.ts
|
|
2
4
|
var APPEARANCES = Object.freeze(["system", "light", "dark"]);
|
|
3
5
|
var DENSITIES = Object.freeze(["compact", "comfortable", "spacious"]);
|
|
@@ -105,20 +107,24 @@ function workspaceInitials(label) {
|
|
|
105
107
|
return letters.join("").toUpperCase();
|
|
106
108
|
}
|
|
107
109
|
function filterWorkspaces(workspaces, query) {
|
|
108
|
-
|
|
109
|
-
if (words.length === 0) return [...workspaces];
|
|
110
|
-
return workspaces.filter((w) => {
|
|
111
|
-
const text = fold(`${w.label} ${w.description ?? ""}`);
|
|
112
|
-
return words.every((word) => text.includes(word));
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
function fold(text) {
|
|
116
|
-
return text.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
|
110
|
+
return workspaces.filter((w) => matchesQuery([w.label, w.description], query));
|
|
117
111
|
}
|
|
118
112
|
function orderedWorkspaces(workspaces, order = WORKSPACE_KIND_ORDER) {
|
|
119
113
|
return groupWorkspaces(workspaces, order).flatMap((g) => g.workspaces);
|
|
120
114
|
}
|
|
115
|
+
var WORKSPACE_SWITCHER_SEARCH_THRESHOLD = 7;
|
|
116
|
+
var DEFAULT_WORKSPACE_KIND_LABELS = {
|
|
117
|
+
personal: "Personal",
|
|
118
|
+
rollup: "Overview",
|
|
119
|
+
tenant: "Organizations"
|
|
120
|
+
};
|
|
121
|
+
function hasWorkspaceBadge(value) {
|
|
122
|
+
return value !== void 0 && value !== null && value !== "" && value !== 0;
|
|
123
|
+
}
|
|
124
|
+
function workspaceBadgeLabel(_workspace, value) {
|
|
125
|
+
return typeof value === "number" ? `${value} new` : String(value);
|
|
126
|
+
}
|
|
121
127
|
|
|
122
|
-
export { APPEARANCES, DENSITIES, GENESIS_APPEARANCE_DEFAULTS, WORKSPACE_KIND_ORDER, defaultWorkspace, filterWorkspaces, groupWorkspaces, isAppearance, isDensity, keepSection, orderedWorkspaces, pathInWorkspace, resolveAppearancePreferences, resolveWorkspaceAppearance, resolveWorkspaceBrand, toAppearancePreferenceValues, workspaceAt, workspaceHref, workspaceInitials };
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
124
|
-
//# sourceMappingURL=chunk-
|
|
128
|
+
export { APPEARANCES, DEFAULT_WORKSPACE_KIND_LABELS, DENSITIES, GENESIS_APPEARANCE_DEFAULTS, WORKSPACE_KIND_ORDER, WORKSPACE_SWITCHER_SEARCH_THRESHOLD, defaultWorkspace, filterWorkspaces, groupWorkspaces, hasWorkspaceBadge, isAppearance, isDensity, keepSection, orderedWorkspaces, pathInWorkspace, resolveAppearancePreferences, resolveWorkspaceAppearance, resolveWorkspaceBrand, toAppearancePreferenceValues, workspaceAt, workspaceBadgeLabel, workspaceHref, workspaceInitials };
|
|
129
|
+
//# sourceMappingURL=chunk-APFXV6FZ.js.map
|
|
130
|
+
//# sourceMappingURL=chunk-APFXV6FZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/appearance-values.ts","../src/workspaces.ts"],"names":[],"mappings":";;;AAeO,IAAM,cAAqC,MAAA,CAAO,MAAA,CAAO,CAAC,QAAA,EAAU,OAAA,EAAS,MAAM,CAAC;AAEpF,IAAM,YAAgC,MAAA,CAAO,MAAA,CAAO,CAAC,SAAA,EAAW,aAAA,EAAe,UAAU,CAAC;AAS1F,IAAM,2BAAA,GAA8E,OAAO,MAAA,CAAO;AAAA,EACvG,UAAA,EAAY,QAAA;AAAA,EACZ,OAAA,EAAS;AACX,CAAC;AAyBM,IAAM,eAAe,CAAC,CAAA,KAAgC,MAAM,OAAA,IAAW,CAAA,KAAM,UAAU,CAAA,KAAM;AAE7F,IAAM,YAAY,CAAC,CAAA,KAA6B,MAAM,SAAA,IAAa,CAAA,KAAM,iBAAiB,CAAA,KAAM;AAGhG,SAAS,6BAA6B,KAAA,EAA4C;AACvF,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,SAAiB,EAAC;AACjD,EAAA,MAAM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,GAAkF;AAAA,EAC7F,QAAA,EAAU,UAAA;AAAA,EACV,MAAA,EAAQ,UAAA;AAAA,EACR,MAAA,EAAQ;AACV;AAGO,SAAS,kBAAkB,KAAA,EAAqD;AACrF,EAAA,OAAO,UAAU,MAAA,IAAa,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAM,KAAA,KAAU,CAAA;AAC5E;AAGO,SAAS,mBAAA,CAAoB,YAAuB,KAAA,EAAgC;AACzF,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,GAAG,KAAK,CAAA,IAAA,CAAA,GAAS,OAAO,KAAK,CAAA;AAClE","file":"chunk-APFXV6FZ.js","sourcesContent":["/**\n * Appearance preferences, as data (ADR 0024): the values and the order that decides which one\n * applies. No React, so a server, a phone or `workspaces.ts` can use it; the provider is\n * `appearance.tsx`.\n *\n * app lock > person > organization default > theme default > Genesis default\n */\n\n/** Light, dark, or follow the device: the person's appearance. */\nexport type Appearance = \"light\" | \"dark\" | \"system\";\n\n/** How tightly rows and controls sit. */\nexport type Density = \"compact\" | \"comfortable\" | \"spacious\";\n\n/** The appearances, in a picker's order. */\nexport const APPEARANCES: readonly Appearance[] = Object.freeze([\"system\", \"light\", \"dark\"]);\n/** The densities, tightest first. */\nexport const DENSITIES: readonly Density[] = Object.freeze([\"compact\", \"comfortable\", \"spacious\"]);\n\n/** An appearance and a density, either of which may be unset. */\nexport interface AppearancePreferenceValues {\n appearance?: Appearance | undefined;\n density?: Density | undefined;\n}\n\n/** Genesis's own defaults, the last step of the order. */\nexport const GENESIS_APPEARANCE_DEFAULTS: Readonly<Required<AppearancePreferenceValues>> = Object.freeze({\n appearance: \"system\",\n density: \"comfortable\",\n});\n\n/** Where a resolved value came from. */\nexport type AppearancePreferenceSource = \"app\" | \"person\" | \"organization\" | \"theme\" | \"genesis\";\n\n/** Each layer of the order; any may be missing. */\nexport interface AppearancePreferenceLayers {\n /** The app's lock: a value set here can't be changed by anyone below it. */\n lock?: AppearancePreferenceValues | undefined;\n /** The person's own choice. */\n person?: AppearancePreferenceValues | undefined;\n /** The organization's default for its people (`WorkspaceTheme.defaults`). */\n organization?: AppearancePreferenceValues | undefined;\n /** The app theme's default (its layout's density, say). */\n theme?: AppearancePreferenceValues | undefined;\n}\n\n/** The values that apply, and where each came from. */\nexport interface ResolvedAppearancePreferences {\n appearance: Appearance;\n density: Density;\n source: { appearance: AppearancePreferenceSource; density: AppearancePreferenceSource };\n}\n\n/** Whether a value is an appearance. */\nexport const isAppearance = (v: unknown): v is Appearance => v === \"light\" || v === \"dark\" || v === \"system\";\n/** Whether a value is a density. */\nexport const isDensity = (v: unknown): v is Density => v === \"compact\" || v === \"comfortable\" || v === \"spacious\";\n\n/** Only the known values: a stored or typed-in value that isn't one is left out. */\nexport function toAppearancePreferenceValues(input: unknown): AppearancePreferenceValues {\n if (!input || typeof input !== \"object\") return {};\n const { appearance, density } = input as Record<string, unknown>;\n return { ...(isAppearance(appearance) ? { appearance } : {}), ...(isDensity(density) ? { density } : {}) };\n}\n\n/**\n * The appearance and density that apply: app lock, then the person, then the organization's\n * default, then the theme's, then Genesis's. Values that aren't known appearances or densities\n * are skipped, so a bad stored value falls through to the next layer.\n *\n * @stability Beta\n */\nexport function resolveAppearancePreferences(layers: AppearancePreferenceLayers): ResolvedAppearancePreferences {\n const order: [AppearancePreferenceSource, AppearancePreferenceValues | undefined][] = [\n [\"app\", layers.lock],\n [\"person\", layers.person],\n [\"organization\", layers.organization],\n [\"theme\", layers.theme],\n [\"genesis\", GENESIS_APPEARANCE_DEFAULTS],\n ];\n const pick = <K extends keyof AppearancePreferenceValues>(key: K, valid: (v: unknown) => boolean) => {\n for (const [source, values] of order) {\n const value = values?.[key];\n if (valid(value)) return { value: value as NonNullable<AppearancePreferenceValues[K]>, source };\n }\n return { value: GENESIS_APPEARANCE_DEFAULTS[key] as NonNullable<AppearancePreferenceValues[K]>, source: \"genesis\" as const };\n };\n const appearance = pick(\"appearance\", isAppearance);\n const density = pick(\"density\", isDensity);\n return {\n appearance: appearance.value as Appearance,\n density: density.value as Density,\n source: { appearance: appearance.source, density: density.source },\n };\n}\n\n","/**\n * Workspaces (docs/adr/0004-workspaces.md): where the viewer is working, chosen first and kept in\n * the URL. A workspace is one tenant (an organization), the roll-up across them, or the viewer's\n * own personal space. Everything inside it is scoped to it: its `scope` is the `ResourceScope`\n * every view reads, and its path prefixes every URL inside it.\n *\n * Router-free and DOM-free, like `navigation`: web and native shells share it.\n */\n\nimport type { ResourceScope } from \"./hooks/viewer-scope\";\nimport type { GenesisViewerRoles } from \"./viewer\";\nimport { matchesQuery } from \"./headless/text\";\nimport { toAppearancePreferenceValues, type AppearancePreferenceValues } from \"./appearance-values\";\n\n/**\n * The kinds of workspace. Genesis ships three; an app adds its own by module augmentation, and\n * the switcher groups and orders them like the built-in ones:\n *\n * ```ts\n * declare module \"@marktiderman/genesis-core/workspaces\" {\n * interface GenesisWorkspaceKinds {\n * location: true;\n * }\n * }\n * ```\n *\n * @stability Beta\n */\nexport interface GenesisWorkspaceKinds {\n /** One tenant: an organization the viewer is a member or staff of. */\n tenant: true;\n /** The roll-up across every tenant the viewer works in. */\n rollup: true;\n /** The viewer's own things, belonging to no tenant. */\n personal: true;\n}\n\n/** @stability Beta */\nexport type WorkspaceKind = keyof GenesisWorkspaceKinds;\n\n/**\n * One place the viewer can work in.\n *\n * @stability Beta\n */\nexport interface Workspace {\n /** Unique among the viewer's workspaces. For a tenant, usually its URL segment. */\n id: string;\n kind: WorkspaceKind;\n /** Its name: the organization's name, \"All organizations\", \"Personal\". */\n label: string;\n /** A second line in the switcher: the viewer's role there, a location. */\n description?: string;\n /**\n * Where it starts, and the prefix of every URL inside it: `/o/acme`, `/all`, `/me`. Matched at\n * segment boundaries, so `/o/acme` never matches `/o/acme-west`.\n */\n path: string;\n /** What views read inside it: `{ orgId }`, `{ orgId: [...] }`, `{ personId }`. */\n scope: ResourceScope;\n /** The viewer's roles here, for view guards (see `GenesisViewerRoles`). */\n roles?: GenesisViewerRoles;\n /** The workspace's IANA time zone, for columns read on the scope's clock. */\n timeZone?: string | null;\n /** Its picture: a logo URL, else initials made from `label`. */\n image?: string;\n /**\n * A count or short status beside it in the switcher: unread messages, tasks waiting. `0`, an\n * empty string, `null` and undefined show nothing.\n */\n badge?: string | number | null;\n /** Its brand, for the switcher's picture and anything the app themes inside it. */\n theme?: WorkspaceTheme;\n /** Anything else the app needs; Genesis never reads it. */\n meta?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * A workspace's brand. `accent` takes the same values as a public page's brand accent (`#rgb`,\n * `#rrggbb`, `rgb()`, `hsl()` or a bare token triplet like `\"160 84% 39%\"`); genesis-ui turns it\n * into the design system's `--primary` (`workspaceThemeStyle`), darkened when it is too light to\n * carry text.\n *\n * @stability Beta\n */\nexport interface WorkspaceTheme {\n accent?: string;\n /**\n * The app brand this organization wears, by id (`defineAppBrand`'s name, what\n * `data-app-brand` names): its colours and typefaces across the app while the workspace is\n * active. `resolveWorkspaceBrand` picks it, checked against the brands the app ships.\n */\n brand?: string;\n /**\n * The organization's defaults for its people's appearance and density. A person's own choice\n * wins over them, and the app's lock over that (`resolveAppearancePreferences`).\n */\n defaults?: AppearancePreferenceValues;\n}\n\n/**\n * The app brand that applies in a workspace: its `theme.brand` when the app ships a brand by\n * that id (`available`, ids or anything with an `id`), else `fallback`. Without `available`,\n * any brand id is taken as given.\n *\n * ```ts\n * const brand = resolveWorkspaceBrand(active, { available: STARTER_BRANDS, fallback: \"acme\" });\n * document.documentElement.dataset.appBrand = brand;\n * ```\n *\n * @stability Beta\n */\nexport function resolveWorkspaceBrand(\n workspace: Pick<Workspace, \"theme\"> | null | undefined,\n options: { available?: readonly (string | { readonly id: string })[]; fallback?: string } = {},\n): string | undefined {\n const wanted = workspace?.theme?.brand;\n if (wanted) {\n const ids = options.available?.map((b) => (typeof b === \"string\" ? b : b.id));\n if (!ids || ids.includes(wanted)) return wanted;\n if (process.env.NODE_ENV !== \"production\") {\n // genesis-allow-console: a development hint about the app's own data, not a caught error.\n console.warn(`[genesis-core] resolveWorkspaceBrand: the workspace asks for brand \"${wanted}\", which the app doesn't ship.`);\n }\n }\n return options.fallback;\n}\n\n/**\n * The organization's appearance and density defaults, for `AppearancePreferencesProvider`'s\n * `organization`: only known values, empty without a workspace.\n *\n * @stability Beta\n */\nexport function resolveWorkspaceAppearance(workspace: Pick<Workspace, \"theme\"> | null | undefined): AppearancePreferenceValues {\n return toAppearancePreferenceValues(workspace?.theme?.defaults);\n}\n\n/** The kinds in their default order: personal, roll-up, then each tenant. */\nexport const WORKSPACE_KIND_ORDER: readonly WorkspaceKind[] = [\"personal\", \"rollup\", \"tenant\"];\n\nfunction trimPath(path: string): string {\n const bare = path.split(/[?#]/)[0] ?? \"\";\n // Trailing slashes off, keeping \"/\" itself. A loop, not /\\/+$/, which is slow on many slashes.\n let end = bare.length;\n while (end > 1 && bare[end - 1] === \"/\") end--;\n return bare.slice(0, end);\n}\n\nfunction within(pathname: string, prefix: string): boolean {\n const p = trimPath(pathname);\n const w = trimPath(prefix);\n if (w === \"/\") return true;\n return p === w || p.startsWith(`${w}/`);\n}\n\n/**\n * The workspace a URL is in: the one whose `path` is the longest prefix of `pathname`, or\n * undefined when the URL is in none (a sign-in page, the app's front door).\n *\n * @stability Beta\n */\nexport function workspaceAt<W extends Workspace>(workspaces: readonly W[], pathname: string): W | undefined {\n let best: W | undefined;\n for (const w of workspaces) {\n if (within(pathname, w.path) && (!best || trimPath(w.path).length > trimPath(best.path).length)) best = w;\n }\n return best;\n}\n\n/**\n * The path inside a workspace: `/o/acme/clients/42` in `/o/acme` is `/clients/42`; the workspace's\n * own landing page is `/`.\n *\n * @stability Beta\n */\nexport function pathInWorkspace(workspace: Pick<Workspace, \"path\">, pathname: string): string {\n const w = trimPath(workspace.path);\n const p = trimPath(pathname);\n if (!within(p, w)) return \"/\";\n const rest = w === \"/\" ? p : p.slice(w.length);\n return rest || \"/\";\n}\n\n/** @stability Beta */\nexport interface WorkspaceHrefOptions {\n /**\n * Whether to keep the viewer's place when switching: given the path inside the current\n * workspace (`/clients`) and the two workspaces, return the path to open in the target, or\n * false for its landing page. By default the place is kept between workspaces of the same kind,\n * up to the first segment (a list, not one record that belongs to the old workspace):\n * `/o/acme/clients/42` switches to `/o/globex/clients`.\n */\n keep?: (rest: string, from: Workspace, to: Workspace) => string | false;\n}\n\n/** The default `keep`: the same kind keeps the section (the first segment), never a record. */\nexport function keepSection(rest: string, from: Workspace, to: Workspace): string | false {\n if (from.kind !== to.kind) return false;\n const section = rest.split(\"/\").filter(Boolean)[0];\n return section ? `/${section}` : false;\n}\n\n/**\n * Where switching to `to` goes from `pathname`. The URL moves with the viewer: it lands in the same\n * section of the new workspace when that makes sense (see `keep`), else on its landing page.\n *\n * @stability Beta\n */\nexport function workspaceHref(\n workspaces: readonly Workspace[],\n to: Workspace,\n pathname: string | undefined,\n options: WorkspaceHrefOptions = {},\n): string {\n const from = pathname === undefined ? undefined : workspaceAt(workspaces, pathname);\n if (!from || from.id === to.id || pathname === undefined) return to.path;\n const kept = (options.keep ?? keepSection)(pathInWorkspace(from, pathname), from, to);\n if (!kept || kept === \"/\") return to.path;\n const base = trimPath(to.path);\n return `${base === \"/\" ? \"\" : base}${kept.startsWith(\"/\") ? kept : `/${kept}`}`;\n}\n\n/** @stability Beta */\nexport interface WorkspaceGroup<W extends Workspace = Workspace> {\n kind: WorkspaceKind;\n workspaces: W[];\n}\n\n/**\n * The workspaces grouped by kind, in `order` (default {@link WORKSPACE_KIND_ORDER}, then any kind\n * an app added), each group in the order given. Empty groups are left out.\n *\n * @stability Beta\n */\nexport function groupWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): WorkspaceGroup<W>[] {\n const kinds = [...order];\n for (const w of workspaces) if (!kinds.includes(w.kind)) kinds.push(w.kind);\n return kinds\n .map((kind) => ({ kind, workspaces: workspaces.filter((w) => w.kind === kind) }))\n .filter((g) => g.workspaces.length > 0);\n}\n\n/**\n * The workspace to open when the URL names none (the app's front door): the remembered one if the\n * viewer still has it, else the first tenant, else the first workspace.\n *\n * @stability Beta\n */\nexport function defaultWorkspace<W extends Workspace>(workspaces: readonly W[], rememberedId?: string | null): W | undefined {\n return (\n (rememberedId ? workspaces.find((w) => w.id === rememberedId) : undefined) ??\n workspaces.find((w) => w.kind === \"tenant\") ??\n workspaces[0]\n );\n}\n\n/**\n * Initials for a workspace with no image: the first letters of its first two words.\n *\n * @stability Beta\n */\nexport function workspaceInitials(label: string): string {\n const words = label.trim().split(/\\s+/).filter(Boolean);\n const letters = words.length > 1 ? [words[0]![0], words[1]![0]] : [...(words[0] ?? \"\")].slice(0, 2);\n return letters.join(\"\").toUpperCase();\n}\n\n/**\n * The workspaces whose label or second line contains every word of `query`, ignoring case and\n * accents, in the order given. An empty query keeps them all. For the switcher's search box, on\n * the web and on the phone.\n *\n * @stability Beta\n */\nexport function filterWorkspaces<W extends Workspace>(workspaces: readonly W[], query: string): W[] {\n return workspaces.filter((w) => matchesQuery([w.label, w.description], query));\n}\n\n/**\n * The workspaces in the order the switcher lists them (grouped by kind, in `order`): the order its\n * keyboard jump numbers them, 1 to 9.\n *\n * @stability Beta\n */\nexport function orderedWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): W[] {\n return groupWorkspaces(workspaces, order).flatMap((g) => g.workspaces);\n}\n\n/** With a switcher's `search=\"auto\"`, past this many workspaces it opens with a search box. On the web and the phone. */\nexport const WORKSPACE_SWITCHER_SEARCH_THRESHOLD = 7;\n\n/** The default heading over each kind's group in a switcher, on the web and the phone. */\nexport const DEFAULT_WORKSPACE_KIND_LABELS: Readonly<Partial<Record<WorkspaceKind, string>>> = {\n personal: \"Personal\",\n rollup: \"Overview\",\n tenant: \"Organizations\",\n};\n\n/** Whether a workspace's badge shows: `0`, an empty string, `null` and undefined show nothing. */\nexport function hasWorkspaceBadge(value: Workspace[\"badge\"]): value is string | number {\n return value !== undefined && value !== null && value !== \"\" && value !== 0;\n}\n\n/** What a screen reader hears for a badge: \"3 new\" for a number, the text itself otherwise. */\nexport function workspaceBadgeLabel(_workspace: Workspace, value: string | number): string {\n return typeof value === \"number\" ? `${value} new` : String(value);\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/headless/text.ts
|
|
2
|
+
function foldText(text) {
|
|
3
|
+
return text.normalize("NFD").replace(/(\p{Script=Latin})\p{Mn}+/gu, (_, base) => base).normalize("NFC").toLowerCase();
|
|
4
|
+
}
|
|
5
|
+
function matchesQuery(texts, query) {
|
|
6
|
+
const words = foldText(query).split(/\s+/).filter(Boolean);
|
|
7
|
+
if (words.length === 0) return true;
|
|
8
|
+
const haystack = foldText((typeof texts === "string" ? [texts] : texts).filter(Boolean).join(" "));
|
|
9
|
+
return words.every((word) => haystack.includes(word));
|
|
10
|
+
}
|
|
11
|
+
function filterOptions(options, query) {
|
|
12
|
+
return options.filter((o) => matchesQuery([o.label, o.description], query));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export { filterOptions, matchesQuery };
|
|
16
|
+
//# sourceMappingURL=chunk-BDPRWVFW.js.map
|
|
17
|
+
//# sourceMappingURL=chunk-BDPRWVFW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/headless/text.ts"],"names":[],"mappings":";AASA,SAAS,SAAS,IAAA,EAAsB;AACtC,EAAA,OAAO,IAAA,CACJ,SAAA,CAAU,KAAK,CAAA,CACf,QAAQ,6BAAA,EAA+B,CAAC,CAAA,EAAG,IAAA,KAAiB,IAAI,CAAA,CAChE,SAAA,CAAU,KAAK,EACf,WAAA,EAAY;AACjB;AAGO,SAAS,YAAA,CAAa,OAAwD,KAAA,EAAwB;AAC3G,EAAA,MAAM,KAAA,GAAQ,SAAS,KAAK,CAAA,CAAE,MAAM,KAAK,CAAA,CAAE,OAAO,OAAO,CAAA;AACzD,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,MAAM,QAAA,GAAW,QAAA,CAAA,CAAU,OAAO,KAAA,KAAU,WAAW,CAAC,KAAK,CAAA,GAAI,KAAA,EAAO,MAAA,CAAO,OAAO,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA;AACjG,EAAA,OAAO,MAAM,KAAA,CAAM,CAAC,SAAS,QAAA,CAAS,QAAA,CAAS,IAAI,CAAC,CAAA;AACtD;AAWO,SAAS,aAAA,CAA6E,SAAuB,KAAA,EAAoB;AACtI,EAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAM,YAAA,CAAa,CAAC,CAAA,CAAE,KAAA,EAAO,CAAA,CAAE,WAAW,CAAA,EAAG,KAAK,CAAC,CAAA;AAC5E","file":"chunk-BDPRWVFW.js","sourcesContent":["// Matching typed text against options: a combobox's list, a workspace switcher's search, a picker.\n// Every word typed must appear, ignoring case and accents (\"cafe\" finds \"Café\"), so the web's\n// Combobox and the phone's NativeCombobox find the same options.\n\n/**\n * Text with the accents of Latin letters taken off and in lower case, for comparing what was\n * typed (\"Café\" is \"cafe\"). Only marks on a Latin letter go: in other scripts a mark changes the\n * letter (Devanagari's vowel signs, Japanese's dakuten: \"ガ\" is not \"カ\"), so it stays.\n */\nfunction foldText(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/(\\p{Script=Latin})\\p{Mn}+/gu, (_, base: string) => base)\n .normalize(\"NFC\")\n .toLowerCase();\n}\n\n/** Whether every word of `query` appears in one of `texts` (an empty query matches everything). */\nexport function matchesQuery(texts: string | readonly (string | null | undefined)[], query: string): boolean {\n const words = foldText(query).split(/\\s+/).filter(Boolean);\n if (words.length === 0) return true;\n const haystack = foldText((typeof texts === \"string\" ? [texts] : texts).filter(Boolean).join(\" \"));\n return words.every((word) => haystack.includes(word));\n}\n\n/** An option a combobox lists: what it stores, what it shows, and a second line. */\nexport interface ComboboxOption<T = string> {\n value: T;\n label: string;\n description?: string | undefined;\n disabled?: boolean | undefined;\n}\n\n/** The options whose label or description matches `query`, in the order given. */\nexport function filterOptions<O extends { label: string; description?: string | undefined }>(options: readonly O[], query: string): O[] {\n return options.filter((o) => matchesQuery([o.label, o.description], query));\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { writeConflict } from './chunk-LKRJB632.js';
|
|
2
2
|
import { useOne } from './chunk-QGWQ6LK3.js';
|
|
3
3
|
import { useUnsavedChangesGuard } from './chunk-RVWKVD5Q.js';
|
|
4
|
-
import { relatedKeys } from './chunk-7NUL32W7.js';
|
|
5
4
|
import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-SOO54YYY.js';
|
|
5
|
+
import { relatedKeys } from './chunk-7NUL32W7.js';
|
|
6
6
|
import { useDataProvider, useStorage } from './chunk-R3YXYVWF.js';
|
|
7
7
|
import { patchCachedRow } from './chunk-AUVKRXRC.js';
|
|
8
8
|
import { titleCase } from './chunk-RYEXWQFD.js';
|
|
@@ -638,5 +638,5 @@ function useResourceForm(options) {
|
|
|
638
638
|
}
|
|
639
639
|
|
|
640
640
|
export { blankValues, buildArrayItemDefaults, useResourceForm };
|
|
641
|
-
//# sourceMappingURL=chunk-
|
|
642
|
-
//# sourceMappingURL=chunk-
|
|
641
|
+
//# sourceMappingURL=chunk-FXPODKCK.js.map
|
|
642
|
+
//# sourceMappingURL=chunk-FXPODKCK.js.map
|