@jsudc/react 0.5.0 → 0.5.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.
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":[],"sources":["../../src/udc/hooks.ts"],"sourcesContent":["import {\n type ActionRequest,\n type Capabilities,\n evaluateFilter,\n type FilterNode,\n type HostAction,\n type HostActionPayload,\n type HostActionResponse,\n isVersionConflict,\n type ListResponse,\n type Row,\n type SortKey,\n} from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport {\n keepPreviousData,\n type QueryClient,\n type UseMutationOptions,\n type UseMutationResult,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport { useState } from \"react\";\nimport { useUdcChanges } from \"./changes.js\";\nimport { useUdcClient } from \"./client.js\";\nimport { type ListKeyParams, type PagingMode, udcKeys } from \"./keys.js\";\nimport { applyToListRows, isInfinite, type ListCache } from \"./listCache.js\";\n\nexport { applyToListRows };\n\nexport function useUdcCollections() {\n const client = useUdcClient();\n return useQuery({ queryKey: udcKeys.collections(), queryFn: () => client.collections() });\n}\n\nexport function useUdcDescribe(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.describe(collection),\n queryFn: () => client.describe(collection),\n staleTime: 5 * 60_000,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\n/** The file a `source_yaml` collection is read from (`source.read`); fetched again on every mount. */\nexport function useUdcSource(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.source(collection),\n queryFn: () => client.sourceRead(collection),\n staleTime: 0,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\nexport interface UseUdcCollectionArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n mode: PagingMode;\n pageLimit: number;\n /** 1-based; pages mode only. */\n page?: number;\n enabled?: boolean;\n /**\n * From `describe`: a source without `cursor` paging is walked by offset in\n * infinite mode too; `changes` says whether it offers the change feed.\n */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n /**\n * Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /**\n * The search box's text, sent as `ListRequest.search` for a source that\n * answers search itself (`capabilities.search === \"source\"`); blank or\n * absent: no `search` in the request, nor in the query key.\n */\n search?: string | undefined;\n}\n\nexport interface UdcCollectionResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => void;\n /** Infinite mode only; always false in pages mode. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n fetchNextPage: () => void;\n /** A source serving a fetched copy: when it was fetched, and whether the last refresh failed. */\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/** `refetchInterval` for TanStack: a positive number of ms, else off. */\nexport function pollInterval(ms: number | undefined): number | false {\n return typeof ms === \"number\" && ms > 0 ? ms : false;\n}\n\n/** The freshness of a list answer: `fetched_at` and `stale` when the source sent them. */\nexport function freshnessOf(res: Pick<ListResponse, \"fetched_at\" | \"stale\"> | undefined): {\n fetchedAt: string | null;\n stale: boolean;\n} {\n return { fetchedAt: res?.fetched_at ?? null, stale: res?.stale === true };\n}\n\n/** `{ search }` for a non-blank text, else nothing: spread into a list request and its query key. */\nexport function searchPart(search: string | undefined): { search?: string } {\n const text = search?.trim();\n return text ? { search: text } : {};\n}\n\n/** The `offset` a 1-based page asks for. */\nexport function pageOffset(page: number, limit: number): number {\n return Math.max(0, Math.floor(page) - 1) * limit;\n}\n\n/**\n * Rows of one collection. Infinite mode follows `next_cursor` page by page\n * (`useInfiniteQuery`), or the next `offset` while rows remain when the\n * source pages by offset only; pages mode asks for one `offset` page\n * (`useQuery`). Both hooks are always mounted and the inactive one is\n * disabled, so switching modes keeps each cache warm. `refetchInterval`\n * polls the active one.\n */\nexport function useUdcCollection(args: UseUdcCollectionArgs): UdcCollectionResult {\n const client = useUdcClient();\n const { collection, filter, mode, pageLimit: limit } = args;\n const sort = args.sort ?? [];\n const page = Math.max(1, args.page ?? 1);\n const enabled = args.enabled ?? true;\n const byCursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n // The change feed (when the provider has one) refetches on events; the timer covers the rest.\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled,\n });\n const refetchInterval = feed.live ? false : pollInterval(args.refetchInterval);\n const searched = searchPart(args.search);\n\n const infiniteParams: ListKeyParams = { filter, sort, limit, mode: \"infinite\", ...searched };\n const infinite = useInfiniteQuery({\n queryKey: udcKeys.list(collection, infiniteParams),\n queryFn: ({ pageParam, signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page:\n typeof pageParam === \"number\"\n ? { limit, offset: pageParam }\n : pageParam\n ? { limit, cursor: pageParam }\n : { limit },\n },\n { signal },\n ),\n initialPageParam: null as string | number | null,\n getNextPageParam: (last, all) => {\n if (byCursor) return last.next_cursor ?? undefined;\n const loaded = all.reduce((n, p) => n + p.rows.length, 0);\n return last.rows.length > 0 && last.total !== null && loaded < last.total\n ? loaded\n : undefined;\n },\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"infinite\",\n refetchInterval,\n });\n\n const pagesParams: ListKeyParams = { filter, sort, limit, mode: \"pages\", page, ...searched };\n const paged = useQuery({\n queryKey: udcKeys.list(collection, pagesParams),\n queryFn: ({ signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page: { limit, offset: pageOffset(page, limit) },\n },\n { signal },\n ),\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"pages\",\n refetchInterval,\n });\n\n if (mode === \"infinite\") {\n const pages = infinite.data?.pages ?? [];\n return {\n rows: pages.flatMap((p) => p.rows),\n total: pages[0]?.total ?? null,\n isLoading: infinite.isLoading,\n isFetching: infinite.isFetching,\n error: infinite.error,\n refetch: () => void infinite.refetch(),\n hasNextPage: infinite.hasNextPage,\n isFetchingNextPage: infinite.isFetchingNextPage,\n fetchNextPage: () => void infinite.fetchNextPage(),\n ...freshnessOf(pages[0]),\n };\n }\n return {\n rows: paged.data?.rows ?? [],\n total: paged.data?.total ?? null,\n isLoading: paged.isLoading,\n isFetching: paged.isFetching,\n error: paged.error,\n refetch: () => void paged.refetch(),\n hasNextPage: false,\n isFetchingNextPage: false,\n fetchNextPage: () => {},\n ...freshnessOf(paged.data),\n };\n}\n\nexport const ALL_ROWS_MAX = 2000;\nconst ALL_ROWS_PAGE = 500;\n\nexport interface FetchAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Stop after this many rows. */\n max: number;\n /** Rows per `list` call. */\n pageLimit?: number;\n /** Keyset paging unless the source pages by offset only. */\n cursor: boolean;\n /** Sent as `ListRequest.search` when not blank (a source that answers search). */\n search?: string | undefined;\n signal?: AbortSignal;\n onProgress?: (loaded: number, total: number | null) => void;\n}\n\n/**\n * Every row of a filter, `list` page after page, until `total` or `max`.\n * Follows `next_cursor` when keyset paging is on; a source that answers no\n * cursor while rows remain is walked on by offset. Answers one list whose\n * `total` is the server's (so `rows.length < total` means capped), with the\n * first page's `fetched_at` and `stale`.\n */\nexport async function fetchAllRows(\n client: UdcClient,\n args: FetchAllRowsArgs,\n): Promise<ListResponse> {\n const { collection, filter, max } = args;\n const sort = args.sort ?? [];\n const pageLimit = args.pageLimit ?? ALL_ROWS_PAGE;\n const rows: Row[] = [];\n let total: number | null = null;\n let freshness: Pick<ListResponse, \"fetched_at\" | \"stale\"> = {};\n let cursor: string | null = null;\n let byCursor = args.cursor;\n while (rows.length < max) {\n const limit = Math.min(pageLimit, max - rows.length);\n const page = byCursor\n ? cursor\n ? { limit, cursor }\n : { limit }\n : { limit, offset: rows.length };\n const res = await client.list(\n { collection, ...(filter ? { filter } : {}), sort, ...searchPart(args.search), page },\n args.signal ? { signal: args.signal } : undefined,\n );\n if (rows.length === 0) {\n freshness = {\n ...(res.fetched_at === undefined ? {} : { fetched_at: res.fetched_at }),\n ...(res.stale === undefined ? {} : { stale: res.stale }),\n };\n }\n rows.push(...res.rows);\n total = res.total;\n args.onProgress?.(rows.length, total);\n if (res.rows.length === 0 || (total !== null && rows.length >= total)) break;\n if (byCursor) {\n if (res.next_cursor) cursor = res.next_cursor;\n else if (total === null) break;\n else byCursor = false;\n } else if (total === null && res.rows.length < limit) {\n break;\n }\n }\n return { ...freshness, rows, next_cursor: null, total: total ?? rows.length };\n}\n\nexport interface UseUdcAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Default 2,000. */\n max?: number;\n /** From `describe`: whether the source pages by cursor, and offers the change feed. */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n enabled?: boolean;\n /**\n * Poll: refetch every row this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /** Sent as `ListRequest.search` when not blank (`capabilities.search === \"source\"`). */\n search?: string | undefined;\n}\n\nexport interface UdcAllRowsResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => Promise<unknown>;\n /** More rows match than `max`: only the first `max` are here. */\n capped: boolean;\n /** Rows loaded so far by the fetch in flight, for a progress bar. */\n progress: { loaded: number; total: number | null } | null;\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/**\n * All rows of the current filter in one cached list: what the kanban (and\n * the calendar, tree, map and charts after it) draw from. The cache entry\n * sits under `udcKeys.lists(collection)`, so `useUdcMutate`'s optimistic\n * patches and invalidations reach it like every other list.\n */\nexport function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult {\n const client = useUdcClient();\n const { collection, filter } = args;\n const sort = args.sort ?? [];\n const max = args.max ?? ALL_ROWS_MAX;\n const cursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n const [progress, setProgress] = useState<UdcAllRowsResult[\"progress\"]>(null);\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled: args.enabled ?? true,\n });\n\n const searched = searchPart(args.search);\n const key: ListKeyParams = { filter, sort, limit: max, mode: \"all\", ...searched };\n const query = useQuery({\n queryKey: udcKeys.list(collection, key),\n queryFn: async ({ signal }) => {\n setProgress({ loaded: 0, total: null });\n try {\n return await fetchAllRows(client, {\n collection,\n filter,\n sort,\n max,\n cursor,\n ...searched,\n signal,\n onProgress: (loaded, total) => setProgress({ loaded, total }),\n });\n } finally {\n setProgress(null);\n }\n },\n placeholderData: keepPreviousData,\n enabled: args.enabled ?? true,\n refetchInterval: feed.live ? false : pollInterval(args.refetchInterval),\n });\n\n const rows = query.data?.rows ?? [];\n const total = query.data?.total ?? null;\n return {\n rows,\n total,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: query.error,\n refetch: () => query.refetch(),\n capped: total !== null && rows.length < total,\n progress,\n ...freshnessOf(query.data),\n };\n}\n\n/** `data` with every row whose id is `id` passed through `patch`. */\nexport function patchRowInList(\n data: ListCache | undefined,\n id: string,\n patch: (row: Row) => Row,\n): ListCache | undefined {\n if (!data) return data;\n const patchPage = (page: ListResponse): ListResponse =>\n page.rows.some((r) => r.__meta.id === id)\n ? { ...page, rows: page.rows.map((r) => (r.__meta.id === id ? patch(r) : r)) }\n : page;\n return isInfinite(data) ? { ...data, pages: data.pages.map(patchPage) } : patchPage(data);\n}\n\nfunction patchRowEverywhere(\n qc: QueryClient,\n collection: string,\n id: string,\n patch: (row: Row) => Row,\n) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n patchRowInList(data, id, patch),\n );\n}\n\nexport type UdcMutateVars = Omit<ActionRequest<\"mutate\">, \"collection\">;\n\n/**\n * Insert / update / delete one row. An update is applied optimistically to\n * the row in every cached list page and rolled back if the server says no.\n * A `version_conflict` additionally re-reads the row, so the cache holds the\n * value that won; the error still reaches the caller. Lists are invalidated\n * once the call settles.\n */\nexport function useUdcMutate(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateVars) => client.mutate({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const { id, row } = vars;\n if (vars.op === \"update\" && id && row) {\n patchRowEverywhere(qc, collection, id, (r) => ({ ...r, ...row, __meta: r.__meta }));\n }\n return { snapshot };\n },\n onSuccess: (res) => {\n patchRowEverywhere(qc, collection, res.row.__meta.id, () => res.row);\n },\n onError: async (err, vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n if (isVersionConflict(err) && vars.id) {\n try {\n const fresh = await client.read(collection, vars.id);\n patchRowEverywhere(qc, collection, vars.id, () => fresh.row);\n } catch {\n // The invalidation below refetches the lists anyway.\n }\n }\n },\n // A row of this collection may be another collection's lookup label: those batches go stale too.\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/**\n * The three schema edits. Each answers the new schema; `describe` (which\n * derives the columns) and the lists are refetched afterwards.\n */\nexport function useUdcSchema(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n const onSuccess = async () => {\n await qc.invalidateQueries({ queryKey: udcKeys.describe(collection) });\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n };\n\n const addField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.add_field\">, \"collection\">) =>\n client.schemaAddField({ collection, ...req }),\n onSuccess,\n });\n const updateField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.update_field\">, \"collection\">) =>\n client.schemaUpdateField({ collection, ...req }),\n onSuccess,\n });\n const softDeleteField = useMutation({\n mutationFn: (field: string) => client.schemaSoftDeleteField({ collection, field }),\n onSuccess,\n });\n return { addField, updateField, softDeleteField };\n}\n\n// mutate_many and host actions (0.5.0) --------------------------------------\n\nexport type UdcMutateManyVars = Omit<ActionRequest<\"mutate_many\">, \"collection\">;\n\n/**\n * Which cached row a `mutate_many` request touches: one of its `ids`, or a row\n * its `filter` matches (evaluated in the browser, `evaluateFilter`) that is\n * not among `except_ids`. A filter the browser cannot evaluate touches no\n * cached row: the invalidation after the call brings the server's answer.\n */\nexport function mutateManyTouches(vars: UdcMutateManyVars): (row: Row) => boolean {\n if (vars.ids) {\n const ids = new Set(vars.ids);\n return (row) => ids.has(row.__meta.id);\n }\n const except = new Set(vars.except_ids ?? []);\n const filter = vars.filter;\n return (row) => {\n if (except.has(row.__meta.id)) return false;\n try {\n return evaluateFilter(filter, row);\n } catch {\n return false;\n }\n };\n}\n\n/**\n * Change (`update`, the patch in `row`) or delete many rows of a collection in\n * one `mutate_many` request: by `ids`, or by `filter` with `except_ids` (\"all\n * that match, except these\"). Like `useUdcMutate` for one row, the loaded\n * rows are patched (or removed) in every cached list at once, put back if the\n * call fails, and the collection's lists and lookups are invalidated once it\n * settles. Resolves to the server's `{ updated, failed }`: `failed` names the\n * ids that were not changed, and why.\n */\nexport function useUdcMutateMany(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateManyVars) => client.mutateMany({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const touches = mutateManyTouches(vars);\n const set = vars.row;\n const patch =\n vars.op === \"update\" && set\n ? (r: Row): Row => ({ ...r, ...set, __meta: r.__meta })\n : undefined;\n if (vars.op === \"delete\" || patch) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n applyToListRows(data, touches, patch),\n );\n }\n return { snapshot };\n },\n onError: (_err, _vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n },\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/** What `useUdcAction` takes besides TanStack's mutation options. */\nexport interface UseUdcActionOptions<Res, Req>\n extends Omit<UseMutationOptions<Res, Error, Req>, \"mutationFn\"> {\n /** Collections whose lists and lookups to invalidate once the call settles (the rows it changed). */\n invalidates?: readonly string[] | undefined;\n}\n\n/**\n * A mutation over the client's typed `call`, for any host action: pass the\n * action's definition (`defineHostAction`, shared with the server) and the\n * payload and the result are typed from its schemas; or pass a name and type\n * it yourself (`useUdcAction<Res, Req>(\"mail.snooze\")`). `invalidates` names\n * the collections whose lists to refetch afterwards.\n */\nexport function useUdcAction<H extends HostAction>(\n action: H,\n options?: UseUdcActionOptions<HostActionResponse<H>, HostActionPayload<H>>,\n): UseMutationResult<HostActionResponse<H>, Error, HostActionPayload<H>>;\nexport function useUdcAction<Res = unknown, Req = Record<string, unknown>>(\n action: string,\n options?: UseUdcActionOptions<Res, Req>,\n): UseMutationResult<Res, Error, Req>;\nexport function useUdcAction(\n action: string | HostAction,\n options: UseUdcActionOptions<unknown, unknown> = {},\n): UseMutationResult<unknown, Error, unknown> {\n const client = useUdcClient();\n const qc = useQueryClient();\n const { invalidates, onSettled, ...rest } = options;\n return useMutation<unknown, Error, unknown>({\n ...rest,\n mutationFn: (payload) => callAction(client, action, payload),\n onSettled: async (...args) => {\n await Promise.all(\n (invalidates ?? []).flatMap((c) => [\n qc.invalidateQueries({ queryKey: udcKeys.lists(c) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(c) }),\n ]),\n );\n return onSettled?.(...args);\n },\n });\n}\n\n/** `client.call` for a host action given by definition or by name (the answer unchecked by name). */\nexport function callAction(\n client: UdcClient,\n action: string | HostAction,\n payload: unknown,\n): Promise<unknown> {\n const call = client.call.bind(client) as (a: string | HostAction, p: unknown) => Promise<unknown>;\n return call(action, payload);\n}\n"],"mappings":";;;;;;;;AAgCA,SAAgB,oBAAoB;CAClC,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EAAE,UAAU,QAAQ,YAAY;EAAG,eAAe,OAAO,YAAY;CAAE,CAAC;AAC1F;AAEA,SAAgB,eAAe,YAAoB,OAA8B,CAAC,GAAG;CACnF,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EACd,UAAU,QAAQ,SAAS,UAAU;EACrC,eAAe,OAAO,SAAS,UAAU;EACzC,WAAW;EACX,UAAU,KAAK,WAAW,SAAS,eAAe;CACpD,CAAC;AACH;;AAGA,SAAgB,aAAa,YAAoB,OAA8B,CAAC,GAAG;CACjF,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EACd,UAAU,QAAQ,OAAO,UAAU;EACnC,eAAe,OAAO,WAAW,UAAU;EAC3C,WAAW;EACX,UAAU,KAAK,WAAW,SAAS,eAAe;CACpD,CAAC;AACH;;AA8CA,SAAgB,aAAa,IAAwC;CACnE,OAAO,OAAO,OAAO,YAAY,KAAK,IAAI,KAAK;AACjD;;AAGA,SAAgB,YAAY,KAG1B;CACA,OAAO;EAAE,WAAW,KAAK,cAAc;EAAM,OAAO,KAAK,UAAU;CAAK;AAC1E;;AAGA,SAAgB,WAAW,QAAiD;CAC1E,MAAM,OAAO,QAAQ,KAAK;CAC1B,OAAO,OAAO,EAAE,QAAQ,KAAK,IAAI,CAAC;AACpC;;AAGA,SAAgB,WAAW,MAAc,OAAuB;CAC9D,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI;AAC7C;;;;;;;;;AAUA,SAAgB,iBAAiB,MAAiD;CAChF,MAAM,SAAS,aAAa;CAC5B,MA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AC5B;CACF,CAAC;AACH;;AAGA,SAAgB,WACd,QACA,QACA,SACkB;CAElB,OADa,OAAO,KAAK,KAAK,MACvB,CAAA,CAAK,QAAQ,OAAO;AAC7B"}
1
+ {"version":3,"file":"hooks.js","names":[],"sources":["../../src/udc/hooks.ts"],"sourcesContent":["import {\n type ActionRequest,\n type Capabilities,\n evaluateFilter,\n type FilterNode,\n type HostAction,\n type HostActionPayload,\n type HostActionResponse,\n isVersionConflict,\n type ListResponse,\n type Row,\n type SortKey,\n} from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport {\n keepPreviousData,\n type QueryClient,\n type UseMutationOptions,\n type UseMutationResult,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport { useState } from \"react\";\nimport { useUdcChanges } from \"./changes.js\";\nimport { useUdcClient } from \"./client.js\";\nimport { type ListKeyParams, type PagingMode, udcKeys } from \"./keys.js\";\nimport { applyToListRows, isInfinite, type ListCache } from \"./listCache.js\";\n\nexport { applyToListRows };\n\nexport function useUdcCollections() {\n const client = useUdcClient();\n return useQuery({ queryKey: udcKeys.collections(), queryFn: () => client.collections() });\n}\n\nexport function useUdcDescribe(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.describe(collection),\n queryFn: () => client.describe(collection),\n staleTime: 5 * 60_000,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\n/** The file a `source_yaml` collection is read from (`source.read`); fetched again on every mount. */\nexport function useUdcSource(collection: string, opts: { enabled?: boolean } = {}) {\n const client = useUdcClient();\n return useQuery({\n queryKey: udcKeys.source(collection),\n queryFn: () => client.sourceRead(collection),\n staleTime: 0,\n enabled: (opts.enabled ?? true) && collection !== \"\",\n });\n}\n\nexport interface UseUdcCollectionArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n mode: PagingMode;\n pageLimit: number;\n /** 1-based; pages mode only. */\n page?: number;\n enabled?: boolean;\n /**\n * From `describe`: a source without `cursor` paging is walked by offset in\n * infinite mode too; `changes` says whether it offers the change feed.\n */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n /**\n * Poll: refetch the loaded rows this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /**\n * The search box's text, sent as `ListRequest.search` for a source that\n * answers search itself (`capabilities.search === \"source\"`); blank or\n * absent: no `search` in the request, nor in the query key.\n */\n search?: string | undefined;\n}\n\nexport interface UdcCollectionResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => void;\n /** Infinite mode only; always false in pages mode. */\n hasNextPage: boolean;\n isFetchingNextPage: boolean;\n fetchNextPage: () => void;\n /** A source serving a fetched copy: when it was fetched, and whether the last refresh failed. */\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/** `refetchInterval` for TanStack: a positive number of ms, else off. */\nexport function pollInterval(ms: number | undefined): number | false {\n return typeof ms === \"number\" && ms > 0 ? ms : false;\n}\n\n/** The freshness of a list answer: `fetched_at` and `stale` when the source sent them. */\nexport function freshnessOf(res: Pick<ListResponse, \"fetched_at\" | \"stale\"> | undefined): {\n fetchedAt: string | null;\n stale: boolean;\n} {\n return { fetchedAt: res?.fetched_at ?? null, stale: res?.stale === true };\n}\n\n/** `{ search }` for a non-blank text, else nothing: spread into a list request and its query key. */\nexport function searchPart(search: string | undefined): { search?: string } {\n const text = search?.trim();\n return text ? { search: text } : {};\n}\n\n/** The `offset` a 1-based page asks for. */\nexport function pageOffset(page: number, limit: number): number {\n return Math.max(0, Math.floor(page) - 1) * limit;\n}\n\n/**\n * Rows of one collection. Infinite mode follows `next_cursor` page by page\n * (`useInfiniteQuery`), or the next `offset` while rows remain when the\n * source pages by offset only; pages mode asks for one `offset` page\n * (`useQuery`). Both hooks are always mounted and the inactive one is\n * disabled, so switching modes keeps each cache warm. `refetchInterval`\n * polls the active one.\n */\nexport function useUdcCollection(args: UseUdcCollectionArgs): UdcCollectionResult {\n const client = useUdcClient();\n const { collection, filter, mode, pageLimit: limit } = args;\n const sort = args.sort ?? [];\n const page = Math.max(1, args.page ?? 1);\n const enabled = args.enabled ?? true;\n const byCursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n // The change feed (when the provider has one) refetches on events; the timer covers the rest.\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled,\n });\n const refetchInterval = feed.live ? false : pollInterval(args.refetchInterval);\n const searched = searchPart(args.search);\n\n const infiniteParams: ListKeyParams = { filter, sort, limit, mode: \"infinite\", ...searched };\n const infinite = useInfiniteQuery({\n queryKey: udcKeys.list(collection, infiniteParams),\n queryFn: ({ pageParam, signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page:\n typeof pageParam === \"number\"\n ? { limit, offset: pageParam }\n : pageParam\n ? { limit, cursor: pageParam }\n : { limit },\n },\n { signal },\n ),\n initialPageParam: null as string | number | null,\n getNextPageParam: (last, all) => {\n if (byCursor) return last.next_cursor ?? undefined;\n const loaded = all.reduce((n, p) => n + p.rows.length, 0);\n // No total (`total_count: false`): a full page means there may be more.\n const more = last.total !== null ? loaded < last.total : last.rows.length >= limit;\n return last.rows.length > 0 && more ? loaded : undefined;\n },\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"infinite\",\n refetchInterval,\n });\n\n const pagesParams: ListKeyParams = { filter, sort, limit, mode: \"pages\", page, ...searched };\n const paged = useQuery({\n queryKey: udcKeys.list(collection, pagesParams),\n queryFn: ({ signal }) =>\n client.list(\n {\n collection,\n ...(filter ? { filter } : {}),\n sort,\n ...searched,\n page: { limit, offset: pageOffset(page, limit) },\n },\n { signal },\n ),\n placeholderData: keepPreviousData,\n enabled: enabled && mode === \"pages\",\n refetchInterval,\n });\n\n if (mode === \"infinite\") {\n const pages = infinite.data?.pages ?? [];\n return {\n rows: pages.flatMap((p) => p.rows),\n total: pages[0]?.total ?? null,\n isLoading: infinite.isLoading,\n isFetching: infinite.isFetching,\n error: infinite.error,\n refetch: () => void infinite.refetch(),\n hasNextPage: infinite.hasNextPage,\n isFetchingNextPage: infinite.isFetchingNextPage,\n fetchNextPage: () => void infinite.fetchNextPage(),\n ...freshnessOf(pages[0]),\n };\n }\n return {\n rows: paged.data?.rows ?? [],\n total: paged.data?.total ?? null,\n isLoading: paged.isLoading,\n isFetching: paged.isFetching,\n error: paged.error,\n refetch: () => void paged.refetch(),\n hasNextPage: false,\n isFetchingNextPage: false,\n fetchNextPage: () => {},\n ...freshnessOf(paged.data),\n };\n}\n\nexport const ALL_ROWS_MAX = 2000;\nconst ALL_ROWS_PAGE = 500;\n\nexport interface FetchAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Stop after this many rows. */\n max: number;\n /** Rows per `list` call. */\n pageLimit?: number;\n /** Keyset paging unless the source pages by offset only. */\n cursor: boolean;\n /** Sent as `ListRequest.search` when not blank (a source that answers search). */\n search?: string | undefined;\n signal?: AbortSignal;\n onProgress?: (loaded: number, total: number | null) => void;\n}\n\n/**\n * Every row of a filter, `list` page after page, until `total` or `max`.\n * Follows `next_cursor` when keyset paging is on; a source that answers no\n * cursor while rows remain is walked on by offset. Answers one list whose\n * `total` is the server's (so `rows.length < total` means capped), with the\n * first page's `fetched_at` and `stale`.\n */\nexport async function fetchAllRows(\n client: UdcClient,\n args: FetchAllRowsArgs,\n): Promise<ListResponse> {\n const { collection, filter, max } = args;\n const sort = args.sort ?? [];\n const pageLimit = args.pageLimit ?? ALL_ROWS_PAGE;\n const rows: Row[] = [];\n let total: number | null = null;\n let freshness: Pick<ListResponse, \"fetched_at\" | \"stale\"> = {};\n let cursor: string | null = null;\n let byCursor = args.cursor;\n while (rows.length < max) {\n const limit = Math.min(pageLimit, max - rows.length);\n const page = byCursor\n ? cursor\n ? { limit, cursor }\n : { limit }\n : { limit, offset: rows.length };\n const res = await client.list(\n { collection, ...(filter ? { filter } : {}), sort, ...searchPart(args.search), page },\n args.signal ? { signal: args.signal } : undefined,\n );\n if (rows.length === 0) {\n freshness = {\n ...(res.fetched_at === undefined ? {} : { fetched_at: res.fetched_at }),\n ...(res.stale === undefined ? {} : { stale: res.stale }),\n };\n }\n rows.push(...res.rows);\n total = res.total;\n args.onProgress?.(rows.length, total);\n if (res.rows.length === 0 || (total !== null && rows.length >= total)) break;\n if (byCursor) {\n if (res.next_cursor) cursor = res.next_cursor;\n else if (total === null) break;\n else byCursor = false;\n } else if (total === null && res.rows.length < limit) {\n break;\n }\n }\n return { ...freshness, rows, next_cursor: null, total: total ?? rows.length };\n}\n\nexport interface UseUdcAllRowsArgs {\n collection: string;\n filter?: FilterNode | undefined;\n sort?: SortKey[];\n /** Default 2,000. */\n max?: number;\n /** From `describe`: whether the source pages by cursor, and offers the change feed. */\n capabilities?: Pick<Capabilities, \"paging\" | \"changes\"> | undefined;\n enabled?: boolean;\n /**\n * Poll: refetch every row this often (the view's `refresh_interval_ms`).\n * Suspended while the provider's change feed carries the collection.\n */\n refetchInterval?: number | undefined;\n /** Sent as `ListRequest.search` when not blank (`capabilities.search === \"source\"`). */\n search?: string | undefined;\n}\n\nexport interface UdcAllRowsResult {\n rows: Row[];\n total: number | null;\n isLoading: boolean;\n isFetching: boolean;\n error: Error | null;\n refetch: () => Promise<unknown>;\n /** More rows match than `max`: only the first `max` are here. */\n capped: boolean;\n /** Rows loaded so far by the fetch in flight, for a progress bar. */\n progress: { loaded: number; total: number | null } | null;\n fetchedAt: string | null;\n stale: boolean;\n}\n\n/**\n * All rows of the current filter in one cached list: what the kanban (and\n * the calendar, tree, map and charts after it) draw from. The cache entry\n * sits under `udcKeys.lists(collection)`, so `useUdcMutate`'s optimistic\n * patches and invalidations reach it like every other list.\n */\nexport function useUdcAllRows(args: UseUdcAllRowsArgs): UdcAllRowsResult {\n const client = useUdcClient();\n const { collection, filter } = args;\n const sort = args.sort ?? [];\n const max = args.max ?? ALL_ROWS_MAX;\n const cursor = args.capabilities?.paging?.includes(\"cursor\") ?? true;\n const [progress, setProgress] = useState<UdcAllRowsResult[\"progress\"]>(null);\n const feed = useUdcChanges(collection, undefined, {\n capabilities: args.capabilities,\n enabled: args.enabled ?? true,\n });\n\n const searched = searchPart(args.search);\n const key: ListKeyParams = { filter, sort, limit: max, mode: \"all\", ...searched };\n const query = useQuery({\n queryKey: udcKeys.list(collection, key),\n queryFn: async ({ signal }) => {\n setProgress({ loaded: 0, total: null });\n try {\n return await fetchAllRows(client, {\n collection,\n filter,\n sort,\n max,\n cursor,\n ...searched,\n signal,\n onProgress: (loaded, total) => setProgress({ loaded, total }),\n });\n } finally {\n setProgress(null);\n }\n },\n placeholderData: keepPreviousData,\n enabled: args.enabled ?? true,\n refetchInterval: feed.live ? false : pollInterval(args.refetchInterval),\n });\n\n const rows = query.data?.rows ?? [];\n const total = query.data?.total ?? null;\n return {\n rows,\n total,\n isLoading: query.isLoading,\n isFetching: query.isFetching,\n error: query.error,\n refetch: () => query.refetch(),\n capped: total !== null && rows.length < total,\n progress,\n ...freshnessOf(query.data),\n };\n}\n\n/** `data` with every row whose id is `id` passed through `patch`. */\nexport function patchRowInList(\n data: ListCache | undefined,\n id: string,\n patch: (row: Row) => Row,\n): ListCache | undefined {\n if (!data) return data;\n const patchPage = (page: ListResponse): ListResponse =>\n page.rows.some((r) => r.__meta.id === id)\n ? { ...page, rows: page.rows.map((r) => (r.__meta.id === id ? patch(r) : r)) }\n : page;\n return isInfinite(data) ? { ...data, pages: data.pages.map(patchPage) } : patchPage(data);\n}\n\nfunction patchRowEverywhere(\n qc: QueryClient,\n collection: string,\n id: string,\n patch: (row: Row) => Row,\n) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n patchRowInList(data, id, patch),\n );\n}\n\nexport type UdcMutateVars = Omit<ActionRequest<\"mutate\">, \"collection\">;\n\n/**\n * Insert / update / delete one row. An update is applied optimistically to\n * the row in every cached list page and rolled back if the server says no.\n * A `version_conflict` additionally re-reads the row, so the cache holds the\n * value that won; the error still reaches the caller. Lists are invalidated\n * once the call settles.\n */\nexport function useUdcMutate(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateVars) => client.mutate({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const { id, row } = vars;\n if (vars.op === \"update\" && id && row) {\n patchRowEverywhere(qc, collection, id, (r) => ({ ...r, ...row, __meta: r.__meta }));\n }\n return { snapshot };\n },\n onSuccess: (res) => {\n patchRowEverywhere(qc, collection, res.row.__meta.id, () => res.row);\n },\n onError: async (err, vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n if (isVersionConflict(err) && vars.id) {\n try {\n const fresh = await client.read(collection, vars.id);\n patchRowEverywhere(qc, collection, vars.id, () => fresh.row);\n } catch {\n // The invalidation below refetches the lists anyway.\n }\n }\n },\n // A row of this collection may be another collection's lookup label: those batches go stale too.\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/**\n * The three schema edits. Each answers the new schema; `describe` (which\n * derives the columns) and the lists are refetched afterwards.\n */\nexport function useUdcSchema(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n const onSuccess = async () => {\n await qc.invalidateQueries({ queryKey: udcKeys.describe(collection) });\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n };\n\n const addField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.add_field\">, \"collection\">) =>\n client.schemaAddField({ collection, ...req }),\n onSuccess,\n });\n const updateField = useMutation({\n mutationFn: (req: Omit<ActionRequest<\"schema.update_field\">, \"collection\">) =>\n client.schemaUpdateField({ collection, ...req }),\n onSuccess,\n });\n const softDeleteField = useMutation({\n mutationFn: (field: string) => client.schemaSoftDeleteField({ collection, field }),\n onSuccess,\n });\n return { addField, updateField, softDeleteField };\n}\n\n// mutate_many and host actions (0.5.0) --------------------------------------\n\nexport type UdcMutateManyVars = Omit<ActionRequest<\"mutate_many\">, \"collection\">;\n\n/**\n * Which cached row a `mutate_many` request touches: one of its `ids`, or a row\n * its `filter` matches (evaluated in the browser, `evaluateFilter`) that is\n * not among `except_ids`. A filter the browser cannot evaluate touches no\n * cached row: the invalidation after the call brings the server's answer.\n */\nexport function mutateManyTouches(vars: UdcMutateManyVars): (row: Row) => boolean {\n if (vars.ids) {\n const ids = new Set(vars.ids);\n return (row) => ids.has(row.__meta.id);\n }\n const except = new Set(vars.except_ids ?? []);\n const filter = vars.filter;\n return (row) => {\n if (except.has(row.__meta.id)) return false;\n try {\n return evaluateFilter(filter, row);\n } catch {\n return false;\n }\n };\n}\n\n/**\n * Change (`update`, the patch in `row`) or delete many rows of a collection in\n * one `mutate_many` request: by `ids`, or by `filter` with `except_ids` (\"all\n * that match, except these\"). Like `useUdcMutate` for one row, the loaded\n * rows are patched (or removed) in every cached list at once, put back if the\n * call fails, and the collection's lists and lookups are invalidated once it\n * settles. Resolves to the server's `{ updated, failed }`: `failed` names the\n * ids that were not changed, and why.\n */\nexport function useUdcMutateMany(collection: string) {\n const client = useUdcClient();\n const qc = useQueryClient();\n\n return useMutation({\n mutationFn: (vars: UdcMutateManyVars) => client.mutateMany({ collection, ...vars }),\n onMutate: async (vars) => {\n await qc.cancelQueries({ queryKey: udcKeys.lists(collection) });\n const snapshot = qc.getQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) });\n const touches = mutateManyTouches(vars);\n const set = vars.row;\n const patch =\n vars.op === \"update\" && set\n ? (r: Row): Row => ({ ...r, ...set, __meta: r.__meta })\n : undefined;\n if (vars.op === \"delete\" || patch) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(collection) }, (data) =>\n applyToListRows(data, touches, patch),\n );\n }\n return { snapshot };\n },\n onError: (_err, _vars, ctx) => {\n for (const [key, data] of ctx?.snapshot ?? []) qc.setQueryData(key, data);\n },\n onSettled: () =>\n Promise.all([\n qc.invalidateQueries({ queryKey: udcKeys.lists(collection) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(collection) }),\n qc.invalidateQueries({ queryKey: [\"udc\", \"lookup-options\", collection] }),\n ]),\n });\n}\n\n/** What `useUdcAction` takes besides TanStack's mutation options. */\nexport interface UseUdcActionOptions<Res, Req>\n extends Omit<UseMutationOptions<Res, Error, Req>, \"mutationFn\"> {\n /** Collections whose lists and lookups to invalidate once the call settles (the rows it changed). */\n invalidates?: readonly string[] | undefined;\n}\n\n/**\n * A mutation over the client's typed `call`, for any host action: pass the\n * action's definition (`defineHostAction`, shared with the server) and the\n * payload and the result are typed from its schemas; or pass a name and type\n * it yourself (`useUdcAction<Res, Req>(\"mail.snooze\")`). `invalidates` names\n * the collections whose lists to refetch afterwards.\n */\nexport function useUdcAction<H extends HostAction>(\n action: H,\n options?: UseUdcActionOptions<HostActionResponse<H>, HostActionPayload<H>>,\n): UseMutationResult<HostActionResponse<H>, Error, HostActionPayload<H>>;\nexport function useUdcAction<Res = unknown, Req = Record<string, unknown>>(\n action: string,\n options?: UseUdcActionOptions<Res, Req>,\n): UseMutationResult<Res, Error, Req>;\nexport function useUdcAction(\n action: string | HostAction,\n options: UseUdcActionOptions<unknown, unknown> = {},\n): UseMutationResult<unknown, Error, unknown> {\n const client = useUdcClient();\n const qc = useQueryClient();\n const { invalidates, onSettled, ...rest } = options;\n return useMutation<unknown, Error, unknown>({\n ...rest,\n mutationFn: (payload) => callAction(client, action, payload),\n onSettled: async (...args) => {\n await Promise.all(\n (invalidates ?? []).flatMap((c) => [\n qc.invalidateQueries({ queryKey: udcKeys.lists(c) }),\n qc.invalidateQueries({ queryKey: udcKeys.lookups(c) }),\n ]),\n );\n return onSettled?.(...args);\n },\n });\n}\n\n/** `client.call` for a host action given by definition or by name (the answer unchecked by name). */\nexport function callAction(\n client: UdcClient,\n action: string | HostAction,\n payload: unknown,\n): Promise<unknown> {\n const call = client.call.bind(client) as (a: string | HostAction, p: unknown) => Promise<unknown>;\n return call(action, payload);\n}\n"],"mappings":";;;;;;;;AAgCA,SAAgB,oBAAoB;CAClC,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EAAE,UAAU,QAAQ,YAAY;EAAG,eAAe,OAAO,YAAY;CAAE,CAAC;AAC1F;AAEA,SAAgB,eAAe,YAAoB,OAA8B,CAAC,GAAG;CACnF,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EACd,UAAU,QAAQ,SAAS,UAAU;EACrC,eAAe,OAAO,SAAS,UAAU;EACzC,WAAW;EACX,UAAU,KAAK,WAAW,SAAS,eAAe;CACpD,CAAC;AACH;;AAGA,SAAgB,aAAa,YAAoB,OAA8B,CAAC,GAAG;CACjF,MAAM,SAAS,aAAa;CAC5B,OAAO,SAAS;EACd,UAAU,QAAQ,OAAO,UAAU;EACnC,eAAe,OAAO,WAAW,UAAU;EAC3C,WAAW;EACX,UAAU,KAAK,WAAW,SAAS,eAAe;CACpD,CAAC;AACH;;AA8CA,SAAgB,aAAa,IAAwC;CACnE,OAAO,OAAO,OAAO,YAAY,KAAK,IAAI,KAAK;AACjD;;AAGA,SAAgB,YAAY,KAG1B;CACA,OAAO;EAAE,WAAW,KAAK,cAAc;EAAM,OAAO,KAAK,UAAU;CAAK;AAC1E;;AAGA,SAAgB,WAAW,QAAiD;CAC1E,MAAM,OAAO,QAAQ,KAAK;CAC1B,OAAO,OAAO,EAAE,QAAQ,KAAK,IAAI,CAAC;AACpC;;AAGA,SAAgB,WAAW,MAAc,OAAuB;CAC9D,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI;AAC7C;;;;;;;;;AAUA,SAAgB,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kB,EAAE,UAAU,QAAQ,QAAQ,CAAC,EAAE,CAAC,CACvD,CAAC,CACH;GACA,OAAO,YAAY,GAAG,IAAI;EAC5B;CACF,CAAC;AACH;;AAGA,SAAgB,WACd,QACA,QACA,SACkB;CAElB,OADa,OAAO,KAAK,KAAK,MACvB,CAAA,CAAK,QAAQ,OAAO;AAC7B"}
@@ -6,6 +6,21 @@ import { type UdcLinks } from "../lookup/links.js";
6
6
  import type { RendererRegistry } from "../renderers/types.js";
