@jsudc/react 0.2.1 → 0.3.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.
Files changed (75) hide show
  1. package/README.md +64 -4
  2. package/dist/calendar/EventDetail.js.map +1 -1
  3. package/dist/data-view/FilterBuilder.d.ts +4 -2
  4. package/dist/data-view/FilterBuilder.js +11 -2
  5. package/dist/data-view/FilterBuilder.js.map +1 -1
  6. package/dist/data-view/FilterChips.d.ts +10 -2
  7. package/dist/data-view/FilterChips.js +14 -2
  8. package/dist/data-view/FilterChips.js.map +1 -1
  9. package/dist/data-view/UdcDataView.js +4 -2
  10. package/dist/data-view/UdcDataView.js.map +1 -1
  11. package/dist/data-view/liveView.js +2 -2
  12. package/dist/data-view/liveView.js.map +1 -1
  13. package/dist/headless.d.ts +3 -0
  14. package/dist/headless.js +5 -2
  15. package/dist/i18n/translations.js +16 -0
  16. package/dist/i18n/translations.js.map +1 -1
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.js +10 -2
  19. package/dist/kanban/KanbanCard.d.ts +1 -1
  20. package/dist/kanban/KanbanCard.js +5 -1
  21. package/dist/kanban/KanbanCard.js.map +1 -1
  22. package/dist/kanban/KanbanRenderer.js +72 -67
  23. package/dist/kanban/KanbanRenderer.js.map +1 -1
  24. package/dist/kanban/model.d.ts +11 -1
  25. package/dist/kanban/model.js +29 -3
  26. package/dist/kanban/model.js.map +1 -1
  27. package/dist/kanban/useKanbanBoard.d.ts +5 -1
  28. package/dist/kanban/useKanbanBoard.js +6 -2
  29. package/dist/kanban/useKanbanBoard.js.map +1 -1
  30. package/dist/lookup/LookupCombobox.d.ts +18 -0
  31. package/dist/lookup/LookupCombobox.js +146 -0
  32. package/dist/lookup/LookupCombobox.js.map +1 -0
  33. package/dist/lookup/LookupSelectChip.d.ts +17 -0
  34. package/dist/lookup/LookupSelectChip.js +96 -0
  35. package/dist/lookup/LookupSelectChip.js.map +1 -0
  36. package/dist/lookup/LookupValue.d.ts +27 -0
  37. package/dist/lookup/LookupValue.js +98 -0
  38. package/dist/lookup/LookupValue.js.map +1 -0
  39. package/dist/lookup/batch.d.ts +33 -0
  40. package/dist/lookup/batch.js +69 -0
  41. package/dist/lookup/batch.js.map +1 -0
  42. package/dist/lookup/label.d.ts +5 -0
  43. package/dist/lookup/label.js +16 -0
  44. package/dist/lookup/label.js.map +1 -0
  45. package/dist/lookup/links.d.ts +30 -0
  46. package/dist/lookup/links.js +49 -0
  47. package/dist/lookup/links.js.map +1 -0
  48. package/dist/lookup/options.d.ts +28 -0
  49. package/dist/lookup/options.js +66 -0
  50. package/dist/lookup/options.js.map +1 -0
  51. package/dist/lookup/useUdcLookup.d.ts +52 -0
  52. package/dist/lookup/useUdcLookup.js +96 -0
  53. package/dist/lookup/useUdcLookup.js.map +1 -0
  54. package/dist/react-router/UdcReactRouterUrlState.d.ts +6 -1
  55. package/dist/react-router/UdcReactRouterUrlState.js +16 -3
  56. package/dist/react-router/UdcReactRouterUrlState.js.map +1 -1
  57. package/dist/styles.css +1 -1
  58. package/dist/table/CellEditor.d.ts +8 -4
  59. package/dist/table/CellEditor.js +15 -2
  60. package/dist/table/CellEditor.js.map +1 -1
  61. package/dist/table/TableRenderer.js +122 -97
  62. package/dist/table/TableRenderer.js.map +1 -1
  63. package/dist/table/cells.d.ts +4 -2
  64. package/dist/table/cells.js +9 -1
  65. package/dist/table/cells.js.map +1 -1
  66. package/dist/udc/hooks.d.ts +53 -2
  67. package/dist/udc/hooks.js +9 -1
  68. package/dist/udc/hooks.js.map +1 -1
  69. package/dist/udc/keys.d.ts +5 -0
  70. package/dist/udc/keys.js +26 -0
  71. package/dist/udc/keys.js.map +1 -1
  72. package/dist/udc/provider.d.ts +8 -1
  73. package/dist/udc/provider.js +6 -1
  74. package/dist/udc/provider.js.map +1 -1
  75. package/package.json +4 -4