7
7
  import type { UiKit } from "../ui-kit/types.js";
8
8
  import { type UdcChangeFeedOptions } from "./changeFeed.js";
9
+ /**
10
+ * `UdcProvider changes={…}` as an object: the feed's options and the
11
+ * `identity` the stream is scoped to.
12
+ */
13
+ export interface UdcProviderChangesOptions extends UdcChangeFeedOptions {
14
+ /**
15
+ * Who the stream is for, when `UdcClient`'s `headers` is a function whose
16
+ * answer changes (a demo user switcher, an account switcher, an
17
+ * impersonation switch). The server scopes a stream once, when it opens;
18
+ * when `identity` changes the provider calls `UdcChangeFeed.reconnect()`,
19
+ * so the stream follows the new user, without remounting anything below.
20
+ * Compared with `Object.is`: a user id, not a new object per render.
21
+ */
22
+ identity?: string | number | boolean | null | undefined;
23
+ }
9
24
  export { createUdcQueryClient, shouldRetry, type UdcQueryClientOptions, useUdcClient, } from "./client.js";
10
25
  /**
11
26
  * The root provider: the client, the renderers `UdcDataView` draws its tabs
@@ -37,8 +52,10 @@ export declare function UdcProvider({ client, kit, renderers, links, cells, acti
37
52
  * stream for the collections the views below show, and they refetch when
38
53
  * the server says their rows changed instead of on their timer. Off by
39
54
  * default: no connection. Left out under another `UdcProvider` with the
40
- * same client, the outer feed is used.
55
+ * same client, the outer feed is used. `identity` (see
56
+ * `UdcProviderChangesOptions`) reopens the stream when the user behind the
57
+ * client's `headers` changes.
41
58
  */