@@ -0,0 +1,49 @@
1
+ import { PARAM, encodeFilterParam } from "../data-view/urlState.js";
2
+ import { createContext, useContext } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ // src/lookup/links.tsx
5
+ /**
6
+ * `/c/<collection>?…`, followed with the History API: `pushState`, then a
7
+ * `popstate` event, which a router on the History API (react-router's
8
+ * `BrowserRouter` among them) reads as a navigation.
9
+ */
10
+ var defaultUdcLinks = {
11
+ href: (collection, search) => {
12
+ const qs = search.toString();
13
+ return `/c/${encodeURIComponent(collection)}${qs ? `?${qs}` : ""}`;
14
+ },
15
+ navigate: (href) => {
16
+ window.history.pushState(null, "", href);
17
+ window.dispatchEvent(new PopStateEvent("popstate"));
18
+ }
19
+ };
20
+ var UdcLinksContext = createContext(defaultUdcLinks);
21
+ /** Links to other collections through `links`; without it, `defaultUdcLinks`. */
22
+ function UdcLinksProvider({ links, children }) {
23
+ return /* @__PURE__ */ jsx(UdcLinksContext.Provider, {
24
+ value: links,
25
+ children
26
+ });
27
+ }
28
+ function useUdcLinks() {
29
+ return useContext(UdcLinksContext);
30
+ }
31
+ /** The address of `collection` opened with `filter` as its filter tree (`?f=`). */
32
+ function filterHref(links, collection, filter) {
33
+ const search = new URLSearchParams();
34
+ const f = encodeFilterParam(filter);
35
+ if (f) search.set(PARAM.filter, f);
36
+ return links.href(collection, search);
37
+ }
38
+ /** A plain click navigates in the app; Cmd / Ctrl / Shift-click (and the middle button) open a new tab. */
39
+ function followLink(e, href, links) {
40
+ e.preventDefault();
41
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) {
42
+ window.open(href, "_blank", "noopener");
43
+ return;
44
+ }
45
+ links.navigate(href);
46
+ }
47
+ export { UdcLinksProvider, defaultUdcLinks, filterHref, followLink, useUdcLinks };
48
+
49
+ //# sourceMappingURL=links.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"links.js","names":[],"sources":["../../src/lookup/links.tsx"],"sourcesContent":["import type { FilterNode } from \"@jsudc/core\";\nimport { createContext, type MouseEvent, type ReactNode, useContext } from \"react\";\nimport { encodeFilterParam, PARAM } from \"../data-view/urlState.js\";\n\n/**\n * How the library links from one collection to another (a lookup cell, a\n * `row_link`): the address of a collection's view, and how to go there\n * without a reload. The library knows no routes of its own, so the host says\n * where `<UdcDataView collection>` is mounted.\n */\nexport interface UdcLinks {\n /** The address of `collection`'s view with `search` as its query string. */\n href(collection: string, search: URLSearchParams): string;\n /** Go to `href` inside the app. */\n navigate(href: string): void;\n}\n\n/**\n * `/c/<collection>?…`, followed with the History API: `pushState`, then a\n * `popstate` event, which a router on the History API (react-router's\n * `BrowserRouter` among them) reads as a navigation.\n */\nexport const defaultUdcLinks: UdcLinks = {\n href: (collection, search) => {\n const qs = search.toString();\n return `/c/${encodeURIComponent(collection)}${qs ? `?${qs}` : \"\"}`;\n },\n navigate: (href) => {\n window.history.pushState(null, \"\", href);\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n};\n\nconst UdcLinksContext = createContext<UdcLinks>(defaultUdcLinks);\n\n/** Links to other collections through `links`; without it, `defaultUdcLinks`. */\nexport function UdcLinksProvider({ links, children }: { links: UdcLinks; children?: ReactNode }) {\n return <UdcLinksContext.Provider value={links}>{children}</UdcLinksContext.Provider>;\n}\n\nexport function useUdcLinks(): UdcLinks {\n return useContext(UdcLinksContext);\n}\n\n/** The address of `collection` opened with `filter` as its filter tree (`?f=`). */\nexport function filterHref(links: UdcLinks, collection: string, filter: FilterNode): string {\n const search = new URLSearchParams();\n const f = encodeFilterParam(filter);\n if (f) search.set(PARAM.filter, f);\n return links.href(collection, search);\n}\n\n/** A plain click navigates in the app; Cmd / Ctrl / Shift-click (and the middle button) open a new tab. */\nexport function followLink(\n e: Pick<MouseEvent, \"metaKey\" | \"ctrlKey\" | \"shiftKey\" | \"button\" | \"preventDefault\">,\n href: string,\n links: UdcLinks,\n): void {\n e.preventDefault();\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) {\n window.open(href, \"_blank\", \"noopener\");\n return;\n }\n links.navigate(href);\n}\n"],"mappings":";;;;;;;;;AAsBA,IAAa,kBAA4B;CACvC,OAAO,YAAY,WAAW;EAC5B,MAAM,KAAK,OAAO,SAAS;EAC3B,OAAO,MAAM,mBAAmB,UAAU,IAAI,KAAK,IAAI,OAAO;CAChE;CACA,WAAW,SAAS;EAClB,OAAO,QAAQ,UAAU,MAAM,IAAI,IAAI;EACvC,OAAO,cAAc,IAAI,cAAc,UAAU,CAAC;CACpD;AACF;AAEA,IAAM,kBAAkB,cAAwB,eAAe;;AAG/D,SAAgB,iBAAiB,EAAE,OAAO,YAAuD;CAC/F,OAAO,oBAAC,gBAAgB,UAAjB;EAA0B,OAAO;EAAQ;CAAmC,CAAA;AACrF;AAEA,SAAgB,cAAwB;CACtC,OAAO,WAAW,eAAe;AACnC;;AAGA,SAAgB,WAAW,OAAiB,YAAoB,QAA4B;CAC1F,MAAM,SAAS,IAAI,gBAAgB;CACnC,MAAM,IAAI,kBAAkB,MAAM;CAClC,IAAI,GAAG,OAAO,IAAI,MAAM,QAAQ,CAAC;CACjC,OAAO,MAAM,KAAK,YAAY,MAAM;AACtC;;AAGA,SAAgB,WACd,GACA,MACA,OACM;CACN,EAAE,eAAe;CACjB,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,GAAG;EAC1D,OAAO,KAAK,MAAM,UAAU,UAAU;EACtC;CACF;CACA,MAAM,SAAS,IAAI;AACrB"}
@@ -0,0 +1,28 @@
1
+ import { type FilterNode, type LookupDef, type Row } from "@jsudc/core";
2
+ /** How many target rows a picker lists; above this it searches by `label_field` instead. */
3
+ export declare const LOOKUP_OPTIONS_LIMIT = 50;
4
+ export interface LookupOption {
5
+ key: string;
6
+ /** The stored key as the target row has it (a number stays a number). */
7
+ raw: unknown;
8
+ label: string;
9
+ row: Row;
10
+ }
11
+ export interface LookupOptionsResult {
12
+ options: LookupOption[];
13
+ /** The target's row count for this search; more than `LOOKUP_OPTIONS_LIMIT` means "type to narrow". */
14
+ total: number | null;
15
+ isLoading: boolean;
16
+ error: Error | null;
17
+ }
18
+ /** The search condition of a picker: `label_field contains <search>`, case-insensitive. */
19
+ export declare function optionsFilter(lookup: LookupDef, search: string): FilterNode | undefined;
20
+ /**
21
+ * The first `LOOKUP_OPTIONS_LIMIT` rows of a lookup's target, by
22
+ * `label_field`, narrowed by `search` (`contains` on `label_field`). A
23
+ * picker shows its search box once `total` (of the empty search) is larger
24
+ * than the limit.
25
+ */
26
+ export declare function useLookupOptions(lookup: LookupDef | undefined, search: string, opts?: {
27
+ enabled?: boolean;
28
+ }): LookupOptionsResult;
@@ -0,0 +1,66 @@
1
+ import { useUdcClient } from "../udc/client.js";
2
+ import { udcKeys } from "../udc/keys.js";
3
+ import { lookupLabel } from "./label.js";
4
+ import { keyString } from "./useUdcLookup.js";
5
+ import { lookupKeyOf } from "@jsudc/core";
6
+ import { keepPreviousData, useQuery } from "@tanstack/react-query";
7
+ // src/lookup/options.ts
8
+ /** How many target rows a picker lists; above this it searches by `label_field` instead. */
9
+ var LOOKUP_OPTIONS_LIMIT = 50;
10
+ /** The search condition of a picker: `label_field contains <search>`, case-insensitive. */
11
+ function optionsFilter(lookup, search) {
12
+ const s = search.trim();
13
+ return s ? {
14
+ field: lookup.label_field,
15
+ op: "contains",
16
+ value: s,
17
+ case_insensitive: true
18
+ } : void 0;
19
+ }
20
+ /**
21
+ * The first `LOOKUP_OPTIONS_LIMIT` rows of a lookup's target, by
22
+ * `label_field`, narrowed by `search` (`contains` on `label_field`). A
23
+ * picker shows its search box once `total` (of the empty search) is larger
24
+ * than the limit.
25
+ */
26
+ function useLookupOptions(lookup, search, opts = {}) {
27
+ const client = useUdcClient();
28
+ const target = lookup ?? {
29
+ collection: "",
30
+ label_field: ""
31
+ };
32
+ const filter = optionsFilter(target, search);
33
+ const q = useQuery({
34
+ queryKey: udcKeys.lookupOptions(target.collection, target.label_field, search.trim()),
35
+ queryFn: ({ signal }) => client.list({
36
+ collection: target.collection,
37
+ ...filter ? { filter } : {},
38
+ sort: [{
39
+ field: target.label_field,
40
+ dir: "asc"
41
+ }],
42
+ page: { limit: 50 }
43
+ }, { signal }),
44
+ enabled: (opts.enabled ?? true) && lookup !== void 0,
45
+ staleTime: 6e4,
46
+ placeholderData: keepPreviousData
47
+ });
48
+ return {
49
+ options: (q.data?.rows ?? []).map((row) => {
50
+ const raw = lookupKeyOf(row, target);
51
+ const key = keyString(raw);
52
+ return {
53
+ key,
54
+ raw,
55
+ label: lookupLabel(row, target) ?? key,
56
+ row
57
+ };
58
+ }),
59
+ total: q.data?.total ?? null,
60
+ isLoading: q.isLoading,
61
+ error: q.error
62
+ };
63
+ }
64
+ export { LOOKUP_OPTIONS_LIMIT, optionsFilter, useLookupOptions };
65
+
66
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../src/lookup/options.ts"],"sourcesContent":["import { type FilterNode, type LookupDef, lookupKeyOf, type Row } from \"@jsudc/core\";\nimport { keepPreviousData, useQuery } from \"@tanstack/react-query\";\nimport { useUdcClient } from \"../udc/client.js\";\nimport { udcKeys } from \"../udc/keys.js\";\nimport { lookupLabel } from \"./label.js\";\nimport { keyString } from \"./useUdcLookup.js\";\n\n/** How many target rows a picker lists; above this it searches by `label_field` instead. */\nexport const LOOKUP_OPTIONS_LIMIT = 50;\n\nexport interface LookupOption {\n key: string;\n /** The stored key as the target row has it (a number stays a number). */\n raw: unknown;\n label: string;\n row: Row;\n}\n\nexport interface LookupOptionsResult {\n options: LookupOption[];\n /** The target's row count for this search; more than `LOOKUP_OPTIONS_LIMIT` means \"type to narrow\". */\n total: number | null;\n isLoading: boolean;\n error: Error | null;\n}\n\n/** The search condition of a picker: `label_field contains <search>`, case-insensitive. */\nexport function optionsFilter(lookup: LookupDef, search: string): FilterNode | undefined {\n const s = search.trim();\n return s\n ? { field: lookup.label_field, op: \"contains\", value: s, case_insensitive: true }\n : undefined;\n}\n\n/**\n * The first `LOOKUP_OPTIONS_LIMIT` rows of a lookup's target, by\n * `label_field`, narrowed by `search` (`contains` on `label_field`). A\n * picker shows its search box once `total` (of the empty search) is larger\n * than the limit.\n */\nexport function useLookupOptions(\n lookup: LookupDef | undefined,\n search: string,\n opts: { enabled?: boolean } = {},\n): LookupOptionsResult {\n const client = useUdcClient();\n const target = lookup ?? { collection: \"\", label_field: \"\" };\n const filter = optionsFilter(target, search);\n const q = useQuery({\n queryKey: udcKeys.lookupOptions(target.collection, target.label_field, search.trim()),\n queryFn: ({ signal }) =>\n client.list(\n {\n collection: target.collection,\n ...(filter ? { filter } : {}),\n sort: [{ field: target.label_field, dir: \"asc\" }],\n page: { limit: LOOKUP_OPTIONS_LIMIT },\n },\n { signal },\n ),\n enabled: (opts.enabled ?? true) && lookup !== undefined,\n staleTime: 60_000,\n placeholderData: keepPreviousData,\n });\n const options = (q.data?.rows ?? []).map((row) => {\n const raw = lookupKeyOf(row, target);\n const key = keyString(raw);\n return { key, raw, label: lookupLabel(row, target) ?? key, row };\n });\n return { options, total: q.data?.total ?? null, isLoading: q.isLoading, error: q.error };\n}\n"],"mappings":";;;;;;;;AAQA,IAAa,uBAAuB;;AAmBpC,SAAgB,cAAc,QAAmB,QAAwC;CACvF,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IACH;EAAE,OAAO,OAAO;EAAa,IAAI;EAAY,OAAO;EAAG,kBAAkB;CAAK,IAC9E,KAAA;AACN;;;;;;;AAQA,SAAgB,iBACd,QACA,QACA,OAA8B,CAAC,GACV;CACrB,MAAM,SAAS,aAAa;CAC5B,MAAM,SAAS,UAAU;EAAE,YAAY;EAAI,aAAa;CAAG;CAC3D,MAAM,SAAS,cAAc,QAAQ,MAAM;CAC3C,MAAM,IAAI,SAAS;EACjB,UAAU,QAAQ,cAAc,OAAO,YAAY,OAAO,aAAa,OAAO,KAAK,CAAC;EACpF,UAAU,EAAE,aACV,OAAO,KACL;GACE,YAAY,OAAO;GACnB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC3B,MAAM,CAAC;IAAE,OAAO,OAAO;IAAa,KAAK;GAAM,CAAC;GAChD,MAAM,EAAE,OAAA,GAA4B;EACtC,GACA,EAAE,OAAO,CACX;EACF,UAAU,KAAK,WAAW,SAAS,WAAW,KAAA;EAC9C,WAAW;EACX,iBAAiB;CACnB,CAAC;CAMD,OAAO;EAAE,UALQ,EAAE,MAAM,QAAQ,CAAC,EAAA,CAAG,KAAK,QAAQ;GAChD,MAAM,MAAM,YAAY,KAAK,MAAM;GACnC,MAAM,MAAM,UAAU,GAAG;GACzB,OAAO;IAAE;IAAK;IAAK,OAAO,YAAY,KAAK,MAAM,KAAK;IAAK;GAAI;EACjE,CACS;EAAS,OAAO,EAAE,MAAM,SAAS;EAAM,WAAW,EAAE;EAAW,OAAO,EAAE;CAAM;AACzF"}
@@ -0,0 +1,52 @@
1
+ import { type LookupDef, type Row } from "@jsudc/core";
2
+ import type { UdcClient } from "@jsudc/core/client";
3
+ import { keepPreviousData } from "@tanstack/react-query";
4
+ /** A key as the maps below hold it: `7` and `"7"` are one key, as on the server. */
5
+ export declare const keyString: (key: unknown) => string;
6
+ /** The distinct keys of some lookup values (each one key or a list), as strings, in order of appearance. */
7
+ export declare function valueKeys(values: readonly unknown[]): string[];
8
+ /** `valueKeys`, sorted: what a lookup query is keyed and asked by. */
9
+ export declare function lookupKeys(values: readonly unknown[]): string[];
10
+ /** `string` (a collection, keyed by id) or a lookup block, as a lookup block. */
11
+ export declare function asLookup(target: string | LookupDef): LookupDef;
12
+ /** The target rows of a lookup, keyed by `keyString` of their key. */
13
+ export type LookupRows = ReadonlyMap<string, Row>;
14
+ /** `list` the target rows of `keys`, one call per 1000 keys (the page limit). */
15
+ export declare function fetchLookupRows(client: UdcClient, lookup: LookupDef, keys: readonly string[], signal?: AbortSignal): Promise<Map<string, Row>>;
16
+ /**
17
+ * The query of one lookup: `["udc", "lookup", collection, sortedKeys]` (and
18
+ * the key field when it is not the id), one batch `list` with an `in` filter.
19
+ */
20
+ export declare function lookupQuery(client: UdcClient, lookup: LookupDef, keys: readonly string[]): {
21
+ queryKey: readonly ["udc", "lookup", string, readonly string[]] | readonly ["udc", "lookup", string, readonly string[], string];
22
+ queryFn: ({ signal }: {
23
+ signal?: AbortSignal;
24
+ }) => Promise<Map<string, Row>>;
25
+ enabled: boolean;
26
+ staleTime: number;
27
+ placeholderData: typeof keepPreviousData;
28
+ };
29
+ export interface UdcLookupResult {
30
+ rows: LookupRows;
31
+ /** The target row of `key`, once loaded. */
32
+ row: (key: unknown) => Row | undefined;
33
+ isLoading: boolean;
34
+ error: Error | null;
35
+ }
36
+ /**
37
+ * The rows of `target` whose key is in `keys`: one `list` with an `in`
38
+ * filter over the key field (the row id without a `key_field`), cached in
39
+ * TanStack Query by collection and sorted keys. `target` is a collection
40
+ * name (keys are ids) or a field's `lookup` block.
41
+ */
42
+ export declare function useUdcLookup(target: string | LookupDef, keys: readonly unknown[], opts?: {
43
+ enabled?: boolean;
44
+ }): UdcLookupResult;
45
+ export interface LookupRequest {
46
+ /** What the result is filed under (the field name). */
47
+ id: string;
48
+ lookup: LookupDef;
49
+ keys: readonly unknown[];
50
+ }
51
+ /** `useUdcLookup` for several lookups at once (one query each), keyed by request id. */
52
+ export declare function useUdcLookups(requests: readonly LookupRequest[]): Map<string, UdcLookupResult>;
@@ -0,0 +1,96 @@
1
+ import { useUdcClient } from "../udc/client.js";
2
+ import { udcKeys } from "../udc/keys.js";
3
+ import { useMemo } from "react";
4
+ import { MAX_PAGE_LIMIT, lookupKeyField, lookupKeyOf, lookupKeysFilter } from "@jsudc/core";
5
+ import { keepPreviousData, useQueries, useQuery } from "@tanstack/react-query";
6
+ // src/lookup/useUdcLookup.ts
7
+ /** A key as the maps below hold it: `7` and `"7"` are one key, as on the server. */
8
+ var keyString = (key) => typeof key === "string" ? key : typeof key === "number" ? String(key) : JSON.stringify(key);
9
+ var isKey = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
10
+ /** The distinct keys of some lookup values (each one key or a list), as strings, in order of appearance. */
11
+ function valueKeys(values) {
12
+ const out = /* @__PURE__ */ new Set();
13
+ for (const v of values) for (const k of Array.isArray(v) ? v : [v]) if (isKey(k)) out.add(keyString(k));
14
+ return [...out];
15
+ }
16
+ /** `valueKeys`, sorted: what a lookup query is keyed and asked by. */
17
+ function lookupKeys(values) {
18
+ return valueKeys(values).sort();
19
+ }
20
+ /** `string` (a collection, keyed by id) or a lookup block, as a lookup block. */
21
+ function asLookup(target) {
22
+ return typeof target === "string" ? {
23
+ collection: target,
24
+ label_field: ""
25
+ } : target;
26
+ }
27
+ /** `list` the target rows of `keys`, one call per 1000 keys (the page limit). */
28
+ async function fetchLookupRows(client, lookup, keys, signal) {
29
+ const out = /* @__PURE__ */ new Map();
30
+ for (let i = 0; i < keys.length; i += MAX_PAGE_LIMIT) {
31
+ const chunk = keys.slice(i, i + MAX_PAGE_LIMIT);
32
+ const filter = lookupKeysFilter(lookup, chunk);
33
+ const res = await client.list({
34
+ collection: lookup.collection,
35
+ filter,
36
+ page: { limit: chunk.length }
37
+ }, signal ? { signal } : void 0);
38
+ for (const row of res.rows) out.set(keyString(lookupKeyOf(row, lookup)), row);
39
+ }
40
+ return out;
41
+ }
42
+ /**
43
+ * The query of one lookup: `["udc", "lookup", collection, sortedKeys]` (and
44
+ * the key field when it is not the id), one batch `list` with an `in` filter.
45
+ */
46
+ function lookupQuery(client, lookup, keys) {
47
+ const field = lookupKeyField(lookup);
48
+ return {
49
+ queryKey: udcKeys.lookup(lookup.collection, keys, field),
50
+ queryFn: ({ signal }) => fetchLookupRows(client, lookup, keys, signal),
51
+ enabled: keys.length > 0 && lookup.collection !== "",
52
+ staleTime: 6e4,
53
+ placeholderData: keepPreviousData
54
+ };
55
+ }
56
+ var EMPTY = /* @__PURE__ */ new Map();
57
+ function result(data, isLoading, error) {
58
+ const rows = data ?? EMPTY;
59
+ return {
60
+ rows,
61
+ row: (key) => rows.get(keyString(key)),
62
+ isLoading,
63
+ error
64
+ };
65
+ }
66
+ /**
67
+ * The rows of `target` whose key is in `keys`: one `list` with an `in`
68
+ * filter over the key field (the row id without a `key_field`), cached in
69
+ * TanStack Query by collection and sorted keys. `target` is a collection
70
+ * name (keys are ids) or a field's `lookup` block.
71
+ */
72
+ function useUdcLookup(target, keys, opts = {}) {
73
+ const q = lookupQuery(useUdcClient(), asLookup(target), useMemo(() => lookupKeys(keys), [keys]));
74
+ const res = useQuery({
75
+ ...q,
76
+ enabled: q.enabled && (opts.enabled ?? true)
77
+ });
78
+ return result(res.data, res.isLoading, res.error);
79
+ }
80
+ /** `useUdcLookup` for several lookups at once (one query each), keyed by request id. */
81
+ function useUdcLookups(requests) {
82
+ const client = useUdcClient();
83
+ const queries = useMemo(() => requests.map((r) => lookupQuery(client, r.lookup, lookupKeys(r.keys))), [client, requests]);
84
+ const results = useQueries({ queries });
85
+ return useMemo(() => {
86
+ const out = /* @__PURE__ */ new Map();
87
+ requests.forEach((r, i) => {
88
+ const res = results[i];
89
+ out.set(r.id, result(res?.data, res?.isLoading ?? false, res?.error ?? null));
90
+ });
91
+ return out;
92
+ }, [requests, results]);
93
+ }
94
+ export { asLookup, fetchLookupRows, keyString, lookupKeys, lookupQuery, useUdcLookup, useUdcLookups, valueKeys };
95
+
96
+ //# sourceMappingURL=useUdcLookup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUdcLookup.js","names":[],"sources":["../../src/lookup/useUdcLookup.ts"],"sourcesContent":["import {\n type FilterNode,\n type LookupDef,\n lookupKeyField,\n lookupKeyOf,\n lookupKeysFilter,\n MAX_PAGE_LIMIT,\n type Row,\n} from \"@jsudc/core\";\nimport type { UdcClient } from \"@jsudc/core/client\";\nimport { keepPreviousData, useQueries, useQuery } from \"@tanstack/react-query\";\nimport { useMemo } from \"react\";\nimport { useUdcClient } from \"../udc/client.js\";\nimport { udcKeys } from \"../udc/keys.js\";\n\n/** A key as the maps below hold it: `7` and `\"7\"` are one key, as on the server. */\nexport const keyString = (key: unknown): string =>\n typeof key === \"string\" ? key : typeof key === \"number\" ? String(key) : JSON.stringify(key);\n\nconst isKey = (v: unknown): v is string | number =>\n (typeof v === \"string\" && v !== \"\") || (typeof v === \"number\" && Number.isFinite(v));\n\n/** The distinct keys of some lookup values (each one key or a list), as strings, in order of appearance. */\nexport function valueKeys(values: readonly unknown[]): string[] {\n const out = new Set<string>();\n for (const v of values) {\n for (const k of Array.isArray(v) ? v : [v]) if (isKey(k)) out.add(keyString(k));\n }\n return [...out];\n}\n\n/** `valueKeys`, sorted: what a lookup query is keyed and asked by. */\nexport function lookupKeys(values: readonly unknown[]): string[] {\n return valueKeys(values).sort();\n}\n\n/** `string` (a collection, keyed by id) or a lookup block, as a lookup block. */\nexport function asLookup(target: string | LookupDef): LookupDef {\n return typeof target === \"string\" ? { collection: target, label_field: \"\" } : target;\n}\n\n/** The target rows of a lookup, keyed by `keyString` of their key. */\nexport type LookupRows = ReadonlyMap<string, Row>;\n\n/** `list` the target rows of `keys`, one call per 1000 keys (the page limit). */\nexport async function fetchLookupRows(\n client: UdcClient,\n lookup: LookupDef,\n keys: readonly string[],\n signal?: AbortSignal,\n): Promise<Map<string, Row>> {\n const out = new Map<string, Row>();\n for (let i = 0; i < keys.length; i += MAX_PAGE_LIMIT) {\n const chunk = keys.slice(i, i + MAX_PAGE_LIMIT);\n const filter: FilterNode = lookupKeysFilter(lookup, chunk);\n const res = await client.list(\n { collection: lookup.collection, filter, page: { limit: chunk.length } },\n signal ? { signal } : undefined,\n );\n for (const row of res.rows) out.set(keyString(lookupKeyOf(row, lookup)), row);\n }\n return out;\n}\n\n/**\n * The query of one lookup: `[\"udc\", \"lookup\", collection, sortedKeys]` (and\n * the key field when it is not the id), one batch `list` with an `in` filter.\n */\nexport function lookupQuery(client: UdcClient, lookup: LookupDef, keys: readonly string[]) {\n const field = lookupKeyField(lookup);\n return {\n queryKey: udcKeys.lookup(lookup.collection, keys, field),\n queryFn: ({ signal }: { signal?: AbortSignal }) =>\n fetchLookupRows(client, lookup, keys, signal),\n enabled: keys.length > 0 && lookup.collection !== \"\",\n staleTime: 60_000,\n // While the next set of keys loads (a new page arrived), keep showing the labels already known.\n placeholderData: keepPreviousData,\n };\n}\n\nexport interface UdcLookupResult {\n rows: LookupRows;\n /** The target row of `key`, once loaded. */\n row: (key: unknown) => Row | undefined;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst EMPTY: LookupRows = new Map();\n\nfunction result(data: LookupRows | undefined, isLoading: boolean, error: Error | null) {\n const rows = data ?? EMPTY;\n return { rows, row: (key: unknown) => rows.get(keyString(key)), isLoading, error };\n}\n\n/**\n * The rows of `target` whose key is in `keys`: one `list` with an `in`\n * filter over the key field (the row id without a `key_field`), cached in\n * TanStack Query by collection and sorted keys. `target` is a collection\n * name (keys are ids) or a field's `lookup` block.\n */\nexport function useUdcLookup(\n target: string | LookupDef,\n keys: readonly unknown[],\n opts: { enabled?: boolean } = {},\n): UdcLookupResult {\n const client = useUdcClient();\n const lookup = asLookup(target);\n const sorted = useMemo(() => lookupKeys(keys), [keys]);\n const q = lookupQuery(client, lookup, sorted);\n const res = useQuery({ ...q, enabled: q.enabled && (opts.enabled ?? true) });\n return result(res.data, res.isLoading, res.error);\n}\n\nexport interface LookupRequest {\n /** What the result is filed under (the field name). */\n id: string;\n lookup: LookupDef;\n keys: readonly unknown[];\n}\n\n/** `useUdcLookup` for several lookups at once (one query each), keyed by request id. */\nexport function useUdcLookups(requests: readonly LookupRequest[]): Map<string, UdcLookupResult> {\n const client = useUdcClient();\n const queries = useMemo(\n () => requests.map((r) => lookupQuery(client, r.lookup, lookupKeys(r.keys))),\n [client, requests],\n );\n const results = useQueries({ queries });\n return useMemo(() => {\n const out = new Map<string, UdcLookupResult>();\n requests.forEach((r, i) => {\n const res = results[i];\n out.set(r.id, result(res?.data, res?.isLoading ?? false, res?.error ?? null));\n });\n return out;\n }, [requests, results]);\n}\n"],"mappings":"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"}
@@ -5,6 +5,11 @@ import { type ReactNode } from "react";
5
5
  * adapter is rebuilt when the router's query string changes, which re-renders