42
- changes?: boolean | UdcChangeFeedOptions;
59
+ changes?: boolean | UdcProviderChangesOptions;
43
60
  children: ReactNode;
44
61
  }): import("react").JSX.Element;
@@ -6,7 +6,7 @@ import { UdcUiProvider } from "../ui-kit/context.js";
6
6
  import { UdcChangeFeed } from "./changeFeed.js";
7
7
  import { UdcChangeFeedContext } from "./changes.js";
8
8
  import { UdcClientContext, createUdcQueryClient, shouldRetry, useUdcClient } from "./client.js";
9
- import { useContext, useEffect, useMemo } from "react";
9
+ import { useContext, useEffect, useMemo, useRef } from "react";
10
10
  import { jsx } from "react/jsx-runtime";
11
11
  // src/udc/provider.tsx
12
12
  /**
@@ -18,9 +18,19 @@ import { jsx } from "react/jsx-runtime";
18
18
  */
19
19
  function UdcProvider({ client, kit, renderers, links, cells, actions, changes, children }) {
20
20
  const outer = useContext(UdcChangeFeedContext);
21
- const optionsKey = typeof changes === "object" ? JSON.stringify(changes) : String(changes ?? false);
21
+ const { identity, ...feedOptions } = typeof changes === "object" ? changes : {};
22
+ const optionsKey = typeof changes === "object" ? JSON.stringify(feedOptions) : String(changes ?? false);
22
23
  const own = useMemo(() => optionsKey === "false" ? null : new UdcChangeFeed(client, optionsKey === "true" ? {} : JSON.parse(optionsKey)), [client, optionsKey]);
23
24
  useEffect(() => own ? () => own.close() : void 0, [own]);
25
+ const scoped = useRef(null);
26
+ useEffect(() => {
27
+ const last = scoped.current;
28
+ scoped.current = {
29
+ feed: own,
30
+ identity
31
+ };
32
+ if (own && last?.feed === own && !Object.is(last.identity, identity)) own.reconnect();
33
+ }, [own, identity]);
24
34
  const feed = changes === void 0 ? outer?.client === client ? outer : null : own;
25
35
  let inner = /* @__PURE__ */ jsx(UdcClientContext.Provider, {
26
36
  value: client,
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","names":[],"sources":["../../src/udc/provider.tsx"],"sourcesContent":["import type { UdcClient } from \"@jsudc/core/client\";\nimport { type ReactNode, useContext, useEffect, useMemo } from \"react\";\nimport { type BulkActionHandlers, UdcActionsProvider } from \"../actions/bulk.js\";\nimport { type CellRegistry, UdcCellsProvider } from \"../cells/registry.js\";\nimport { type UdcLinks, UdcLinksProvider } from \"../lookup/links.js\";\nimport { UdcRenderersProvider } from \"../renderers/context.js\";\nimport type { RendererRegistry } from \"../renderers/types.js\";\nimport { UdcUiProvider } from \"../ui-kit/context.js\";\nimport type { UiKit } from \"../ui-kit/types.js\";\nimport { UdcChangeFeed, type UdcChangeFeedOptions } from \"./changeFeed.js\";\nimport { UdcChangeFeedContext } from \"./changes.js\";\nimport { UdcClientContext } from \"./client.js\";\n\nexport {\n createUdcQueryClient,\n shouldRetry,\n type UdcQueryClientOptions,\n useUdcClient,\n} from \"./client.js\";\n\n/**\n * The root provider: the client, the renderers `UdcDataView` draws its tabs\n * with, and optionally the UI kit they draw with. Without `kit` the kit in\n * effect is kept (an outer `UdcUiProvider`'s, else `defaultUiKit`); without\n * `renderers` the outer `UdcRenderersProvider`'s registry is kept (else none:\n * every tab says no renderer is registered).\n */\nexport function UdcProvider({\n client,\n kit,\n renderers,\n links,\n cells,\n actions,\n changes,\n children,\n}: {\n client: UdcClient;\n /**\n * Where a lookup link and a `row_link` go: the address of a collection's\n * view, and how to navigate there. Default `defaultUdcLinks` (`/c/<name>`);\n * `UdcReactRouterUrlState collectionPath` sets it for react-router.\n */\n links?: UdcLinks;\n kit?: UiKit;\n /** `createRendererRegistry(tableRenderer, …)`, or `RENDERERS` from `@jsudc/react/all`. */\n renderers?: RendererRegistry;\n /** `createCellRegistry(...)`: the cell components a column's `render` may name (README \"Custom cells\"). */\n cells?: CellRegistry;\n /**\n * The default handlers of the bulk actions of every data view below, by\n * `kind` (README \"Selection and bulk actions\"); a view's `actions` win.\n */\n actions?: BulkActionHandlers;\n /**\n * The change feed (README \"Live updates\"): `true`, or options, opens one\n * stream for the collections the views below show, and they refetch when\n * the server says their rows changed instead of on their timer. Off by\n * default: no connection. Left out under another `UdcProvider` with the\n * same client, the outer feed is used.\n */\n changes?: boolean | UdcChangeFeedOptions;\n children: ReactNode;\n}) {\n const outer = useContext(UdcChangeFeedContext);\n const optionsKey =\n typeof changes === \"object\" ? JSON.stringify(changes) : String(changes ?? false);\n // `changes` is read through its key: a new but equal options object keeps the feed.\n const own = useMemo(\n () =>\n optionsKey === \"false\"\n ? null\n : new UdcChangeFeed(\n client,\n optionsKey === \"true\" ? {} : (JSON.parse(optionsKey) as UdcChangeFeedOptions),\n ),\n [client, optionsKey],\n );\n useEffect(() => (own ? () => own.close() : undefined), [own]);\n const feed = changes === undefined ? (outer?.client === client ? outer : null) : own;\n\n let inner = (\n <UdcClientContext.Provider value={client}>\n <UdcChangeFeedContext.Provider value={feed}>{children}</UdcChangeFeedContext.Provider>\n </UdcClientContext.Provider>\n );\n if (links) inner = <UdcLinksProvider links={links}>{inner}</UdcLinksProvider>;\n if (cells) inner = <UdcCellsProvider cells={cells}>{inner}</UdcCellsProvider>;\n if (actions) inner = <UdcActionsProvider actions={actions}>{inner}</UdcActionsProvider>;\n if (renderers) inner = <UdcRenderersProvider renderers={renderers}>{inner}</UdcRenderersProvider>;\n return kit ? <UdcUiProvider kit={kit}>{inner}</UdcUiProvider> : inner;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,SAAgB,YAAY,EAC1B,QACA,KACA,WACA,OACA,OACA,SACA,SACA,YA4BC;CACD,MAAM,QAAQ,WAAW,oBAAoB;CAC7C,MAAM,aACJ,OAAO,YAAY,WAAW,KAAK,UAAU,OAAO,IAAI,OAAO,WAAW,KAAK;CAEjF,MAAM,MAAM,cAER,eAAe,UACX,OACA,IAAI,cACF,QACA,eAAe,SAAS,CAAC,IAAK,KAAK,MAAM,UAAU,CACrD,GACN,CAAC,QAAQ,UAAU,CACrB;CACA,gBAAiB,YAAY,IAAI,MAAM,IAAI,KAAA,GAAY,CAAC,GAAG,CAAC;CAC5D,MAAM,OAAO,YAAY,KAAA,IAAa,OAAO,WAAW,SAAS,QAAQ,OAAQ;CAEjF,IAAI,QACF,oBAAC,iBAAiB,UAAlB;EAA2B,OAAO;EAChC,UAAA,oBAAC,qBAAqB,UAAtB;GAA+B,OAAO;GAAO;EAAwC,CAAA;CAC5D,CAAA;CAE7B,IAAI,OAAO,QAAQ,oBAAC,kBAAD;EAAyB;EAAQ,UAAA;CAAwB,CAAA;CAC5E,IAAI,OAAO,QAAQ,oBAAC,kBAAD;EAAyB;EAAQ,UAAA;CAAwB,CAAA;CAC5E,IAAI,SAAS,QAAQ,oBAAC,oBAAD;EAA6B;EAAU,UAAA;CAA0B,CAAA;CACtF,IAAI,WAAW,QAAQ,oBAAC,sBAAD;EAAiC;EAAY,UAAA;CAA4B,CAAA;CAChG,OAAO,MAAM,oBAAC,eAAD;EAAoB;EAAM,UAAA;CAAqB,CAAA,IAAI;AAClE"}
1
+ {"version":3,"file":"provider.js","names":[],"sources":["../../src/udc/provider.tsx"],"sourcesContent":["import type { UdcClient } from \"@jsudc/core/client\";\nimport { type ReactNode, useContext, useEffect, useMemo, useRef } from \"react\";\nimport { type BulkActionHandlers, UdcActionsProvider } from \"../actions/bulk.js\";\nimport { type CellRegistry, UdcCellsProvider } from \"../cells/registry.js\";\nimport { type UdcLinks, UdcLinksProvider } from \"../lookup/links.js\";\nimport { UdcRenderersProvider } from \"../renderers/context.js\";\nimport type { RendererRegistry } from \"../renderers/types.js\";\nimport { UdcUiProvider } from \"../ui-kit/context.js\";\nimport type { UiKit } from \"../ui-kit/types.js\";\nimport { UdcChangeFeed, type UdcChangeFeedOptions } from \"./changeFeed.js\";\nimport { UdcChangeFeedContext } from \"./changes.js\";\nimport { UdcClientContext } from \"./client.js\";\n\n/**\n * `UdcProvider changes={…}` as an object: the feed's options and the\n * `identity` the stream is scoped to.\n */\nexport interface UdcProviderChangesOptions extends UdcChangeFeedOptions {\n /**\n * Who the stream is for, when `UdcClient`'s `headers` is a function whose\n * answer changes (a demo user switcher, an account switcher, an\n * impersonation switch). The server scopes a stream once, when it opens;\n * when `identity` changes the provider calls `UdcChangeFeed.reconnect()`,\n * so the stream follows the new user, without remounting anything below.\n * Compared with `Object.is`: a user id, not a new object per render.\n */\n identity?: string | number | boolean | null | undefined;\n}\n\nexport {\n createUdcQueryClient,\n shouldRetry,\n type UdcQueryClientOptions,\n useUdcClient,\n} from \"./client.js\";\n\n/**\n * The root provider: the client, the renderers `UdcDataView` draws its tabs\n * with, and optionally the UI kit they draw with. Without `kit` the kit in\n * effect is kept (an outer `UdcUiProvider`'s, else `defaultUiKit`); without\n * `renderers` the outer `UdcRenderersProvider`'s registry is kept (else none:\n * every tab says no renderer is registered).\n */\nexport function UdcProvider({\n client,\n kit,\n renderers,\n links,\n cells,\n actions,\n changes,\n children,\n}: {\n client: UdcClient;\n /**\n * Where a lookup link and a `row_link` go: the address of a collection's\n * view, and how to navigate there. Default `defaultUdcLinks` (`/c/<name>`);\n * `UdcReactRouterUrlState collectionPath` sets it for react-router.\n */\n links?: UdcLinks;\n kit?: UiKit;\n /** `createRendererRegistry(tableRenderer, …)`, or `RENDERERS` from `@jsudc/react/all`. */\n renderers?: RendererRegistry;\n /** `createCellRegistry(...)`: the cell components a column's `render` may name (README \"Custom cells\"). */\n cells?: CellRegistry;\n /**\n * The default handlers of the bulk actions of every data view below, by\n * `kind` (README \"Selection and bulk actions\"); a view's `actions` win.\n */\n actions?: BulkActionHandlers;\n /**\n * The change feed (README \"Live updates\"): `true`, or options, opens one\n * stream for the collections the views below show, and they refetch when\n * the server says their rows changed instead of on their timer. Off by\n * default: no connection. Left out under another `UdcProvider` with the\n * same client, the outer feed is used. `identity` (see\n * `UdcProviderChangesOptions`) reopens the stream when the user behind the\n * client's `headers` changes.\n */\n changes?: boolean | UdcProviderChangesOptions;\n children: ReactNode;\n}) {\n const outer = useContext(UdcChangeFeedContext);\n const { identity, ...feedOptions } = typeof changes === \"object\" ? changes : {};\n const optionsKey =\n typeof changes === \"object\" ? JSON.stringify(feedOptions) : String(changes ?? false);\n // `changes` is read through its key: a new but equal options object keeps the feed.\n const own = useMemo(\n () =>\n optionsKey === \"false\"\n ? null\n : new UdcChangeFeed(\n client,\n optionsKey === \"true\" ? {} : (JSON.parse(optionsKey) as UdcChangeFeedOptions),\n ),\n [client, optionsKey],\n );\n useEffect(() => (own ? () => own.close() : undefined), [own]);\n // A new identity behind the client's `headers`: the same feed, its stream reopened for it.\n const scoped = useRef<{ feed: UdcChangeFeed | null; identity: unknown } | null>(null);\n useEffect(() => {\n const last = scoped.current;\n scoped.current = { feed: own, identity };\n if (own && last?.feed === own && !Object.is(last.identity, identity)) own.reconnect();\n }, [own, identity]);\n const feed = changes === undefined ? (outer?.client === client ? outer : null) : own;\n\n let inner = (\n <UdcClientContext.Provider value={client}>\n <UdcChangeFeedContext.Provider value={feed}>{children}</UdcChangeFeedContext.Provider>\n </UdcClientContext.Provider>\n );\n if (links) inner = <UdcLinksProvider links={links}>{inner}</UdcLinksProvider>;\n if (cells) inner = <UdcCellsProvider cells={cells}>{inner}</UdcCellsProvider>;\n if (actions) inner = <UdcActionsProvider actions={actions}>{inner}</UdcActionsProvider>;\n if (renderers) inner = <UdcRenderersProvider renderers={renderers}>{inner}</UdcRenderersProvider>;\n return kit ? <UdcUiProvider kit={kit}>{inner}</UdcUiProvider> : inner;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,SAAgB,YAAY,EAC1B,QACA,KACA,WACA,OACA,OACA,SACA,SACA,YA8BC;CACD,MAAM,QAAQ,WAAW,oBAAoB;CAC7C,MAAM,EAAE,UAAU,GAAG,gBAAgB,OAAO,YAAY,WAAW,UAAU,CAAC;CAC9E,MAAM,aACJ,OAAO,YAAY,WAAW,KAAK,UAAU,WAAW,IAAI,OAAO,WAAW,KAAK;CAErF,MAAM,MAAM,cAER,eAAe,UACX,OACA,IAAI,cACF,QACA,eAAe,SAAS,CAAC,IAAK,KAAK,MAAM,UAAU,CACrD,GACN,CAAC,QAAQ,UAAU,CACrB;CACA,gBAAiB,YAAY,IAAI,MAAM,IAAI,KAAA,GAAY,CAAC,GAAG,CAAC;CAE5D,MAAM,SAAS,OAAiE,IAAI;CACpF,gBAAgB;EACd,MAAM,OAAO,OAAO;EACpB,OAAO,UAAU;GAAE,MAAM;GAAK;EAAS;EACvC,IAAI,OAAO,MAAM,SAAS,OAAO,CAAC,OAAO,GAAG,KAAK,UAAU,QAAQ,GAAG,IAAI,UAAU;CACtF,GAAG,CAAC,KAAK,QAAQ,CAAC;CAClB,MAAM,OAAO,YAAY,KAAA,IAAa,OAAO,WAAW,SAAS,QAAQ,OAAQ;CAEjF,IAAI,QACF,oBAAC,iBAAiB,UAAlB;EAA2B,OAAO;EAChC,UAAA,oBAAC,qBAAqB,UAAtB;GAA+B,OAAO;GAAO;EAAwC,CAAA;CAC5D,CAAA;CAE7B,IAAI,OAAO,QAAQ,oBAAC,kBAAD;EAAyB;EAAQ,UAAA;CAAwB,CAAA;CAC5E,IAAI,OAAO,QAAQ,oBAAC,kBAAD;EAAyB;EAAQ,UAAA;CAAwB,CAAA;CAC5E,IAAI,SAAS,QAAQ,oBAAC,oBAAD;EAA6B;EAAU,UAAA;CAA0B,CAAA;CACtF,IAAI,WAAW,QAAQ,oBAAC,sBAAD;EAAiC;EAAY,UAAA;CAA4B,CAAA;CAChG,OAAO,MAAM,oBAAC,eAAD;EAAoB;EAAM,UAAA;CAAqB,CAAA,IAAI;AAClE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jsudc/react",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "React components for UDC collections: the data view, its table, cards, kanban, calendar, tree, map and chart renderers (one subpath each), the schema editor, headless hooks and models, i18n, theme and a compiled, udc:-prefixed stylesheet.",