6
6
  * the hooks under it in the router's own render; nothing to subscribe to.
7
7
  */
8
- export declare function UdcReactRouterUrlState({ children }: {
8
+ export declare function UdcReactRouterUrlState({ children, collectionPath, }: {
9
9
  children?: ReactNode;
10
+ /**
11
+ * The route of a collection's view, e.g. `` (c) => `/udc/${c}` ``. With it, lookup
12
+ * links and `row_link`s go there through the router's `navigate`.
13
+ */
14
+ collectionPath?: (collection: string) => string;
10
15
  }): import("react").JSX.Element;
@@ -1,7 +1,8 @@
1
+ import { UdcLinksProvider } from "../lookup/links.js";
1
2
  import { UdcUrlStateProvider } from "../url-state/UrlState.js";
2
3
  import { useMemo, useRef } from "react";
3
4
  import { jsx } from "react/jsx-runtime";
4
- import { useSearchParams } from "react-router";
5
+ import { useNavigate, useSearchParams } from "react-router";
5
6
  // src/react-router/UdcReactRouterUrlState.tsx
6
7
  var noSubscription = () => () => {};
7
8
  /**
@@ -10,8 +11,16 @@ var noSubscription = () => () => {};
10
11
  * adapter is rebuilt when the router's query string changes, which re-renders
11
12
  * the hooks under it in the router's own render; nothing to subscribe to.
12
13
  */
13
- function UdcReactRouterUrlState({ children }) {
14
+ function UdcReactRouterUrlState({ children, collectionPath }) {
14
15
  const [searchParams, setSearchParams] = useSearchParams();
16
+ const navigate = useNavigate();
17
+ const links = useMemo(() => collectionPath ? {
18
+ href: (collection, search) => {
19
+ const qs = search.toString();
20
+ return `${collectionPath(collection)}${qs ? `?${qs}` : ""}`;
21
+ },
22
+ navigate: (href) => void navigate(href)
23
+ } : null, [collectionPath, navigate]);
15
24
  const search = searchParams.toString();
16
25
  const latest = useRef(search);
17
26
  const adapter = useMemo(() => {
@@ -25,10 +34,14 @@ function UdcReactRouterUrlState({ children }) {
25
34
  subscribe: noSubscription
26
35
  };
27
36
  }, [search, setSearchParams]);
28
- return /* @__PURE__ */ jsx(UdcUrlStateProvider, {
37
+ const inner = /* @__PURE__ */ jsx(UdcUrlStateProvider, {
29
38
  adapter,
30
39
  children
31
40
  });
41
+ return links ? /* @__PURE__ */ jsx(UdcLinksProvider, {
42
+ links,
43
+ children: inner
44
+ }) : inner;
32
45
  }
33
46
  export { UdcReactRouterUrlState };
34
47
 
@@ -1 +1 @@
1
- {"version":3,"file":"UdcReactRouterUrlState.js","names":[],"sources":["../../src/react-router/UdcReactRouterUrlState.tsx"],"sourcesContent":["import { type ReactNode, useMemo, useRef } from \"react\";\nimport { useSearchParams } from \"react-router\";\nimport type { UrlStateAdapter } from \"../url-state/adapter.js\";\nimport { UdcUrlStateProvider } from \"../url-state/UrlState.js\";\n\nconst noSubscription = () => () => {};\n\n/**\n * Mount inside a react-router router (`BrowserRouter`, `MemoryRouter`, a data\n * router) to keep the data view's URL state in the router's location. The\n * adapter is rebuilt when the router's query string changes, which re-renders\n * the hooks under it in the router's own render; nothing to subscribe to.\n */\nexport function UdcReactRouterUrlState({ children }: { children?: ReactNode }) {\n const [searchParams, setSearchParams] = useSearchParams();\n const search = searchParams.toString();\n // What the last `set` wrote, until the router renders it: a second update in the\n // same transition starts from the first one's result, as with `window.location`.\n const latest = useRef(search);\n const adapter = useMemo<UrlStateAdapter>(() => {\n latest.current = search;\n return {\n get: () => new URLSearchParams(latest.current),\n set(next, opts) {\n latest.current = next.toString();\n setSearchParams(next, { replace: opts?.replace });\n },\n subscribe: noSubscription,\n };\n }, [search, setSearchParams]);\n return <UdcUrlStateProvider adapter={adapter}>{children}</UdcUrlStateProvider>;\n}\n"],"mappings":";;;;;AAKA,IAAM,6BAA6B,CAAC;;;;;;;AAQpC,SAAgB,uBAAuB,EAAE,YAAsC;CAC7E,MAAM,CAAC,cAAc,mBAAmB,gBAAgB;CACxD,MAAM,SAAS,aAAa,SAAS;CAGrC,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,UAAU,cAA+B;EAC7C,OAAO,UAAU;EACjB,OAAO;GACL,WAAW,IAAI,gBAAgB,OAAO,OAAO;GAC7C,IAAI,MAAM,MAAM;IACd,OAAO,UAAU,KAAK,SAAS;IAC/B,gBAAgB,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC;GAClD;GACA,WAAW;EACb;CACF,GAAG,CAAC,QAAQ,eAAe,CAAC;CAC5B,OAAO,oBAAC,qBAAD;EAA8B;EAAU;CAA8B,CAAA;AAC/E"}
1
+ {"version":3,"file":"UdcReactRouterUrlState.js","names":[],"sources":["../../src/react-router/UdcReactRouterUrlState.tsx"],"sourcesContent":["import { type ReactNode, useMemo, useRef } from \"react\";\nimport { useNavigate, useSearchParams } from \"react-router\";\nimport { type UdcLinks, UdcLinksProvider } from \"../lookup/links.js\";\nimport type { UrlStateAdapter } from \"../url-state/adapter.js\";\nimport { UdcUrlStateProvider } from \"../url-state/UrlState.js\";\n\nconst noSubscription = () => () => {};\n\n/**\n * Mount inside a react-router router (`BrowserRouter`, `MemoryRouter`, a data\n * router) to keep the data view's URL state in the router's location. The\n * adapter is rebuilt when the router's query string changes, which re-renders\n * the hooks under it in the router's own render; nothing to subscribe to.\n */\nexport function UdcReactRouterUrlState({\n children,\n collectionPath,\n}: {\n children?: ReactNode;\n /**\n * The route of a collection's view, e.g. `` (c) => `/udc/${c}` ``. With it, lookup\n * links and `row_link`s go there through the router's `navigate`.\n */\n collectionPath?: (collection: string) => string;\n}) {\n const [searchParams, setSearchParams] = useSearchParams();\n const navigate = useNavigate();\n const links = useMemo<UdcLinks | null>(\n () =>\n collectionPath\n ? {\n href: (collection, search) => {\n const qs = search.toString();\n return `${collectionPath(collection)}${qs ? `?${qs}` : \"\"}`;\n },\n navigate: (href) => void navigate(href),\n }\n : null,\n [collectionPath, navigate],\n );\n const search = searchParams.toString();\n // What the last `set` wrote, until the router renders it: a second update in the\n // same transition starts from the first one's result, as with `window.location`.\n const latest = useRef(search);\n const adapter = useMemo<UrlStateAdapter>(() => {\n latest.current = search;\n return {\n get: () => new URLSearchParams(latest.current),\n set(next, opts) {\n latest.current = next.toString();\n setSearchParams(next, { replace: opts?.replace });\n },\n subscribe: noSubscription,\n };\n }, [search, setSearchParams]);\n const inner = <UdcUrlStateProvider adapter={adapter}>{children}</UdcUrlStateProvider>;\n return links ? <UdcLinksProvider links={links}>{inner}</UdcLinksProvider> : inner;\n}\n"],"mappings":";;;;;;AAMA,IAAM,6BAA6B,CAAC;;;;;;;AAQpC,SAAgB,uBAAuB,EACrC,UACA,kBAQC;CACD,MAAM,CAAC,cAAc,mBAAmB,gBAAgB;CACxD,MAAM,WAAW,YAAY;CAC7B,MAAM,QAAQ,cAEV,iBACI;EACE,OAAO,YAAY,WAAW;GAC5B,MAAM,KAAK,OAAO,SAAS;GAC3B,OAAO,GAAG,eAAe,UAAU,IAAI,KAAK,IAAI,OAAO;EACzD;EACA,WAAW,SAAS,KAAK,SAAS,IAAI;CACxC,IACA,MACN,CAAC,gBAAgB,QAAQ,CAC3B;CACA,MAAM,SAAS,aAAa,SAAS;CAGrC,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,UAAU,cAA+B;EAC7C,OAAO,UAAU;EACjB,OAAO;GACL,WAAW,IAAI,gBAAgB,OAAO,OAAO;GAC7C,IAAI,MAAM,MAAM;IACd,OAAO,UAAU,KAAK,SAAS;IAC/B,gBAAgB,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC;GAClD;GACA,WAAW;EACb;CACF,GAAG,CAAC,QAAQ,eAAe,CAAC;CAC5B,MAAM,QAAQ,oBAAC,qBAAD;EAA8B;EAAU;CAA8B,CAAA;CACpF,OAAO,QAAQ,oBAAC,kBAAD;EAAyB;EAAQ,UAAA;CAAwB,CAAA,IAAI;AAC9E"}