@jsudc/react 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +139 -3
  2. package/dist/calendar/CalendarRenderer.js +1 -0
  3. package/dist/calendar/CalendarRenderer.js.map +1 -1
  4. package/dist/cards/CardRenderer.js +4 -2
  5. package/dist/cards/CardRenderer.js.map +1 -1
  6. package/dist/chart/ChartRenderer.js +2 -0
  7. package/dist/chart/ChartRenderer.js.map +1 -1
  8. package/dist/data-view/UdcDataView.d.ts +34 -4
  9. package/dist/data-view/UdcDataView.js +36 -16
  10. package/dist/data-view/UdcDataView.js.map +1 -1
  11. package/dist/data-view/liveView.d.ts +21 -4
  12. package/dist/data-view/liveView.js +31 -6
  13. package/dist/data-view/liveView.js.map +1 -1
  14. package/dist/data-view/useDataViewState.d.ts +30 -1
  15. package/dist/data-view/useDataViewState.js +47 -3
  16. package/dist/data-view/useDataViewState.js.map +1 -1
  17. package/dist/headless.d.ts +1 -1
  18. package/dist/headless.js +4 -4
  19. package/dist/i18n/translations.js +16 -0
  20. package/dist/i18n/translations.js.map +1 -1
  21. package/dist/index.d.ts +3 -2
  22. package/dist/index.js +5 -4
  23. package/dist/kanban/KanbanRenderer.js +1 -0
  24. package/dist/kanban/KanbanRenderer.js.map +1 -1
  25. package/dist/map/MapRenderer.js +1 -0
  26. package/dist/map/MapRenderer.js.map +1 -1
  27. package/dist/table/Pager.d.ts +10 -2
  28. package/dist/table/Pager.js +26 -20
  29. package/dist/table/Pager.js.map +1 -1
  30. package/dist/table/TableRenderer.js +45 -20
  31. package/dist/table/TableRenderer.js.map +1 -1
  32. package/dist/table/columnLayout.d.ts +41 -0
  33. package/dist/table/columnLayout.js +86 -0
  34. package/dist/table/columnLayout.js.map +1 -0
  35. package/dist/table/index.d.ts +1 -0
  36. package/dist/table/states.d.ts +10 -2
  37. package/dist/table/states.js +15 -8
  38. package/dist/table/states.js.map +1 -1
  39. package/dist/table.js +2 -1
  40. package/dist/table.js.map +1 -1
  41. package/dist/tree/TreeRenderer.js +1 -0
  42. package/dist/tree/TreeRenderer.js.map +1 -1
  43. package/dist/udc/changeFeed.d.ts +13 -0
  44. package/dist/udc/changeFeed.js +35 -4
  45. package/dist/udc/changeFeed.js.map +1 -1
  46. package/dist/udc/changes.d.ts +7 -1
  47. package/dist/udc/changes.js +7 -1
  48. package/dist/udc/changes.js.map +1 -1
  49. package/dist/udc/hooks.d.ts +14 -1
  50. package/dist/udc/hooks.js +2 -1
  51. package/dist/udc/hooks.js.map +1 -1
  52. package/dist/udc/provider.d.ts +19 -2
  53. package/dist/udc/provider.js +12 -2
  54. package/dist/udc/provider.js.map +1 -1
  55. package/package.json +3 -3
@@ -0,0 +1,86 @@
1
+ import { useLayoutEffect, useState } from "react";
2
+ // src/table/columnLayout.ts
3
+ var positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
4
+ /** `width: fill`: the column takes the rest of the pane. */
5
+ function isFillWidth(c) {
6
+ return c.width === "fill";
7
+ }
8
+ /**
9
+ * Whether `hide_below` leaves the column out at this pane width. An unmeasured pane (`null`, or
10
+ * 0 where nothing lays out) hides nothing, so the table renders as it did before a first measure.
11
+ */
12
+ function hiddenAtWidth(c, paneWidth) {
13
+ const below = positive(c.hide_below);
14
+ return below !== void 0 && paneWidth !== null && paneWidth > 0 && paneWidth < below;
15
+ }
16
+ /**
17
+ * The width in whole px of every column. A fixed column gets its `width` (else the default). The
18
+ * pane's free width is shared among the `fill` columns by `grow`; one whose share would be under
19
+ * its `min_width` gets the floor and the rest is shared again among the others. Without a
20
+ * measured pane a fill column is its floor. Shares are rounded down, so the columns never add up
21
+ * to more than the pane and no sideways scrollbar appears for a fraction of a pixel.
22
+ */
23
+ function layoutColumnWidths(columns, opts) {
24
+ const out = {};
25
+ const fills = [];
26
+ let fixed = 0;
27
+ for (const c of columns) {
28
+ if (isFillWidth(c.config)) {
29
+ fills.push({
30
+ id: c.id,
31
+ grow: positive(c.config.grow) ?? 1,
32
+ min: positive(c.config.min_width) ?? opts.defaultWidth
33
+ });
34
+ continue;
35
+ }
36
+ const w = positive(c.config.width) ?? opts.defaultWidth;
37
+ out[c.id] = w;
38
+ fixed += w;
39
+ }
40
+ if (fills.length === 0) return out;
41
+ let free = opts.paneWidth && opts.paneWidth > 0 ? opts.paneWidth - opts.reserved - fixed : 0;
42
+ let open = fills;
43
+ for (;;) {
44
+ const grow = open.reduce((sum, f) => sum + f.grow, 0);
45
+ const clamped = open.filter((f) => free * f.grow / grow < f.min);
46
+ if (clamped.length === 0) {
47
+ for (const f of open) out[f.id] = Math.max(f.min, Math.floor(free * f.grow / grow));
48
+ break;
49
+ }
50
+ for (const f of clamped) {
51
+ out[f.id] = f.min;
52
+ free -= f.min;
53
+ }
54
+ open = open.filter((f) => !clamped.includes(f));
55
+ if (open.length === 0) break;
56
+ }
57
+ return out;
58
+ }
59
+ /**
60
+ * The inner width of the table's pane (`clientWidth` of the element: no border, no vertical
61
+ * scrollbar), kept current by a ResizeObserver. `null` until measured, and where there is no
62
+ * ResizeObserver or the element has no layout (0, as in jsdom). Off: no observer, `null`.
63
+ */
64
+ function usePaneWidth(ref, on) {
65
+ const [width, setWidth] = useState(null);
66
+ useLayoutEffect(() => {
67
+ const el = ref.current;
68
+ if (!on || !el) {
69
+ setWidth(null);
70
+ return;
71
+ }
72
+ const measure = () => {
73
+ const w = el.clientWidth;
74
+ setWidth(w > 0 ? w : null);
75
+ };
76
+ measure();
77
+ if (typeof ResizeObserver === "undefined") return;
78
+ const ro = new ResizeObserver(measure);
79
+ ro.observe(el);
80
+ return () => ro.disconnect();
81
+ }, [ref, on]);
82
+ return width;
83
+ }
84
+ export { hiddenAtWidth, isFillWidth, layoutColumnWidths, usePaneWidth };
85
+
86
+ //# sourceMappingURL=columnLayout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"columnLayout.js","names":[],"sources":["../../src/table/columnLayout.ts"],"sourcesContent":["// Column sizing against the table's pane (0.6.0): a column's `width` is pixels or `fill`, a\n// `fill` column takes what the pane has left after the fixed columns (never less than its\n// `min_width`, several sharing it by `grow`), and `hide_below` drops a column while the pane is\n// narrower than that. The keys are read loosely, so this works with `@jsudc/core` ^0.5.0, whose\n// schema types `width` as a number and does not know the other three.\nimport { type RefObject, useLayoutEffect, useState } from \"react\";\n\n/** The sizing keys of a column config, as they may arrive from any server. */\nexport interface ColumnSizing {\n width?: unknown;\n grow?: unknown;\n min_width?: unknown;\n hide_below?: unknown;\n}\n\nconst positive = (v: unknown): number | undefined =>\n typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : undefined;\n\n/** `width: fill`: the column takes the rest of the pane. */\nexport function isFillWidth(c: ColumnSizing): boolean {\n return c.width === \"fill\";\n}\n\n/**\n * Whether `hide_below` leaves the column out at this pane width. An unmeasured pane (`null`, or\n * 0 where nothing lays out) hides nothing, so the table renders as it did before a first measure.\n */\nexport function hiddenAtWidth(c: ColumnSizing, paneWidth: number | null): boolean {\n const below = positive(c.hide_below);\n return below !== undefined && paneWidth !== null && paneWidth > 0 && paneWidth < below;\n}\n\nexport interface LayoutInput {\n id: string;\n config: ColumnSizing;\n}\n\nexport interface LayoutOptions {\n /** The pane's inner width in px (`clientWidth` of the scroll box); `null` before a measure. */\n paneWidth: number | null;\n /** Width taken by columns that are not view columns (checkbox, actions, add-column). */\n reserved: number;\n /** The view's `default_column_width`: a column without a width, and a fill column's floor. */\n defaultWidth: number;\n}\n\n/**\n * The width in whole px of every column. A fixed column gets its `width` (else the default). The\n * pane's free width is shared among the `fill` columns by `grow`; one whose share would be under\n * its `min_width` gets the floor and the rest is shared again among the others. Without a\n * measured pane a fill column is its floor. Shares are rounded down, so the columns never add up\n * to more than the pane and no sideways scrollbar appears for a fraction of a pixel.\n */\nexport function layoutColumnWidths(\n columns: readonly LayoutInput[],\n opts: LayoutOptions,\n): Record<string, number> {\n const out: Record<string, number> = {};\n const fills: { id: string; grow: number; min: number }[] = [];\n let fixed = 0;\n for (const c of columns) {\n if (isFillWidth(c.config)) {\n fills.push({\n id: c.id,\n grow: positive(c.config.grow) ?? 1,\n min: positive(c.config.min_width) ?? opts.defaultWidth,\n });\n continue;\n }\n const w = positive(c.config.width) ?? opts.defaultWidth;\n out[c.id] = w;\n fixed += w;\n }\n if (fills.length === 0) return out;\n\n let free = opts.paneWidth && opts.paneWidth > 0 ? opts.paneWidth - opts.reserved - fixed : 0;\n let open = fills;\n // Water-filling: pin each column whose share falls under its floor, then share the rest again.\n for (;;) {\n const grow = open.reduce((sum, f) => sum + f.grow, 0);\n const clamped = open.filter((f) => (free * f.grow) / grow < f.min);\n if (clamped.length === 0) {\n for (const f of open) out[f.id] = Math.max(f.min, Math.floor((free * f.grow) / grow));\n break;\n }\n for (const f of clamped) {\n out[f.id] = f.min;\n free -= f.min;\n }\n open = open.filter((f) => !clamped.includes(f));\n if (open.length === 0) break;\n }\n return out;\n}\n\n/**\n * The inner width of the table's pane (`clientWidth` of the element: no border, no vertical\n * scrollbar), kept current by a ResizeObserver. `null` until measured, and where there is no\n * ResizeObserver or the element has no layout (0, as in jsdom). Off: no observer, `null`.\n */\nexport function usePaneWidth(ref: RefObject<HTMLElement | null>, on: boolean): number | null {\n const [width, setWidth] = useState<number | null>(null);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!on || !el) {\n setWidth(null);\n return;\n }\n const measure = () => {\n const w = el.clientWidth;\n setWidth(w > 0 ? w : null);\n };\n measure();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(measure);\n ro.observe(el);\n return () => ro.disconnect();\n }, [ref, on]);\n return width;\n}\n"],"mappings":";;AAeA,IAAM,YAAY,MAChB,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,IAAI,IAAI,KAAA;;AAG7D,SAAgB,YAAY,GAA0B;CACpD,OAAO,EAAE,UAAU;AACrB;;;;;AAMA,SAAgB,cAAc,GAAiB,WAAmC;CAChF,MAAM,QAA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I;CACtD,sBAAsB;EACpB,MAAM,KAAK,IAAI;EACf,IAAI,CAAC,MAAM,CAAC,IAAI;GACd,SAAS,IAAI;GACb;EACF;EACA,MAAM,gBAAgB;GACpB,MAAM,IAAI,GAAG;GACb,SAAS,IAAI,IAAI,IAAI,IAAI;EAC3B;EACA,QAAQ;EACR,IAAI,OAAO,mBAAmB,aAAa;EAC3C,MAAM,KAAK,IAAI,eAAe,OAAO;EACrC,GAAG,QAAQ,EAAE;EACb,aAAa,GAAG,WAAW;CAC7B,GAAG,CAAC,KAAK,EAAE,CAAC;CACZ,OAAO;AACT"}
@@ -1,5 +1,6 @@
1
1
  import type { RendererDefinition } from "../renderers/types.js";
2
2
  export { CellValue, displayText, renderKind } from "./cells.js";
3
+ export { type ColumnSizing, hiddenAtWidth, isFillWidth, type LayoutInput, type LayoutOptions, layoutColumnWidths, usePaneWidth, } from "./columnLayout.js";
3
4
  export { Pager } from "./Pager.js";
4
5
  export { TableRenderer, type TableRendererProps } from "./TableRenderer.js";
5
6
  export type { TableVirtualization, TableVirtualizeProp } from "./useRowWindow.js";
@@ -1,8 +1,16 @@
1
- /** `body` replaces the default text (a view's `empty_label`). */
2
- export declare function EmptyState({ filtered, onClear, body, }: {
1
+ /**
2
+ * No rows. Its strings are looked up in the collection's own section first
3
+ * (`TBL_<COLLECTION>.EMPTY_TITLE` / `EMPTY_BODY` / `EMPTY_PLAIN`, as
4
+ * `SEARCH_PLACEHOLDER` is), then in `APP`: an empty mail folder can say "No
5
+ * messages here." without every other view of the app saying it too. `body`
6
+ * replaces the default text (a view's `empty_label`) and wins over both.
7
+ */
8
+ export declare function EmptyState({ filtered, onClear, body, collection, }: {
3
9
  filtered: boolean;
4
10
  onClear: () => void;
5
11
  body?: string | undefined;
12
+ /** The collection whose `TBL_<COLLECTION>` section is asked first. */
13
+ collection?: string | undefined;
6
14
  }): import("react").JSX.Element;
7
15
  /**
8
16
  * A failed load. "Not signed in" (`isUnauthenticated`: an HTTP 401, or the
@@ -1,4 +1,4 @@
1
- import { useI18n } from "../i18n/i18n.js";
1
+ import { tableSection, useI18n } from "../i18n/i18n.js";
2
2
  import { useUiKit } from "../ui-kit/context.js";
3
3
  import { isUnauthenticated } from "@jsudc/core";
4
4
  import { AlertTriangle, LogIn, RotateCw, SearchX, Table2 } from "lucide-react";
@@ -28,15 +28,22 @@ function Panel({ icon, title, body, action, testId, tone = "muted" }) {
28
28
  ]
29
29
  });
30
30
  }
31
- /** `body` replaces the default text (a view's `empty_label`). */
32
- function EmptyState({ filtered, onClear, body }) {
31
+ /**
32
+ * No rows. Its strings are looked up in the collection's own section first
33
+ * (`TBL_<COLLECTION>.EMPTY_TITLE` / `EMPTY_BODY` / `EMPTY_PLAIN`, as
34
+ * `SEARCH_PLACEHOLDER` is), then in `APP`: an empty mail folder can say "No
35
+ * messages here." without every other view of the app saying it too. `body`
36
+ * replaces the default text (a view's `empty_label`) and wins over both.
37
+ */
38
+ function EmptyState({ filtered, onClear, body, collection }) {
33
39
  const { Button } = useUiKit();
34
- const { t } = useI18n();
40
+ const { t, tMaybe } = useI18n();
41
+ const term = (key) => (collection ? tMaybe(tableSection(collection), key) : null) ?? t("APP", key);
35
42
  return filtered ? /* @__PURE__ */ jsx(Panel, {
36
43
  testId: "table-empty",
37
44
  icon: /* @__PURE__ */ jsx(SearchX, { className: "udc:size-5" }),
38
- title: t("APP", "EMPTY_TITLE"),
39
- body: body ?? t("APP", "EMPTY_BODY"),
45
+ title: term("EMPTY_TITLE"),
46
+ body: body ?? term("EMPTY_BODY"),
40
47
  action: /* @__PURE__ */ jsx(Button, {
41
48
  size: "sm",
42
49
  onClick: onClear,
@@ -45,8 +52,8 @@ function EmptyState({ filtered, onClear, body }) {
45
52
  }) : /* @__PURE__ */ jsx(Panel, {
46
53
  testId: "table-empty",
47
54
  icon: /* @__PURE__ */ jsx(Table2, { className: "udc:size-5" }),
48
- title: t("APP", "EMPTY_TITLE"),
49
- body: body ?? t("APP", "EMPTY_PLAIN")
55
+ title: term("EMPTY_TITLE"),
56
+ body: body ?? term("EMPTY_PLAIN")
50
57
  });
51
58
  }
52
59
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"states.js","names":[],"sources":["../../src/table/states.tsx"],"sourcesContent":["import { isUnauthenticated } from \"@jsudc/core\";\nimport { AlertTriangle, LogIn, RotateCw, SearchX, Table2 } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { useI18n } from \"../i18n/i18n.js\";\nimport { useUiKit } from \"../ui-kit/context.js\";\n\nfunction Panel({\n icon,\n title,\n body,\n action,\n testId,\n tone = \"muted\",\n}: {\n icon: ReactNode;\n title: string;\n body?: ReactNode;\n action?: ReactNode;\n testId: string;\n tone?: \"muted\" | \"danger\";\n}) {\n return (\n <div\n data-testid={testId}\n className=\"udc:flex udc:flex-col udc:items-center udc:px-6 udc:py-16 udc:text-center\"\n >\n <div\n className={\n tone === \"danger\"\n ? \"udc:mb-4 udc:grid udc:size-12 udc:place-items-center udc:rounded-xl udc:bg-sem-danger-bg udc:text-sem-danger\"\n : \"udc:mb-4 udc:grid udc:size-12 udc:place-items-center udc:rounded-xl udc:border udc:border-border udc:bg-muted udc:text-muted-foreground\"\n }\n >\n {icon}\n </div>\n <div className=\"udc:text-sm udc:font-semibold\">{title}</div>\n {body ? (\n <div className=\"udc:mt-1 udc:max-w-sm udc:text-[13px] udc:text-muted-foreground\">\n {body}\n </div>\n ) : null}\n {action ? <div className=\"udc:mt-4\">{action}</div> : null}\n </div>\n );\n}\n\n/** `body` replaces the default text (a view's `empty_label`). */\nexport function EmptyState({\n filtered,\n onClear,\n body,\n}: {\n filtered: boolean;\n onClear: () => void;\n body?: string | undefined;\n}) {\n const { Button } = useUiKit();\n const { t } = useI18n();\n return filtered ? (\n <Panel\n testId=\"table-empty\"\n icon={<SearchX className=\"udc:size-5\" />}\n title={t(\"APP\", \"EMPTY_TITLE\")}\n body={body ?? t(\"APP\", \"EMPTY_BODY\")}\n action={\n <Button size=\"sm\" onClick={onClear}>\n {t(\"APP\", \"CLEAR_FILTERS\")}\n </Button>\n }\n />\n ) : (\n <Panel\n testId=\"table-empty\"\n icon={<Table2 className=\"udc:size-5\" />}\n title={t(\"APP\", \"EMPTY_TITLE\")}\n body={body ?? t(\"APP\", \"EMPTY_PLAIN\")}\n />\n );\n}\n\n/**\n * A failed load. \"Not signed in\" (`isUnauthenticated`: an HTTP 401, or the\n * server's in-protocol refusal) is a state of the session, not of the data:\n * it says so (`APP.SIGNED_OUT_TITLE` / `SIGNED_OUT_BODY`) and offers no Retry,\n * which would only be refused again. Anything else shows its message and Retry.\n */\nexport function ErrorState({ error, onRetry }: { error: Error; onRetry: () => void }) {\n const { Button } = useUiKit();\n const { t } = useI18n();\n if (isUnauthenticated(error)) {\n return (\n <Panel\n testId=\"signed-out\"\n icon={<LogIn className=\"udc:size-5\" />}\n title={t(\"APP\", \"SIGNED_OUT_TITLE\")}\n body={t(\"APP\", \"SIGNED_OUT_BODY\")}\n />\n );\n }\n return (\n <Panel\n testId=\"table-error\"\n tone=\"danger\"\n icon={<AlertTriangle className=\"udc:size-5\" />}\n title={t(\"APP\", \"ERROR_TITLE\")}\n body={<span className=\"udc:font-mono udc:text-xs\">{error.message}</span>}\n action={\n <Button size=\"sm\" onClick={onRetry} data-testid=\"retry\">\n <RotateCw className=\"udc:size-3.5!\" />\n {t(\"APP\", \"RETRY\")}\n </Button>\n }\n />\n );\n}\n\n/**\n * A tab whose renderer the host did not register: the registry is explicit\n * (`UdcProvider renderers={…}`), so this is a setup error, not missing data.\n */\nexport function NoRendererState({ name }: { name: string }) {\n const { t } = useI18n();\n return (\n <Panel\n testId=\"no-renderer\"\n icon={<Table2 className=\"udc:size-5\" />}\n title={t(\"APP\", \"NO_RENDERER_TITLE\", { name })}\n body={t(\"APP\", \"NO_RENDERER_BODY\")}\n />\n );\n}\n"],"mappings":";;;;;;AAMA,SAAS,MAAM,EACb,MACA,OACA,MACA,QACA,QACA,OAAO,WAQN;CACD,OACE,qBAAC,OAAD;EACE,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E,OAAO,aAAa;EAC7B,MAAM,oBAAC,QAAD;GAAM,WAAU;GAA6B,UAAA,MAAM;EAAc,CAAA;EACvE,QACE,qBAAC,QAAD;GAAQ,MAAK;GAAK,SAAS;GAAS,eAAY;GAAhD,UAAA,CACE,oBAAC,UAAD,EAAU,WAAU,gBAAiB,CAAA,GACpC,EAAE,OAAO,OAAO,CACX;;CAEX,CAAA;AAEL;;;;;AAMA,SAAgB,gBAAgB,EAAE,QAA0B;CAC1D,MAAM,EAAE,MAAM,QAAQ;CACtB,OACE,oBAAC,OAAD;EACE,QAAO;EACP,MAAM,oBAAC,QAAD,EAAQ,WAAU,aAAc,CAAA;EACtC,OAAO,EAAE,OAAO,qBAAqB,EAAE,KAAK,CAAC;EAC7C,MAAM,EAAE,OAAO,kBAAkB;CAClC,CAAA;AAEL"}
1
+ {"version":3,"file":"states.js","names":[],"sources":["../../src/table/states.tsx"],"sourcesContent":["import { isUnauthenticated } from \"@jsudc/core\";\nimport { AlertTriangle, LogIn, RotateCw, SearchX, Table2 } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { tableSection, useI18n } from \"../i18n/i18n.js\";\nimport { useUiKit } from \"../ui-kit/context.js\";\n\nfunction Panel({\n icon,\n title,\n body,\n action,\n testId,\n tone = \"muted\",\n}: {\n icon: ReactNode;\n title: string;\n body?: ReactNode;\n action?: ReactNode;\n testId: string;\n tone?: \"muted\" | \"danger\";\n}) {\n return (\n <div\n data-testid={testId}\n className=\"udc:flex udc:flex-col udc:items-center udc:px-6 udc:py-16 udc:text-center\"\n >\n <div\n className={\n tone === \"danger\"\n ? \"udc:mb-4 udc:grid udc:size-12 udc:place-items-center udc:rounded-xl udc:bg-sem-danger-bg udc:text-sem-danger\"\n : \"udc:mb-4 udc:grid udc:size-12 udc:place-items-center udc:rounded-xl udc:border udc:border-border udc:bg-muted udc:text-muted-foreground\"\n }\n >\n {icon}\n </div>\n <div className=\"udc:text-sm udc:font-semibold\">{title}</div>\n {body ? (\n <div className=\"udc:mt-1 udc:max-w-sm udc:text-[13px] udc:text-muted-foreground\">\n {body}\n </div>\n ) : null}\n {action ? <div className=\"udc:mt-4\">{action}</div> : null}\n </div>\n );\n}\n\n/**\n * No rows. Its strings are looked up in the collection's own section first\n * (`TBL_<COLLECTION>.EMPTY_TITLE` / `EMPTY_BODY` / `EMPTY_PLAIN`, as\n * `SEARCH_PLACEHOLDER` is), then in `APP`: an empty mail folder can say \"No\n * messages here.\" without every other view of the app saying it too. `body`\n * replaces the default text (a view's `empty_label`) and wins over both.\n */\nexport function EmptyState({\n filtered,\n onClear,\n body,\n collection,\n}: {\n filtered: boolean;\n onClear: () => void;\n body?: string | undefined;\n /** The collection whose `TBL_<COLLECTION>` section is asked first. */\n collection?: string | undefined;\n}) {\n const { Button } = useUiKit();\n const { t, tMaybe } = useI18n();\n const term = (key: string) =>\n (collection ? tMaybe(tableSection(collection), key) : null) ?? t(\"APP\", key);\n return filtered ? (\n <Panel\n testId=\"table-empty\"\n icon={<SearchX className=\"udc:size-5\" />}\n title={term(\"EMPTY_TITLE\")}\n body={body ?? term(\"EMPTY_BODY\")}\n action={\n <Button size=\"sm\" onClick={onClear}>\n {t(\"APP\", \"CLEAR_FILTERS\")}\n </Button>\n }\n />\n ) : (\n <Panel\n testId=\"table-empty\"\n icon={<Table2 className=\"udc:size-5\" />}\n title={term(\"EMPTY_TITLE\")}\n body={body ?? term(\"EMPTY_PLAIN\")}\n />\n );\n}\n\n/**\n * A failed load. \"Not signed in\" (`isUnauthenticated`: an HTTP 401, or the\n * server's in-protocol refusal) is a state of the session, not of the data:\n * it says so (`APP.SIGNED_OUT_TITLE` / `SIGNED_OUT_BODY`) and offers no Retry,\n * which would only be refused again. Anything else shows its message and Retry.\n */\nexport function ErrorState({ error, onRetry }: { error: Error; onRetry: () => void }) {\n const { Button } = useUiKit();\n const { t } = useI18n();\n if (isUnauthenticated(error)) {\n return (\n <Panel\n testId=\"signed-out\"\n icon={<LogIn className=\"udc:size-5\" />}\n title={t(\"APP\", \"SIGNED_OUT_TITLE\")}\n body={t(\"APP\", \"SIGNED_OUT_BODY\")}\n />\n );\n }\n return (\n <Panel\n testId=\"table-error\"\n tone=\"danger\"\n icon={<AlertTriangle className=\"udc:size-5\" />}\n title={t(\"APP\", \"ERROR_TITLE\")}\n body={<span className=\"udc:font-mono udc:text-xs\">{error.message}</span>}\n action={\n <Button size=\"sm\" onClick={onRetry} data-testid=\"retry\">\n <RotateCw className=\"udc:size-3.5!\" />\n {t(\"APP\", \"RETRY\")}\n </Button>\n }\n />\n );\n}\n\n/**\n * A tab whose renderer the host did not register: the registry is explicit\n * (`UdcProvider renderers={…}`), so this is a setup error, not missing data.\n */\nexport function NoRendererState({ name }: { name: string }) {\n const { t } = useI18n();\n return (\n <Panel\n testId=\"no-renderer\"\n icon={<Table2 className=\"udc:size-5\" />}\n title={t(\"APP\", \"NO_RENDERER_TITLE\", { name })}\n body={t(\"APP\", \"NO_RENDERER_BODY\")}\n />\n );\n}\n"],"mappings":";;;;;;AAMA,SAAS,MAAM,EACb,MACA,OACA,MACA,QACA,QACA,OAAO,WAQN;CACD,OACE,qBAAC,OAAD;EACE,eAAa;EACb,WAAU;EAFZ,UAAA;GAIE,oBAAC,OAAD;IACE,WACE,SAAS,WACL,iHACA;IAGL,UAAA;GACE,CAAA;GACL,oBAAC,OAAD;IAAK,WAAU;IAAiC,UAAA;GAAW,CAAA;GAC1D,OACC,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,IACH;GACH,SAAS,oBAAC,OAAD;IAAK,WAAU;IAAY,UAAA;GAAY,CAAA,IAAI;EAClD;;AAET;;;;;;;;AASA,SAAgB,WAAW,EACzB,UACA,SACA,MACA,cAOC;CACD,MAAM,EAAE,WAAW,SAAS;CAC5B,MAAM,EAAE,GAAG,WAAW,QAAQ;CAC9B,MAAM,QAAQ,SACX,aAAa,OAAO,aAAa,UAAU,GAAG,GAAG,IAAI,SAAS,EAAE,OAAO,GAAG;CAC7E,OAA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AqB,EAAE,KAAK,CAAC;EAC7C,MAAM,EAAE,OAAO,kBAAkB;CAClC,CAAA;AAEL"}
package/dist/table.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { displayText, renderKind } from "./table/format.js";
2
2
  import { TableRenderer } from "./table/TableRenderer.js";
3
3
  import { CellValue } from "./table/cells.js";
4
+ import { hiddenAtWidth, isFillWidth, layoutColumnWidths, usePaneWidth } from "./table/columnLayout.js";
4
5
  import { Pager } from "./table/Pager.js";
5
6
  import { Table2 } from "lucide-react";
6
7
  // src/table/index.ts
@@ -13,6 +14,6 @@ var tableRenderer = {
13
14
  paging: true,
14
15
  editMode: true
15
16
  };
16
- export { CellValue, Pager, TableRenderer, displayText, renderKind, tableRenderer };
17
+ export { CellValue, Pager, TableRenderer, displayText, hiddenAtWidth, isFillWidth, layoutColumnWidths, renderKind, tableRenderer, usePaneWidth };
17
18
 
18
19
  //# sourceMappingURL=table.js.map
package/dist/table.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"table.js","names":[],"sources":["../src/table/index.ts"],"sourcesContent":["// @jsudc/react/table: the table renderer. Needs the `@tanstack/react-table` peer.\nimport { Table2 } from \"lucide-react\";\nimport type { RendererDefinition } from \"../renderers/types.js\";\nimport { TableRenderer } from \"./TableRenderer.js\";\n\nexport { CellValue, displayText, renderKind } from \"./cells.js\";\nexport { Pager } from \"./Pager.js\";\nexport { TableRenderer, type TableRendererProps } from \"./TableRenderer.js\";\nexport type { TableVirtualization, TableVirtualizeProp } from \"./useRowWindow.js\";\n\n/** `createRendererRegistry(tableRenderer, …)`: the `table` tab, paged, with the schema editor. */\nexport const tableRenderer: RendererDefinition = {\n name: \"table\",\n component: TableRenderer,\n icon: Table2,\n labelKey: \"TAB_TABLE\",\n paging: true,\n editMode: true,\n};\n"],"mappings":";;;;;;;AAWA,IAAa,gBAAoC;CAC/C,MAAM;CACN,WAAW;CACX,MAAM;CACN,UAAU;CACV,QAAQ;CACR,UAAU;AACZ"}
1
+ {"version":3,"file":"table.js","names":[],"sources":["../src/table/index.ts"],"sourcesContent":["// @jsudc/react/table: the table renderer. Needs the `@tanstack/react-table` peer.\nimport { Table2 } from \"lucide-react\";\nimport type { RendererDefinition } from \"../renderers/types.js\";\nimport { TableRenderer } from \"./TableRenderer.js\";\n\nexport { CellValue, displayText, renderKind } from \"./cells.js\";\nexport {\n type ColumnSizing,\n hiddenAtWidth,\n isFillWidth,\n type LayoutInput,\n type LayoutOptions,\n layoutColumnWidths,\n usePaneWidth,\n} from \"./columnLayout.js\";\nexport { Pager } from \"./Pager.js\";\nexport { TableRenderer, type TableRendererProps } from \"./TableRenderer.js\";\nexport type { TableVirtualization, TableVirtualizeProp } from \"./useRowWindow.js\";\n\n/** `createRendererRegistry(tableRenderer, …)`: the `table` tab, paged, with the schema editor. */\nexport const tableRenderer: RendererDefinition = {\n name: \"table\",\n component: TableRenderer,\n icon: Table2,\n labelKey: \"TAB_TABLE\",\n paging: true,\n editMode: true,\n};\n"],"mappings":";;;;;;;;AAoBA,IAAa,gBAAoC;CAC/C,MAAM;CACN,WAAW;CACX,MAAM;CACN,UAAU;CACV,QAAQ;CACR,UAAU;AACZ"}
@@ -368,6 +368,7 @@ function Tree({ collection, describe, filter, baseFilter, search, listSearch, fi
368
368
  style: { marginLeft: i % 3 * 20 }
369
369
  }, k))
370
370
  }) : topRows.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
371
+ collection,
371
372
  filtered,
372
373
  onClear: onClearFilters
373
374
  }) : /* @__PURE__ */ jsxs(DndContext, {
@@ -1 +1 @@
1
- {"version":3,"file":"TreeRenderer.js","names":[],"sources":["../../src/tree/TreeRenderer.tsx"],"sourcesContent":["import {\n type CollisionDetection,\n DndContext,\n type DragEndEvent,\n DragOverlay,\n type DragStartEvent,\n PointerSensor,\n pointerWithin,\n TouchSensor,\n useSensor,\n useSensors,\n} from \"@dnd-kit/core\";\nimport {\n type FilterNode,\n isVersionConflict,\n type Row,\n type TreeOptions,\n UdcError,\n} from \"@jsudc/core\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { ChevronsDownUp, ChevronsUpDown, ListTree } from \"lucide-react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useI18n } from \"../i18n/i18n.js\";\nimport { CardDetailDialog } from \"../kanban/CardDetailDialog.js\";\nimport { AllRowsStatus } from \"../renderers/AllRowsStatus.js\";\nimport type { RendererProps } from \"../renderers/types.js\";\nimport { EmptyState, ErrorState } from \"../table/states.js\";\nimport { useUdcAllRows, useUdcCollection, useUdcMutate } from \"../udc/hooks.js\";\nimport { udcKeys } from \"../udc/keys.js\";\nimport { useUdcClient } from \"../udc/provider.js\";\nimport { useUiKit } from \"../ui-kit/context.js\";\nimport { type TreeExpand, useTreeExpand } from \"./expand.js\";\nimport {\n type BuiltTree,\n buildTree,\n canDrop,\n type DropTarget,\n dropParent,\n idOf,\n lazyChildrenQuery,\n lazyRootsQuery,\n numberOf,\n parentOf,\n parseDropId,\n planDrop,\n reparentRequest,\n replyRow,\n searchExpansion,\n siblingsQuery,\n sortSiblings,\n} from \"./model.js\";\nimport { TreeNode, TreeNodeLabel } from \"./TreeNode.js\";\n\n/** A node moved in this session, drawn at its new place until the lists are read again. */\ninterface Moved {\n row: Row;\n parent: string | null;\n order: number;\n}\n\nexport interface TreeCtx {\n collection: string;\n opts: TreeOptions;\n describe: RendererProps[\"describe\"];\n lazy: boolean;\n /** What every lazy branch adds to its own condition: the data view's filter. */\n dataFilter: FilterNode | undefined;\n /** The text sent as `search` with every list (a source that answers search); absent otherwise. */\n dataSearch?: string | undefined;\n /** The highlighted search term (\"\" when none). */\n term: string;\n isOpen: (id: string, depth: number) => boolean;\n setOpen: (id: string, open: boolean) => void;\n /** Non-lazy: the children of a node as built from the loaded rows. */\n childrenOf: (id: string) => Row[];\n /** Rows moved in this session, by id. */\n moved: ReadonlyMap<string, Moved>;\n orphans: ReadonlySet<string>;\n can: { rename: boolean; reply: boolean; reparent: boolean };\n /** The id being dragged, and the loaded rows the drop targets are checked against. */\n drag: { id: string; rowsById: ReadonlyMap<string, Row> } | null;\n /** Lazy branches report the rows they loaded (for drop gating). */\n report: (parent: string, rows: Row[]) => void;\n onOpenDetail: (row: Row) => void;\n onRename: (row: Row, label: string) => Promise<void>;\n onReply: (parent: Row, text: string) => Promise<void>;\n}\n\nconst Ctx = createContext<TreeCtx | null>(null);\n\nexport function useTree(): TreeCtx {\n const ctx = useContext(Ctx);\n if (!ctx) throw new Error(\"useTree needs a <TreeRenderer> above it\");\n return ctx;\n}\n\n/** Rows as drawn under `parent`: the loaded ones minus those moved away, plus those moved here. */\nexport function withMoves(\n rows: readonly Row[],\n parent: string | null,\n moved: ReadonlyMap<string, Moved>,\n ctx: Pick<TreeCtx, \"opts\">,\n): Row[] {\n const { opts } = ctx;\n const stay = rows.filter((r) => {\n const m = moved.get(idOf(r));\n return !m || m.parent === parent;\n });\n const here = [...moved.values()]\n .filter((m) => m.parent === parent && !stay.some((r) => idOf(r) === idOf(m.row)))\n .map((m) => m.row);\n const patched = [...stay, ...here].map((r) => {\n const m = moved.get(idOf(r));\n return m ? { ...r, [opts.parent_field]: m.parent, [opts.order_field]: m.order } : r;\n });\n return sortSiblings(patched, opts.sibling_sort);\n}\n\nexport function TreeRenderer(props: RendererProps) {\n const { t } = useI18n();\n const opts = props.describe.view.tree_options;\n if (!opts) {\n return (\n <div className=\"udc:p-6 udc:text-sm udc:text-muted-foreground\" data-testid=\"tree-no-options\">\n {t(\"APP\", \"TREE_NO_OPTIONS\")}\n </div>\n );\n }\n return <Tree {...props} opts={opts} />;\n}\n\nconst SKELETON = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\n\nfunction Tree({\n collection,\n describe,\n filter,\n baseFilter,\n search,\n listSearch,\n filtered,\n onClearFilters,\n onCount,\n opts,\n}: RendererProps & { opts: TreeOptions }) {\n const { Button, Skeleton, useToast } = useUiKit();\n const { t } = useI18n();\n const { toast } = useToast();\n const client = useUdcClient();\n const qc = useQueryClient();\n const { capabilities, schema, view } = describe;\n const lazy = opts.lazy;\n const term = search.trim();\n // highlight_and_expand on a loaded tree searches in the browser; anything else asks the server.\n const clientSearch = !lazy && opts.on_search.mode === \"highlight_and_expand\";\n // A source that answers search gets the text, unless the tree searches what it loaded.\n const serverSearch = clientSearch ? undefined : listSearch;\n // A lazy tree lists the matches of a filter flat; a source search alone is such a filter too.\n const dataFilter: FilterNode | undefined = clientSearch\n ? baseFilter\n : (filter ?? (serverSearch === undefined ? undefined : { and: [] }));\n const highlight = opts.on_search.mode === \"highlight_and_expand\" ? term : \"\";\n\n // --- rows ----------------------------------------------------------------------\n const all = useUdcAllRows({\n collection,\n filter: dataFilter,\n sort: opts.sibling_sort,\n capabilities,\n enabled: !lazy,\n refetchInterval: describe.view.refresh_interval_ms,\n search: serverSearch,\n });\n const rootsQ = lazyRootsQuery(opts, dataFilter);\n const roots = useUdcCollection({\n collection,\n filter: rootsQ.filter,\n sort: rootsQ.sort ?? [],\n mode: \"pages\",\n pageLimit: rootsQ.limit,\n enabled: lazy,\n search: serverSearch,\n });\n const totalQ = useUdcCollection({\n collection,\n filter: dataFilter,\n mode: \"pages\",\n pageLimit: 1,\n enabled: lazy,\n search: serverSearch,\n });\n\n const [moved, setMoved] = useState<ReadonlyMap<string, Moved>>(new Map());\n const tree: BuiltTree = useMemo(\n () =>\n buildTree(\n all.rows.map((r) => {\n const m = moved.get(idOf(r));\n return m ? { ...r, [opts.parent_field]: m.parent, [opts.order_field]: m.order } : r;\n }),\n opts,\n ),\n [all.rows, moved, opts],\n );\n\n // A filtered lazy tree lists every match; those under a listed parent show when it opens.\n const lazyRoots = useMemo(() => {\n const ids = new Set(roots.rows.map(idOf));\n const top = roots.rows.filter((r) => {\n const p = parentOf(r, opts);\n return p === null || !ids.has(p);\n });\n return withMoves(top, null, moved, { opts });\n }, [roots.rows, moved, opts]);\n const lazyOrphans = useMemo(\n () => new Set(lazyRoots.filter((r) => parentOf(r, opts) !== null).map(idOf)),\n [lazyRoots, opts],\n );\n\n useEffect(() => {\n onCount(\n lazy\n ? totalQ.total === null\n ? null\n : { shown: lazyRoots.length, total: totalQ.total, unit: \"nodes\" }\n : all.total === null\n ? null\n : { shown: all.rows.length, total: all.rows.length, unit: \"nodes\" },\n );\n }, [onCount, lazy, lazyRoots.length, totalQ.total, all.rows.length, all.total]);\n useEffect(() => () => onCount(null), [onCount]);\n\n // --- expand state (with the search's own, while there is a term) ---------------------\n const expand: TreeExpand = useTreeExpand(opts, collection);\n const expansion = useMemo(\n () =>\n clientSearch && term\n ? searchExpansion(tree, term, view.search?.fields ?? [opts.label_field], opts)\n : null,\n [clientSearch, term, tree, view.search?.fields, opts],\n );\n const [searchToggles, setSearchToggles] = useState<ReadonlyMap<string, boolean>>(new Map());\n // biome-ignore lint/correctness/useExhaustiveDependencies: a new term starts from its own expansion\n useEffect(() => setSearchToggles(new Map()), [term]);\n // A filtered lazy tree lists matches at every depth: none is opened by default.\n const defaultsOn = !(lazy && dataFilter !== undefined);\n\n const isOpen = useCallback(\n (id: string, depth: number) => {\n if (expansion) {\n const toggled = searchToggles.get(id);\n if (toggled !== undefined) return toggled;\n if (expansion.open.has(id)) return true;\n return !opts.on_search.collapse_others && expand.isOpen(id, depth);\n }\n return expand.isOpen(id, defaultsOn ? depth : Number.POSITIVE_INFINITY);\n },\n [expansion, searchToggles, opts.on_search.collapse_others, expand, defaultsOn],\n );\n const setOpen = useCallback(\n (id: string, open: boolean) => {\n if (expansion) setSearchToggles((m) => new Map(m).set(id, open));\n else expand.set(id, open);\n },\n [expansion, expand],\n );\n\n // --- writes -------------------------------------------------------------------------\n const can = {\n rename: opts.interactive.rename && capabilities.mutate,\n reply: opts.interactive.reply && capabilities.mutate,\n reparent: opts.interactive.reparent && capabilities.mutate && capabilities.tree_reparent,\n };\n const mutate = useUdcMutate(collection);\n const fail = useCallback(\n (err: unknown, title: string) => {\n if (isVersionConflict(err)) {\n toast({\n variant: \"warning\",\n title: t(\"APP\", \"TREE_CONFLICT_TITLE\"),\n description: t(\"APP\", \"TREE_CONFLICT_BODY\"),\n });\n } else {\n toast({ variant: \"danger\", title, description: (err as Error).message });\n }\n },\n [toast, t],\n );\n\n const onRename = async (row: Row, label: string) => {\n try {\n await mutate.mutateAsync({\n op: \"update\",\n id: idOf(row),\n row: { [opts.label_field]: label },\n expected_version: row.__meta.version,\n });\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_RENAME_FAILED\"));\n }\n };\n\n const onReply = async (parent: Row, text: string) => {\n try {\n await mutate.mutateAsync({\n op: \"insert\",\n row: replyRow(\n opts,\n schema,\n parent,\n tree.children.get(idOf(parent)) ?? [],\n text,\n new Date(),\n ),\n });\n setOpen(idOf(parent), true);\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_REPLY_FAILED\"));\n throw err;\n }\n };\n\n // --- drag and drop ---------------------------------------------------------------------\n const branches = useRef(new Map<string, Row[]>());\n const report = useCallback((parent: string, rows: Row[]) => {\n branches.current.set(parent, rows);\n }, []);\n const loadedRows = (): Map<string, Row> => {\n if (!lazy) return new Map(tree.byId);\n const map = new Map<string, Row>();\n for (const r of roots.rows) map.set(idOf(r), r);\n for (const rows of branches.current.values()) for (const r of rows) map.set(idOf(r), r);\n for (const m of moved.values()) {\n map.set(idOf(m.row), {\n ...m.row,\n [opts.parent_field]: m.parent,\n [opts.order_field]: m.order,\n });\n }\n return map;\n };\n const [drag, setDrag] = useState<TreeCtx[\"drag\"]>(null);\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),\n useSensor(TouchSensor, { activationConstraint: { delay: 180, tolerance: 6 } }),\n );\n // The gap strip above a row wins over the row it overlaps.\n const collision: CollisionDetection = (args) =>\n pointerWithin(args).sort(\n (a, b) =>\n Number(String(b.id).startsWith(\"before:\")) - Number(String(a.id).startsWith(\"before:\")),\n );\n\n const onDragStart = (e: DragStartEvent) =>\n setDrag({ id: String(e.active.id), rowsById: loadedRows() });\n\n const siblingOrders = async (parent: string | null) => {\n const q = siblingsQuery(opts, parent);\n const res = await client.list({ collection, ...q, page: { limit: q.limit } });\n return res.rows.map((r) => ({ id: idOf(r), order: numberOf(r, opts.order_field), row: r }));\n };\n\n const move = async (dragId: string, target: DropTarget, rowsById: ReadonlyMap<string, Row>) => {\n const parent = dropParent(target, rowsById, opts);\n const row = rowsById.get(dragId);\n if (parent === undefined || !row) return;\n // Drawn at once: last under the new parent, or just above the target.\n const above = numberOf(rowsById.get(target.id), opts.order_field);\n const provisional =\n target.kind === \"before\" && above !== null ? above - 0.5 : Number.MAX_SAFE_INTEGER;\n setMoved((m) => new Map(m).set(dragId, { row, parent, order: provisional }));\n if (parent !== null) setOpen(parent, true);\n try {\n let siblings = await siblingOrders(parent);\n let plan = planDrop(dragId, target, parent, siblings);\n let version = row.__meta.version;\n if (plan.collision) {\n if (parent === null) throw new UdcError(\"internal\", t(\"APP\", \"TREE_NO_ROOM\"));\n await client.reindex({\n collection,\n scope: { [opts.parent_field]: parent },\n order_field: opts.order_field,\n });\n siblings = await siblingOrders(parent);\n plan = planDrop(dragId, target, parent, siblings);\n if (plan.collision) throw new UdcError(\"internal\", t(\"APP\", \"TREE_NO_ROOM\"));\n // A reindex of the node's own siblings bumped its version too.\n version = siblings.find((s) => s.id === dragId)?.row.__meta.version ?? version;\n }\n await client.treeReparent(reparentRequest(collection, opts, plan, version));\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_MOVE_FAILED\"));\n } finally {\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n setMoved((m) => {\n const next = new Map(m);\n next.delete(dragId);\n return next;\n });\n }\n };\n\n const onDragEnd = (e: DragEndEvent) => {\n const current = drag;\n setDrag(null);\n const target = e.over ? parseDropId(String(e.over.id)) : null;\n if (!current || !target || !canDrop(current.id, target, current.rowsById, opts)) return;\n void move(current.id, target, current.rowsById);\n };\n\n // --- detail -------------------------------------------------------------------------------\n const [detail, setDetail] = useState<Row | null>(null);\n\n const ctx: TreeCtx = {\n collection,\n opts,\n describe,\n lazy,\n dataFilter,\n dataSearch: serverSearch,\n term: highlight,\n isOpen,\n setOpen,\n childrenOf: (id) => tree.children.get(id) ?? [],\n moved,\n orphans: lazy ? lazyOrphans : tree.orphans,\n can,\n drag,\n report,\n onOpenDetail: setDetail,\n onRename,\n onReply,\n };\n\n const topRows = lazy ? lazyRoots : tree.roots;\n const loading = lazy ? roots.isLoading : all.isLoading;\n const error = lazy ? roots.error : all.error;\n const allIds = () => [...tree.children.keys()];\n const dragRow = drag ? drag.rowsById.get(drag.id) : undefined;\n\n return (\n <Ctx.Provider value={ctx}>\n <div\n className=\"udc-tree udc:flex udc:min-h-0 udc:flex-1 udc:flex-col\"\n data-testid=\"tree\"\n data-lazy={lazy || undefined}\n data-searching={expansion ? true : undefined}\n >\n {lazy ? null : <AllRowsStatus result={all} />}\n <div className=\"udc:flex udc:items-center udc:gap-1 udc:border-b udc:border-border udc:bg-muted/30 udc:px-3 udc:py-1.5\">\n {lazy ? null : (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n data-testid=\"tree-expand-all\"\n onClick={() => expand.expandAll(allIds())}\n >\n <ChevronsUpDown />\n {t(\"APP\", \"TREE_EXPAND_ALL\")}\n </Button>\n )}\n <Button\n size=\"sm\"\n variant=\"ghost\"\n data-testid=\"tree-collapse-all\"\n onClick={() => {\n setSearchToggles(new Map([...tree.children.keys()].map((id) => [id, false])));\n expand.collapseAll();\n }}\n >\n <ChevronsDownUp />\n {t(\"APP\", \"TREE_COLLAPSE_ALL\")}\n </Button>\n </div>\n <div className=\"udc-scroll-thin udc:min-h-0 udc:flex-1 udc:overflow-auto udc:py-1\">\n {error ? (\n <ErrorState\n error={error}\n onRetry={() => void (lazy ? roots.refetch() : all.refetch())}\n />\n ) : loading ? (\n <div className=\"udc:flex udc:flex-col udc:gap-2 udc:p-4\">\n {SKELETON.map((k, i) => (\n <Skeleton key={k} className=\"udc:h-6\" style={{ marginLeft: (i % 3) * 20 }} />\n ))}\n </div>\n ) : topRows.length === 0 ? (\n <EmptyState filtered={filtered} onClear={onClearFilters} />\n ) : (\n <DndContext\n sensors={sensors}\n collisionDetection={collision}\n onDragStart={onDragStart}\n onDragEnd={onDragEnd}\n onDragCancel={() => setDrag(null)}\n >\n <div role=\"tree\" aria-label={t(\"COLLECTIONS\", collection)} data-testid=\"tree-root\">\n <NodeList rows={topRows} depth={0} />\n </div>\n <DragOverlay dropAnimation={null}>\n {dragRow ? (\n <div className=\"udc:flex udc:max-w-md udc:items-center udc:gap-2 udc:rounded-md udc:border udc:border-border udc:bg-surface udc:px-3 udc:py-1.5 udc:text-[13px] udc:shadow-lg udc:shadow-black/15\">\n <ListTree className=\"udc:size-3.5 udc:text-muted-foreground\" />\n <TreeNodeLabel row={dragRow} />\n </div>\n ) : null}\n </DragOverlay>\n </DndContext>\n )}\n </div>\n </div>\n <CardDetailDialog\n row={detail ?? undefined}\n describe={describe}\n collection={collection}\n labels={{}}\n titleField={opts.label_field}\n bodyField={undefined}\n testId=\"tree-detail\"\n onClose={() => setDetail(null)}\n />\n </Ctx.Provider>\n );\n}\n\nexport function NodeList({ rows, depth }: { rows: readonly Row[]; depth: number }) {\n return (\n // biome-ignore lint/a11y/useSemanticElements: an ARIA tree group has no native element\n <div role=\"group\">\n {rows.map((row) => (\n <TreeNode key={idOf(row)} row={row} depth={depth} />\n ))}\n </div>\n );\n}\n\n/** One level of a lazy tree, read when its parent opens. */\nexport function LazyChildren({ parent, depth }: { parent: string; depth: number }) {\n const { Spinner } = useUiKit();\n const { t } = useI18n();\n const ctx = useTree();\n const { opts, collection, moved, report, dataFilter, dataSearch } = ctx;\n const q = lazyChildrenQuery(opts, parent, dataFilter);\n const res = useUdcCollection({\n collection,\n filter: q.filter,\n sort: q.sort ?? [],\n mode: \"pages\",\n pageLimit: q.limit,\n search: dataSearch,\n });\n useEffect(() => report(parent, res.rows), [report, parent, res.rows]);\n const rows = withMoves(res.rows, parent, moved, ctx);\n if (res.isLoading) {\n return (\n <div\n className=\"udc:flex udc:items-center udc:gap-2 udc:py-1 udc:text-xs udc:text-muted-foreground\"\n style={{ paddingLeft: 12 + (depth + 1) * 20 }}\n data-testid=\"tree-branch-loading\"\n >\n <Spinner className=\"udc:size-3.5\" />\n {t(\"APP\", \"TREE_LOADING\")}\n </div>\n );\n }\n return <NodeList rows={rows} depth={depth + 1} />;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgGA,IAAM,MAAM,cAA8B,IAAI;AAE9C,SAAgB,UAAmB;CACjC,MAAM,MAAM,WAAW,GAAG;CAC1B,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,yCAAyC;CACnE,OAAO;AACT;;AAGA,SAAgB,UACd,MACA,QACA,OACA,KACO;CACP,MAAM,EAAE,SAAS;CACjB,MAAM,OAAO,KAAK,QAAQ,MAAM;EAC9B,MAAM,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC;EAC3B,OAAO,CAAC,KAAK,EAAE,WAAW;CAC5B,CAAC;CACD,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAC7B,QAAQ,MAAM,EAAE,WAAW,UAAU,CAAC,KAAK,MAAM,MAAM,KAAK,CAAC,MAAM,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAChF,KAAK,MAAM,EAAE,GAAG;CACnB,MAAM,UAAU,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC,KAAK,MAAM;EAC5C,MAAM,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC;EAC3B,OAAO,IAAI;GAAE,GAAG;IAAI,KAAK,eAAe,EAAE;IAAS,KAAK,cAAc,EAAE;EAAM,IAAI;CACpF,CAAC;CACD,OAAO,aAAa,SAAS,KAAK,YAAY;AAChD;AAEA,SAAgB,aAAa,OAAsB;CACjD,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,OAAO,MAAM,SAAS,KAAK;CACjC,IAAI,CAAC,MACH,OACE,oBAAC,OAAD;EAAK,WAAU;EA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M,YAAY,OAAO,QAAQ,YAAY,eAAe;CACpE,MAAM,IAAI,kBAAkB,MAAM,QAAQ,UAAU;CACpD,MAAM,MAAM,iBAAiB;EAC3B;EACA,QAAQ,EAAE;EACV,MAAM,EAAE,QAAQ,CAAC;EACjB,MAAM;EACN,WAAW,EAAE;EACb,QAAQ;CACV,CAAC;CACD,gBAAgB,OAAO,QAAQ,IAAI,IAAI,GAAG;EAAC;EAAQ;EAAQ,IAAI;CAAI,CAAC;CACpE,MAAM,OAAO,UAAU,IAAI,MAAM,QAAQ,OAAO,GAAG;CACnD,IAAI,IAAI,WACN,OACE,qBAAC,OAAD;EACE,WAAU;EACV,OAAO,EAAE,aAAa,MAAM,QAAQ,KAAK,GAAG;EAC5C,eAAY;EAHd,UAAA,CAKE,oBAAC,SAAD,EAAS,WAAU,eAAgB,CAAA,GAClC,EAAE,OAAO,cAAc,CACrB;;CAGT,OAAO,oBAAC,UAAD;EAAgB;EAAM,OAAO,QAAQ;CAAI,CAAA;AAClD"}
1
+ {"version":3,"file":"TreeRenderer.js","names":[],"sources":["../../src/tree/TreeRenderer.tsx"],"sourcesContent":["import {\n type CollisionDetection,\n DndContext,\n type DragEndEvent,\n DragOverlay,\n type DragStartEvent,\n PointerSensor,\n pointerWithin,\n TouchSensor,\n useSensor,\n useSensors,\n} from \"@dnd-kit/core\";\nimport {\n type FilterNode,\n isVersionConflict,\n type Row,\n type TreeOptions,\n UdcError,\n} from \"@jsudc/core\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { ChevronsDownUp, ChevronsUpDown, ListTree } from \"lucide-react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useI18n } from \"../i18n/i18n.js\";\nimport { CardDetailDialog } from \"../kanban/CardDetailDialog.js\";\nimport { AllRowsStatus } from \"../renderers/AllRowsStatus.js\";\nimport type { RendererProps } from \"../renderers/types.js\";\nimport { EmptyState, ErrorState } from \"../table/states.js\";\nimport { useUdcAllRows, useUdcCollection, useUdcMutate } from \"../udc/hooks.js\";\nimport { udcKeys } from \"../udc/keys.js\";\nimport { useUdcClient } from \"../udc/provider.js\";\nimport { useUiKit } from \"../ui-kit/context.js\";\nimport { type TreeExpand, useTreeExpand } from \"./expand.js\";\nimport {\n type BuiltTree,\n buildTree,\n canDrop,\n type DropTarget,\n dropParent,\n idOf,\n lazyChildrenQuery,\n lazyRootsQuery,\n numberOf,\n parentOf,\n parseDropId,\n planDrop,\n reparentRequest,\n replyRow,\n searchExpansion,\n siblingsQuery,\n sortSiblings,\n} from \"./model.js\";\nimport { TreeNode, TreeNodeLabel } from \"./TreeNode.js\";\n\n/** A node moved in this session, drawn at its new place until the lists are read again. */\ninterface Moved {\n row: Row;\n parent: string | null;\n order: number;\n}\n\nexport interface TreeCtx {\n collection: string;\n opts: TreeOptions;\n describe: RendererProps[\"describe\"];\n lazy: boolean;\n /** What every lazy branch adds to its own condition: the data view's filter. */\n dataFilter: FilterNode | undefined;\n /** The text sent as `search` with every list (a source that answers search); absent otherwise. */\n dataSearch?: string | undefined;\n /** The highlighted search term (\"\" when none). */\n term: string;\n isOpen: (id: string, depth: number) => boolean;\n setOpen: (id: string, open: boolean) => void;\n /** Non-lazy: the children of a node as built from the loaded rows. */\n childrenOf: (id: string) => Row[];\n /** Rows moved in this session, by id. */\n moved: ReadonlyMap<string, Moved>;\n orphans: ReadonlySet<string>;\n can: { rename: boolean; reply: boolean; reparent: boolean };\n /** The id being dragged, and the loaded rows the drop targets are checked against. */\n drag: { id: string; rowsById: ReadonlyMap<string, Row> } | null;\n /** Lazy branches report the rows they loaded (for drop gating). */\n report: (parent: string, rows: Row[]) => void;\n onOpenDetail: (row: Row) => void;\n onRename: (row: Row, label: string) => Promise<void>;\n onReply: (parent: Row, text: string) => Promise<void>;\n}\n\nconst Ctx = createContext<TreeCtx | null>(null);\n\nexport function useTree(): TreeCtx {\n const ctx = useContext(Ctx);\n if (!ctx) throw new Error(\"useTree needs a <TreeRenderer> above it\");\n return ctx;\n}\n\n/** Rows as drawn under `parent`: the loaded ones minus those moved away, plus those moved here. */\nexport function withMoves(\n rows: readonly Row[],\n parent: string | null,\n moved: ReadonlyMap<string, Moved>,\n ctx: Pick<TreeCtx, \"opts\">,\n): Row[] {\n const { opts } = ctx;\n const stay = rows.filter((r) => {\n const m = moved.get(idOf(r));\n return !m || m.parent === parent;\n });\n const here = [...moved.values()]\n .filter((m) => m.parent === parent && !stay.some((r) => idOf(r) === idOf(m.row)))\n .map((m) => m.row);\n const patched = [...stay, ...here].map((r) => {\n const m = moved.get(idOf(r));\n return m ? { ...r, [opts.parent_field]: m.parent, [opts.order_field]: m.order } : r;\n });\n return sortSiblings(patched, opts.sibling_sort);\n}\n\nexport function TreeRenderer(props: RendererProps) {\n const { t } = useI18n();\n const opts = props.describe.view.tree_options;\n if (!opts) {\n return (\n <div className=\"udc:p-6 udc:text-sm udc:text-muted-foreground\" data-testid=\"tree-no-options\">\n {t(\"APP\", \"TREE_NO_OPTIONS\")}\n </div>\n );\n }\n return <Tree {...props} opts={opts} />;\n}\n\nconst SKELETON = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\n\nfunction Tree({\n collection,\n describe,\n filter,\n baseFilter,\n search,\n listSearch,\n filtered,\n onClearFilters,\n onCount,\n opts,\n}: RendererProps & { opts: TreeOptions }) {\n const { Button, Skeleton, useToast } = useUiKit();\n const { t } = useI18n();\n const { toast } = useToast();\n const client = useUdcClient();\n const qc = useQueryClient();\n const { capabilities, schema, view } = describe;\n const lazy = opts.lazy;\n const term = search.trim();\n // highlight_and_expand on a loaded tree searches in the browser; anything else asks the server.\n const clientSearch = !lazy && opts.on_search.mode === \"highlight_and_expand\";\n // A source that answers search gets the text, unless the tree searches what it loaded.\n const serverSearch = clientSearch ? undefined : listSearch;\n // A lazy tree lists the matches of a filter flat; a source search alone is such a filter too.\n const dataFilter: FilterNode | undefined = clientSearch\n ? baseFilter\n : (filter ?? (serverSearch === undefined ? undefined : { and: [] }));\n const highlight = opts.on_search.mode === \"highlight_and_expand\" ? term : \"\";\n\n // --- rows ----------------------------------------------------------------------\n const all = useUdcAllRows({\n collection,\n filter: dataFilter,\n sort: opts.sibling_sort,\n capabilities,\n enabled: !lazy,\n refetchInterval: describe.view.refresh_interval_ms,\n search: serverSearch,\n });\n const rootsQ = lazyRootsQuery(opts, dataFilter);\n const roots = useUdcCollection({\n collection,\n filter: rootsQ.filter,\n sort: rootsQ.sort ?? [],\n mode: \"pages\",\n pageLimit: rootsQ.limit,\n enabled: lazy,\n search: serverSearch,\n });\n const totalQ = useUdcCollection({\n collection,\n filter: dataFilter,\n mode: \"pages\",\n pageLimit: 1,\n enabled: lazy,\n search: serverSearch,\n });\n\n const [moved, setMoved] = useState<ReadonlyMap<string, Moved>>(new Map());\n const tree: BuiltTree = useMemo(\n () =>\n buildTree(\n all.rows.map((r) => {\n const m = moved.get(idOf(r));\n return m ? { ...r, [opts.parent_field]: m.parent, [opts.order_field]: m.order } : r;\n }),\n opts,\n ),\n [all.rows, moved, opts],\n );\n\n // A filtered lazy tree lists every match; those under a listed parent show when it opens.\n const lazyRoots = useMemo(() => {\n const ids = new Set(roots.rows.map(idOf));\n const top = roots.rows.filter((r) => {\n const p = parentOf(r, opts);\n return p === null || !ids.has(p);\n });\n return withMoves(top, null, moved, { opts });\n }, [roots.rows, moved, opts]);\n const lazyOrphans = useMemo(\n () => new Set(lazyRoots.filter((r) => parentOf(r, opts) !== null).map(idOf)),\n [lazyRoots, opts],\n );\n\n useEffect(() => {\n onCount(\n lazy\n ? totalQ.total === null\n ? null\n : { shown: lazyRoots.length, total: totalQ.total, unit: \"nodes\" }\n : all.total === null\n ? null\n : { shown: all.rows.length, total: all.rows.length, unit: \"nodes\" },\n );\n }, [onCount, lazy, lazyRoots.length, totalQ.total, all.rows.length, all.total]);\n useEffect(() => () => onCount(null), [onCount]);\n\n // --- expand state (with the search's own, while there is a term) ---------------------\n const expand: TreeExpand = useTreeExpand(opts, collection);\n const expansion = useMemo(\n () =>\n clientSearch && term\n ? searchExpansion(tree, term, view.search?.fields ?? [opts.label_field], opts)\n : null,\n [clientSearch, term, tree, view.search?.fields, opts],\n );\n const [searchToggles, setSearchToggles] = useState<ReadonlyMap<string, boolean>>(new Map());\n // biome-ignore lint/correctness/useExhaustiveDependencies: a new term starts from its own expansion\n useEffect(() => setSearchToggles(new Map()), [term]);\n // A filtered lazy tree lists matches at every depth: none is opened by default.\n const defaultsOn = !(lazy && dataFilter !== undefined);\n\n const isOpen = useCallback(\n (id: string, depth: number) => {\n if (expansion) {\n const toggled = searchToggles.get(id);\n if (toggled !== undefined) return toggled;\n if (expansion.open.has(id)) return true;\n return !opts.on_search.collapse_others && expand.isOpen(id, depth);\n }\n return expand.isOpen(id, defaultsOn ? depth : Number.POSITIVE_INFINITY);\n },\n [expansion, searchToggles, opts.on_search.collapse_others, expand, defaultsOn],\n );\n const setOpen = useCallback(\n (id: string, open: boolean) => {\n if (expansion) setSearchToggles((m) => new Map(m).set(id, open));\n else expand.set(id, open);\n },\n [expansion, expand],\n );\n\n // --- writes -------------------------------------------------------------------------\n const can = {\n rename: opts.interactive.rename && capabilities.mutate,\n reply: opts.interactive.reply && capabilities.mutate,\n reparent: opts.interactive.reparent && capabilities.mutate && capabilities.tree_reparent,\n };\n const mutate = useUdcMutate(collection);\n const fail = useCallback(\n (err: unknown, title: string) => {\n if (isVersionConflict(err)) {\n toast({\n variant: \"warning\",\n title: t(\"APP\", \"TREE_CONFLICT_TITLE\"),\n description: t(\"APP\", \"TREE_CONFLICT_BODY\"),\n });\n } else {\n toast({ variant: \"danger\", title, description: (err as Error).message });\n }\n },\n [toast, t],\n );\n\n const onRename = async (row: Row, label: string) => {\n try {\n await mutate.mutateAsync({\n op: \"update\",\n id: idOf(row),\n row: { [opts.label_field]: label },\n expected_version: row.__meta.version,\n });\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_RENAME_FAILED\"));\n }\n };\n\n const onReply = async (parent: Row, text: string) => {\n try {\n await mutate.mutateAsync({\n op: \"insert\",\n row: replyRow(\n opts,\n schema,\n parent,\n tree.children.get(idOf(parent)) ?? [],\n text,\n new Date(),\n ),\n });\n setOpen(idOf(parent), true);\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_REPLY_FAILED\"));\n throw err;\n }\n };\n\n // --- drag and drop ---------------------------------------------------------------------\n const branches = useRef(new Map<string, Row[]>());\n const report = useCallback((parent: string, rows: Row[]) => {\n branches.current.set(parent, rows);\n }, []);\n const loadedRows = (): Map<string, Row> => {\n if (!lazy) return new Map(tree.byId);\n const map = new Map<string, Row>();\n for (const r of roots.rows) map.set(idOf(r), r);\n for (const rows of branches.current.values()) for (const r of rows) map.set(idOf(r), r);\n for (const m of moved.values()) {\n map.set(idOf(m.row), {\n ...m.row,\n [opts.parent_field]: m.parent,\n [opts.order_field]: m.order,\n });\n }\n return map;\n };\n const [drag, setDrag] = useState<TreeCtx[\"drag\"]>(null);\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),\n useSensor(TouchSensor, { activationConstraint: { delay: 180, tolerance: 6 } }),\n );\n // The gap strip above a row wins over the row it overlaps.\n const collision: CollisionDetection = (args) =>\n pointerWithin(args).sort(\n (a, b) =>\n Number(String(b.id).startsWith(\"before:\")) - Number(String(a.id).startsWith(\"before:\")),\n );\n\n const onDragStart = (e: DragStartEvent) =>\n setDrag({ id: String(e.active.id), rowsById: loadedRows() });\n\n const siblingOrders = async (parent: string | null) => {\n const q = siblingsQuery(opts, parent);\n const res = await client.list({ collection, ...q, page: { limit: q.limit } });\n return res.rows.map((r) => ({ id: idOf(r), order: numberOf(r, opts.order_field), row: r }));\n };\n\n const move = async (dragId: string, target: DropTarget, rowsById: ReadonlyMap<string, Row>) => {\n const parent = dropParent(target, rowsById, opts);\n const row = rowsById.get(dragId);\n if (parent === undefined || !row) return;\n // Drawn at once: last under the new parent, or just above the target.\n const above = numberOf(rowsById.get(target.id), opts.order_field);\n const provisional =\n target.kind === \"before\" && above !== null ? above - 0.5 : Number.MAX_SAFE_INTEGER;\n setMoved((m) => new Map(m).set(dragId, { row, parent, order: provisional }));\n if (parent !== null) setOpen(parent, true);\n try {\n let siblings = await siblingOrders(parent);\n let plan = planDrop(dragId, target, parent, siblings);\n let version = row.__meta.version;\n if (plan.collision) {\n if (parent === null) throw new UdcError(\"internal\", t(\"APP\", \"TREE_NO_ROOM\"));\n await client.reindex({\n collection,\n scope: { [opts.parent_field]: parent },\n order_field: opts.order_field,\n });\n siblings = await siblingOrders(parent);\n plan = planDrop(dragId, target, parent, siblings);\n if (plan.collision) throw new UdcError(\"internal\", t(\"APP\", \"TREE_NO_ROOM\"));\n // A reindex of the node's own siblings bumped its version too.\n version = siblings.find((s) => s.id === dragId)?.row.__meta.version ?? version;\n }\n await client.treeReparent(reparentRequest(collection, opts, plan, version));\n } catch (err) {\n fail(err, t(\"APP\", \"TREE_MOVE_FAILED\"));\n } finally {\n await qc.invalidateQueries({ queryKey: udcKeys.lists(collection) });\n setMoved((m) => {\n const next = new Map(m);\n next.delete(dragId);\n return next;\n });\n }\n };\n\n const onDragEnd = (e: DragEndEvent) => {\n const current = drag;\n setDrag(null);\n const target = e.over ? parseDropId(String(e.over.id)) : null;\n if (!current || !target || !canDrop(current.id, target, current.rowsById, opts)) return;\n void move(current.id, target, current.rowsById);\n };\n\n // --- detail -------------------------------------------------------------------------------\n const [detail, setDetail] = useState<Row | null>(null);\n\n const ctx: TreeCtx = {\n collection,\n opts,\n describe,\n lazy,\n dataFilter,\n dataSearch: serverSearch,\n term: highlight,\n isOpen,\n setOpen,\n childrenOf: (id) => tree.children.get(id) ?? [],\n moved,\n orphans: lazy ? lazyOrphans : tree.orphans,\n can,\n drag,\n report,\n onOpenDetail: setDetail,\n onRename,\n onReply,\n };\n\n const topRows = lazy ? lazyRoots : tree.roots;\n const loading = lazy ? roots.isLoading : all.isLoading;\n const error = lazy ? roots.error : all.error;\n const allIds = () => [...tree.children.keys()];\n const dragRow = drag ? drag.rowsById.get(drag.id) : undefined;\n\n return (\n <Ctx.Provider value={ctx}>\n <div\n className=\"udc-tree udc:flex udc:min-h-0 udc:flex-1 udc:flex-col\"\n data-testid=\"tree\"\n data-lazy={lazy || undefined}\n data-searching={expansion ? true : undefined}\n >\n {lazy ? null : <AllRowsStatus result={all} />}\n <div className=\"udc:flex udc:items-center udc:gap-1 udc:border-b udc:border-border udc:bg-muted/30 udc:px-3 udc:py-1.5\">\n {lazy ? null : (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n data-testid=\"tree-expand-all\"\n onClick={() => expand.expandAll(allIds())}\n >\n <ChevronsUpDown />\n {t(\"APP\", \"TREE_EXPAND_ALL\")}\n </Button>\n )}\n <Button\n size=\"sm\"\n variant=\"ghost\"\n data-testid=\"tree-collapse-all\"\n onClick={() => {\n setSearchToggles(new Map([...tree.children.keys()].map((id) => [id, false])));\n expand.collapseAll();\n }}\n >\n <ChevronsDownUp />\n {t(\"APP\", \"TREE_COLLAPSE_ALL\")}\n </Button>\n </div>\n <div className=\"udc-scroll-thin udc:min-h-0 udc:flex-1 udc:overflow-auto udc:py-1\">\n {error ? (\n <ErrorState\n error={error}\n onRetry={() => void (lazy ? roots.refetch() : all.refetch())}\n />\n ) : loading ? (\n <div className=\"udc:flex udc:flex-col udc:gap-2 udc:p-4\">\n {SKELETON.map((k, i) => (\n <Skeleton key={k} className=\"udc:h-6\" style={{ marginLeft: (i % 3) * 20 }} />\n ))}\n </div>\n ) : topRows.length === 0 ? (\n <EmptyState collection={collection} filtered={filtered} onClear={onClearFilters} />\n ) : (\n <DndContext\n sensors={sensors}\n collisionDetection={collision}\n onDragStart={onDragStart}\n onDragEnd={onDragEnd}\n onDragCancel={() => setDrag(null)}\n >\n <div role=\"tree\" aria-label={t(\"COLLECTIONS\", collection)} data-testid=\"tree-root\">\n <NodeList rows={topRows} depth={0} />\n </div>\n <DragOverlay dropAnimation={null}>\n {dragRow ? (\n <div className=\"udc:flex udc:max-w-md udc:items-center udc:gap-2 udc:rounded-md udc:border udc:border-border udc:bg-surface udc:px-3 udc:py-1.5 udc:text-[13px] udc:shadow-lg udc:shadow-black/15\">\n <ListTree className=\"udc:size-3.5 udc:text-muted-foreground\" />\n <TreeNodeLabel row={dragRow} />\n </div>\n ) : null}\n </DragOverlay>\n </DndContext>\n )}\n </div>\n </div>\n <CardDetailDialog\n row={detail ?? undefined}\n describe={describe}\n collection={collection}\n labels={{}}\n titleField={opts.label_field}\n bodyField={undefined}\n testId=\"tree-detail\"\n onClose={() => setDetail(null)}\n />\n </Ctx.Provider>\n );\n}\n\nexport function NodeList({ rows, depth }: { rows: readonly Row[]; depth: number }) {\n return (\n // biome-ignore lint/a11y/useSemanticElements: an ARIA tree group has no native element\n <div role=\"group\">\n {rows.map((row) => (\n <TreeNode key={idOf(row)} row={row} depth={depth} />\n ))}\n </div>\n );\n}\n\n/** One level of a lazy tree, read when its parent opens. */\nexport function LazyChildren({ parent, depth }: { parent: string; depth: number }) {\n const { Spinner } = useUiKit();\n const { t } = useI18n();\n const ctx = useTree();\n const { opts, collection, moved, report, dataFilter, dataSearch } = ctx;\n const q = lazyChildrenQuery(opts, parent, dataFilter);\n const res = useUdcCollection({\n collection,\n filter: q.filter,\n sort: q.sort ?? [],\n mode: \"pages\",\n pageLimit: q.limit,\n search: dataSearch,\n });\n useEffect(() => report(parent, res.rows), [report, parent, res.rows]);\n const rows = withMoves(res.rows, parent, moved, ctx);\n if (res.isLoading) {\n return (\n <div\n className=\"udc:flex udc:items-center udc:gap-2 udc:py-1 udc:text-xs udc:text-muted-foreground\"\n style={{ paddingLeft: 12 + (depth + 1) * 20 }}\n data-testid=\"tree-branch-loading\"\n >\n <Spinner className=\"udc:size-3.5\" />\n {t(\"APP\", \"TREE_LOADING\")}\n </div>\n );\n }\n return <NodeList rows={rows} depth={depth + 1} />;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgGA,IAAM,MAAM,cAA8B,IAAI;AAE9C,SAAgB,UAAmB;CACjC,MAAM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,MAAM,QAAQ,OAAO,GAAG;CACnD,IAAI,IAAI,WACN,OACE,qBAAC,OAAD;EACE,WAAU;EACV,OAAO,EAAE,aAAa,MAAM,QAAQ,KAAK,GAAG;EAC5C,eAAY;EAHd,UAAA,CAKE,oBAAC,SAAD,EAAS,WAAU,eAAgB,CAAA,GAClC,EAAE,OAAO,cAAc,CACrB;;CAGT,OAAO,oBAAC,UAAD;EAAgB;EAAM,OAAO,QAAQ;CAAI,CAAA;AAClD"}
@@ -68,6 +68,19 @@ export declare class UdcChangeFeed {
68
68
  status(collection: string): UdcChangeFeedStatus;
69
69
  /** Called whenever a status may have changed (for `useSyncExternalStore`). */
70
70
  onStatus(listener: () => void): () => void;
71
+ /**
72
+ * Close the stream and open it again for the same collections, now: the
73
+ * server runs the plugin's `context` again, so the stream is scoped to
74
+ * whoever `UdcClient`'s `headers` (or cookies) say is signed in now. For an
75
+ * identity switch with a `headers` function (a demo user, an account
76
+ * switcher, impersonation), or after signing in again, since a stream the
77
+ * server refused is otherwise not asked for until the set of collections
78
+ * changes. Meanwhile the collections report `reconnecting` (polling
79
+ * resumes); once it is open, data fetched before the call is refetched. Does
80
+ * nothing while nobody is subscribed. `UdcProvider changes={{ identity }}`
81
+ * calls it when `identity` changes.
82
+ */
83
+ reconnect(): void;
71
84
  /** Close the stream and drop every timer; the feed opens again when somebody subscribes. */
72
85
  close(): void;
73
86
  private emit;
@@ -74,7 +74,10 @@ var UdcChangeFeed = class {
74
74
  const cur = this.current;
75
75
  if (cur?.collections.has(collection) && !(cur.state === "down" && this.pending)) return cur.state;
76
76
  const pen = this.pending;
77
- if (pen?.collections.has(collection)) return pen.state === "live" ? "live" : pen.state === "down" ? "down" : "connecting";
77
+ if (pen?.collections.has(collection)) {
78
+ if (pen.state === "live" || pen.state === "down") return pen.state;
79
+ return pen.resumed ? "reconnecting" : "connecting";
80
+ }
78
81
  return "connecting";
79
82
  }
80
83
  /** Called whenever a status may have changed (for `useSyncExternalStore`). */
@@ -84,6 +87,32 @@ var UdcChangeFeed = class {
84
87
  this.listeners.delete(listener);
85
88
  };
86
89
  }
90
+ /**
91
+ * Close the stream and open it again for the same collections, now: the
92
+ * server runs the plugin's `context` again, so the stream is scoped to
93
+ * whoever `UdcClient`'s `headers` (or cookies) say is signed in now. For an
94
+ * identity switch with a `headers` function (a demo user, an account
95
+ * switcher, impersonation), or after signing in again, since a stream the
96
+ * server refused is otherwise not asked for until the set of collections
97
+ * changes. Meanwhile the collections report `reconnecting` (polling
98
+ * resumes); once it is open, data fetched before the call is refetched. Does
99
+ * nothing while nobody is subscribed. `UdcProvider changes={{ identity }}`
100
+ * calls it when `identity` changes.
101
+ */
102
+ reconnect() {
103
+ if (this.reconcileTimer) clearTimeout(this.reconcileTimer);
104
+ this.reconcileTimer = null;
105
+ const wanted = this.collections();
106
+ if (wanted.length === 0) {
107
+ this.close();
108
+ return;
109
+ }
110
+ this.pending?.ctl.abort();
111
+ this.current?.ctl.abort();
112
+ this.current = null;
113
+ this.pending = this.open(wanted, keyOf(wanted), true);
114
+ this.emit();
115
+ }
87
116
  /** Close the stream and drop every timer; the feed opens again when somebody subscribes. */
88
117
  close() {
89
118
  if (this.reconcileTimer) clearTimeout(this.reconcileTimer);
@@ -122,17 +151,19 @@ var UdcChangeFeed = class {
122
151
  return;
123
152
  }
124
153
  if (this.pending?.key === key) return;
154
+ const resumed = cur === null && this.pending?.resumed === true;
125
155
  this.pending?.ctl.abort();
126
- this.pending = this.open(wanted, key);
156
+ this.pending = this.open(wanted, key, resumed);
127
157
  this.emit();
128
158
  }
129
- open(collections, key) {
159
+ open(collections, key, resumed = false) {
130
160
  const conn = {
131
161
  key,
132
162
  collections: new Set(collections),
133
163
  ctl: new AbortController(),
134
164
  state: "connecting",
135
- startedAt: Date.now()
165
+ startedAt: Date.now(),
166
+ resumed
136
167
  };
137
168
  const { minDelayMs, maxDelayMs, idleTimeoutMs } = this.opts;
138
169
  const options = {
@@ -1 +1 @@
1
- {"version":3,"file":"changeFeed.js","names":[],"sources":["../../src/udc/changeFeed.ts"],"sourcesContent":["import { type ChangeEvent, isUnauthenticated } from \"@jsudc/core\";\nimport type { ChangesOptions, UdcClient } from \"@jsudc/core/client\";\nimport type { Query, QueryClient } from \"@tanstack/react-query\";\nimport { udcKeys } from \"./keys.js\";\nimport { applyToListRows, type ListCache } from \"./listCache.js\";\nimport { notifyUnauthenticated } from \"./unauthenticated.js\";\n\n/**\n * Where the change feed stands for one collection, as `useUdcChanges` reports\n * it:\n * - `off`: no feed (the provider has none, or the collection does not offer\n * `capabilities.changes`); the view polls as it always did.\n * - `connecting`: subscribed, the stream that carries it is not open yet.\n * - `live`: the stream is open; timer polling is suspended.\n * - `reconnecting`: the stream dropped and is being reopened; polling resumes.\n * - `down`: the server refused the stream (signed out, forbidden, unknown\n * collection); no reconnecting, polling only.\n */\nexport type UdcChangeFeedStatus = \"off\" | \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\n/** `UdcProvider changes={…}`: `true` takes every default. */\nexport interface UdcChangeFeedOptions {\n /** A burst of events for one collection within this many ms makes one invalidation. Default 200. */\n debounceMs?: number;\n /**\n * How long to wait after a view mounts or unmounts before the stream is\n * reopened with the new list of collections, so a page that mounts several\n * views opens one stream. Default 50.\n */\n batchMs?: number;\n /**\n * A `delete` event that names its ids removes those rows from the cached\n * lists at once, before the refetch. Default `true`.\n */\n removeDeleted?: boolean;\n /** Passed to `UdcClient.changes`: the first reconnect delay. */\n minDelayMs?: number;\n /** Passed to `UdcClient.changes`: the longest reconnect delay. */\n maxDelayMs?: number;\n /** Passed to `UdcClient.changes`: a silent stream is reopened after this long. */\n idleTimeoutMs?: number;\n}\n\ninterface Subscriber {\n qc: QueryClient;\n onEvent: ((event: ChangeEvent) => void) | undefined;\n}\n\ntype ConnState = \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\ninterface Conn {\n key: string;\n collections: ReadonlySet<string>;\n ctl: AbortController;\n state: ConnState;\n /** When the stream was asked for: data fetched before it may have missed an event. */\n startedAt: number;\n}\n\nconst keyOf = (collections: Iterable<string>) => [...collections].sort().join(\"\\n\");\n\n/**\n * The change feed of one `UdcProvider`: one stream for every collection a\n * mounted view (or hook) shows. Collections are reference-counted; when the\n * set changes the new stream is opened first and the old one closed only once\n * the new one is subscribed, so the collections that stay miss nothing. An\n * event marks its collection dirty and, after `debounceMs`, its lists, lookup\n * batches and lookup options are invalidated; \"reconnected\" invalidates every\n * collection of the stream. Framework-free apart from TanStack's QueryClient;\n * `useUdcChanges` is the React side.\n */\nexport class UdcChangeFeed {\n readonly client: UdcClient;\n private readonly opts: Required<\n Omit<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">\n > &\n Pick<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">;\n private readonly subs = new Map<string, Set<Subscriber>>();\n private current: Conn | null = null;\n private pending: Conn | null = null;\n private reconcileTimer: ReturnType<typeof setTimeout> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly dirty = new Map<string, number | undefined>();\n private readonly listeners = new Set<() => void>();\n\n constructor(client: UdcClient, options: UdcChangeFeedOptions = {}) {\n this.client = client;\n this.opts = {\n debounceMs: options.debounceMs ?? 200,\n batchMs: options.batchMs ?? 50,\n removeDeleted: options.removeDeleted ?? true,\n ...(options.minDelayMs === undefined ? {} : { minDelayMs: options.minDelayMs }),\n ...(options.maxDelayMs === undefined ? {} : { maxDelayMs: options.maxDelayMs }),\n ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),\n };\n }\n\n /**\n * Count one more user of `collection` (whose queries live in `qc`); the\n * returned function counts it out. `onEvent` hears every event of the\n * collection as it arrives, before the debounced invalidation.\n */\n subscribe(collection: string, qc: QueryClient, onEvent?: (event: ChangeEvent) => void) {\n const sub: Subscriber = { qc, onEvent };\n let set = this.subs.get(collection);\n if (!set) {\n set = new Set();\n this.subs.set(collection, set);\n }\n set.add(sub);\n this.scheduleReconcile();\n this.emit();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n const s = this.subs.get(collection);\n s?.delete(sub);\n if (s?.size === 0) this.subs.delete(collection);\n this.scheduleReconcile();\n this.emit();\n };\n }\n\n /** The collections the stream is (or is about to be) asked for. */\n collections(): string[] {\n return [...this.subs.keys()].sort();\n }\n\n /** Where the feed stands for `collection`. */\n status(collection: string): UdcChangeFeedStatus {\n if (!this.subs.has(collection)) return \"off\";\n const cur = this.current;\n if (cur?.collections.has(collection) && !(cur.state === \"down\" && this.pending)) {\n return cur.state;\n }\n const pen = this.pending;\n if (pen?.collections.has(collection)) {\n return pen.state === \"live\" ? \"live\" : pen.state === \"down\" ? \"down\" : \"connecting\";\n }\n return \"connecting\";\n }\n\n /** Called whenever a status may have changed (for `useSyncExternalStore`). */\n onStatus(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Close the stream and drop every timer; the feed opens again when somebody subscribes. */\n close(): void {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.reconcileTimer = this.flushTimer = null;\n this.dirty.clear();\n this.pending?.ctl.abort();\n this.current?.ctl.abort();\n this.pending = this.current = null;\n this.emit();\n }\n\n // The stream ---------------------------------------------------------------\n\n private emit() {\n for (const l of this.listeners) l();\n }\n\n private scheduleReconcile() {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = setTimeout(() => {\n this.reconcileTimer = null;\n this.reconcile();\n }, this.opts.batchMs);\n }\n\n private reconcile() {\n const wanted = this.collections();\n const key = keyOf(wanted);\n if (wanted.length === 0) {\n this.close();\n return;\n }\n const cur = this.current;\n if (cur && cur.key === key) {\n // The set went back to what is open: a reopen in flight is not needed. A stream the\n // server refused for this very set stays refused until the set changes.\n if (this.pending) {\n this.pending.ctl.abort();\n this.pending = null;\n this.emit();\n }\n return;\n }\n if (this.pending?.key === key) return;\n this.pending?.ctl.abort();\n this.pending = this.open(wanted, key);\n this.emit();\n }\n\n private open(collections: string[], key: string): Conn {\n const conn: Conn = {\n key,\n collections: new Set(collections),\n ctl: new AbortController(),\n state: \"connecting\",\n startedAt: Date.now(),\n };\n const { minDelayMs, maxDelayMs, idleTimeoutMs } = this.opts;\n const options: ChangesOptions = {\n collections,\n signal: conn.ctl.signal,\n onChange: (event) => this.deliver(conn, event),\n onOpen: ({ reconnected }) => this.opened(conn, reconnected),\n onError: () => this.dropped(conn),\n ...(minDelayMs === undefined ? {} : { minDelayMs }),\n ...(maxDelayMs === undefined ? {} : { maxDelayMs }),\n ...(idleTimeoutMs === undefined ? {} : { idleTimeoutMs }),\n };\n this.client.changes(options).then(\n () => {},\n (err: unknown) => this.refused(conn, err),\n );\n return conn;\n }\n\n private live(conn: Conn) {\n return conn === this.current || conn === this.pending;\n }\n\n private opened(conn: Conn, reconnected: boolean) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const prev = this.current;\n if (conn === this.pending) {\n // The new stream is subscribed: it takes over, the old one closes.\n this.current = conn;\n this.pending = null;\n if (prev && prev !== conn) prev.ctl.abort();\n }\n conn.state = \"live\";\n if (reconnected) {\n // Changes made while the stream was down were not sent: refetch everything it carries.\n for (const c of conn.collections) this.markDirty(c);\n } else {\n // A collection that was not carried by an open stream until now may have changed between\n // its last fetch and this subscription: refetch what was fetched before the stream was asked for.\n const carried = prev && prev !== conn && prev.state === \"live\" ? prev.collections : new Set();\n for (const c of conn.collections) if (!carried.has(c)) this.markDirty(c, conn.startedAt);\n }\n this.emit();\n }\n\n private dropped(conn: Conn) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"reconnecting\";\n this.emit();\n }\n\n /** `changes()` rejected: the server refused (401, 403, 404, 400). No reconnecting. */\n private refused(conn: Conn, err: unknown) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"down\";\n if (isUnauthenticated(err))\n for (const qc of this.queryClients()) notifyUnauthenticated(qc, err);\n // A refused reopen stays as `pending` in state `down`: the old stream (if open) still carries\n // what it carried, and the same set is not asked for again until it changes.\n this.emit();\n }\n\n private deliver(conn: Conn, event: ChangeEvent) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const subs = this.subs.get(event.collection);\n if (!subs) return; // Not a collection on screen.\n for (const s of [...subs]) {\n try {\n s.onEvent?.(event);\n } catch (err) {\n console.error(\"useUdcChanges: onEvent threw\", err);\n }\n }\n if (event.op === \"delete\" && event.ids?.length && this.opts.removeDeleted) {\n const gone = new Set(event.ids);\n for (const qc of this.queryClients(event.collection)) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(event.collection) }, (data) =>\n applyToListRows(data, (r) => gone.has(r.__meta.id)),\n );\n }\n }\n this.markDirty(event.collection);\n }\n\n // Invalidation -------------------------------------------------------------\n\n /**\n * Refetch `collection` after the debounce; `before` limits it to queries\n * whose data is older than that time (a later plain mark lifts the limit).\n */\n private markDirty(collection: string, before?: number) {\n const had = this.dirty.has(collection);\n const prev = this.dirty.get(collection);\n const next =\n before === undefined || (had && prev === undefined) ? undefined : Math.max(prev ?? 0, before);\n this.dirty.set(collection, next);\n this.scheduleFlush();\n }\n\n private scheduleFlush() {\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.flushTimer = setTimeout(() => this.flush(), this.opts.debounceMs);\n }\n\n private flush() {\n this.flushTimer = null;\n const clients = this.queryClients();\n // A mutation in flight invalidates when it settles; refetching under it would show the\n // row as it was before the optimistic patch. Wait for it.\n if ([...clients].some((qc) => qc.isMutating() > 0)) {\n this.scheduleFlush();\n return;\n }\n const batch = [...this.dirty];\n this.dirty.clear();\n for (const [collection, before] of batch) {\n const predicate =\n before === undefined\n ? undefined\n : (q: Query) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < before;\n for (const qc of this.queryClients(collection)) {\n for (const queryKey of invalidatedKeys(collection)) {\n void qc.invalidateQueries(predicate ? { queryKey, predicate } : { queryKey });\n }\n }\n }\n }\n\n /** The query clients of `collection`'s subscribers, or of everybody's. */\n private queryClients(collection?: string): Set<QueryClient> {\n const out = new Set<QueryClient>();\n const sets = collection === undefined ? [...this.subs.values()] : [this.subs.get(collection)];\n for (const set of sets) for (const s of set ?? []) out.add(s.qc);\n return out;\n }\n}\n\n/** What a change of `collection` makes stale: its lists, the lookups into it, its picker options. */\nexport function invalidatedKeys(collection: string): (readonly unknown[])[] {\n return [\n udcKeys.lists(collection),\n udcKeys.lookups(collection),\n [\"udc\", \"lookup-options\", collection],\n ];\n}\n"],"mappings":";;;;;AA2DA,IAAM,SAAS,gBAAkC,CAAC,GAAG,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;AAYlF,IAAa,gBAAb,MAA2B;CACzB;CACA;CAIA,uBAAwB,IAAI,IAA6B;CACzD,UAA+B;CAC/B,UAA+B;CAC/B,iBAA+D;CAC/D,aAA2D;CAC3D,wBAAyB,IAAI,IAAgC;CAC7D,4BAA6B,IAAI,IAAgB;CAEjD,YAAY,QAAmB,UAAgC,CAAC,GAAG;EACjE,KAAK,SAAS;EACd,KAAK,OAAO;GACV,YAAY,QAAQ,cAAc;GAClC,SAAS,QAAQ,WAAW;GAC5B,eAAe,QAAQ,iBAAiB;GACxC,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;GAC7E,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;GAC7E,GAAI,QAAQ,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;EACxF;CACF;;;;;;CAOA,UAAU,YAAoB,IAAiB,SAAwC;EACrF,MAAM,MAAkB;GAAE;GAAI;EAAQ;EACtC,IAAI,MAAM,KAAK,KAAK,IAAI,UAAU;EAClC,IAAI,CAAC,KAAK;GACR,sBAAM,IAAI,IAAI;GACd,KAAK,KAAK,IAAI,YAAY,GAA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F;CACF;;CAGA,aAAqB,YAAuC;EAC1D,MAAM,sBAAM,IAAI,IAAiB;EACjC,MAAM,OAAO,eAAe,KAAA,IAAY,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,KAAK,KAAK,IAAI,UAAU,CAAC;EAC5F,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC,GAAG,IAAI,IAAI,EAAE,EAAE;EAC/D,OAAO;CACT;AACF;;AAGA,SAAgB,gBAAgB,YAA4C;CAC1E,OAAO;EACL,QAAQ,MAAM,UAAU;EACxB,QAAQ,QAAQ,UAAU;EAC1B;GAAC;GAAO;GAAkB;EAAU;CACtC;AACF"}
1
+ {"version":3,"file":"changeFeed.js","names":[],"sources":["../../src/udc/changeFeed.ts"],"sourcesContent":["import { type ChangeEvent, isUnauthenticated } from \"@jsudc/core\";\nimport type { ChangesOptions, UdcClient } from \"@jsudc/core/client\";\nimport type { Query, QueryClient } from \"@tanstack/react-query\";\nimport { udcKeys } from \"./keys.js\";\nimport { applyToListRows, type ListCache } from \"./listCache.js\";\nimport { notifyUnauthenticated } from \"./unauthenticated.js\";\n\n/**\n * Where the change feed stands for one collection, as `useUdcChanges` reports\n * it:\n * - `off`: no feed (the provider has none, or the collection does not offer\n * `capabilities.changes`); the view polls as it always did.\n * - `connecting`: subscribed, the stream that carries it is not open yet.\n * - `live`: the stream is open; timer polling is suspended.\n * - `reconnecting`: the stream dropped and is being reopened; polling resumes.\n * - `down`: the server refused the stream (signed out, forbidden, unknown\n * collection); no reconnecting, polling only.\n */\nexport type UdcChangeFeedStatus = \"off\" | \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\n/** `UdcProvider changes={…}`: `true` takes every default. */\nexport interface UdcChangeFeedOptions {\n /** A burst of events for one collection within this many ms makes one invalidation. Default 200. */\n debounceMs?: number;\n /**\n * How long to wait after a view mounts or unmounts before the stream is\n * reopened with the new list of collections, so a page that mounts several\n * views opens one stream. Default 50.\n */\n batchMs?: number;\n /**\n * A `delete` event that names its ids removes those rows from the cached\n * lists at once, before the refetch. Default `true`.\n */\n removeDeleted?: boolean;\n /** Passed to `UdcClient.changes`: the first reconnect delay. */\n minDelayMs?: number;\n /** Passed to `UdcClient.changes`: the longest reconnect delay. */\n maxDelayMs?: number;\n /** Passed to `UdcClient.changes`: a silent stream is reopened after this long. */\n idleTimeoutMs?: number;\n}\n\ninterface Subscriber {\n qc: QueryClient;\n onEvent: ((event: ChangeEvent) => void) | undefined;\n}\n\ntype ConnState = \"connecting\" | \"live\" | \"reconnecting\" | \"down\";\n\ninterface Conn {\n key: string;\n collections: ReadonlySet<string>;\n ctl: AbortController;\n state: ConnState;\n /** When the stream was asked for: data fetched before it may have missed an event. */\n startedAt: number;\n /** Opened by `reconnect()`: no stream carries its collections until it is open (\"reconnecting\"). */\n resumed: boolean;\n}\n\nconst keyOf = (collections: Iterable<string>) => [...collections].sort().join(\"\\n\");\n\n/**\n * The change feed of one `UdcProvider`: one stream for every collection a\n * mounted view (or hook) shows. Collections are reference-counted; when the\n * set changes the new stream is opened first and the old one closed only once\n * the new one is subscribed, so the collections that stay miss nothing. An\n * event marks its collection dirty and, after `debounceMs`, its lists, lookup\n * batches and lookup options are invalidated; \"reconnected\" invalidates every\n * collection of the stream. Framework-free apart from TanStack's QueryClient;\n * `useUdcChanges` is the React side.\n */\nexport class UdcChangeFeed {\n readonly client: UdcClient;\n private readonly opts: Required<\n Omit<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">\n > &\n Pick<UdcChangeFeedOptions, \"minDelayMs\" | \"maxDelayMs\" | \"idleTimeoutMs\">;\n private readonly subs = new Map<string, Set<Subscriber>>();\n private current: Conn | null = null;\n private pending: Conn | null = null;\n private reconcileTimer: ReturnType<typeof setTimeout> | null = null;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly dirty = new Map<string, number | undefined>();\n private readonly listeners = new Set<() => void>();\n\n constructor(client: UdcClient, options: UdcChangeFeedOptions = {}) {\n this.client = client;\n this.opts = {\n debounceMs: options.debounceMs ?? 200,\n batchMs: options.batchMs ?? 50,\n removeDeleted: options.removeDeleted ?? true,\n ...(options.minDelayMs === undefined ? {} : { minDelayMs: options.minDelayMs }),\n ...(options.maxDelayMs === undefined ? {} : { maxDelayMs: options.maxDelayMs }),\n ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),\n };\n }\n\n /**\n * Count one more user of `collection` (whose queries live in `qc`); the\n * returned function counts it out. `onEvent` hears every event of the\n * collection as it arrives, before the debounced invalidation.\n */\n subscribe(collection: string, qc: QueryClient, onEvent?: (event: ChangeEvent) => void) {\n const sub: Subscriber = { qc, onEvent };\n let set = this.subs.get(collection);\n if (!set) {\n set = new Set();\n this.subs.set(collection, set);\n }\n set.add(sub);\n this.scheduleReconcile();\n this.emit();\n let done = false;\n return () => {\n if (done) return;\n done = true;\n const s = this.subs.get(collection);\n s?.delete(sub);\n if (s?.size === 0) this.subs.delete(collection);\n this.scheduleReconcile();\n this.emit();\n };\n }\n\n /** The collections the stream is (or is about to be) asked for. */\n collections(): string[] {\n return [...this.subs.keys()].sort();\n }\n\n /** Where the feed stands for `collection`. */\n status(collection: string): UdcChangeFeedStatus {\n if (!this.subs.has(collection)) return \"off\";\n const cur = this.current;\n if (cur?.collections.has(collection) && !(cur.state === \"down\" && this.pending)) {\n return cur.state;\n }\n const pen = this.pending;\n if (pen?.collections.has(collection)) {\n if (pen.state === \"live\" || pen.state === \"down\") return pen.state;\n return pen.resumed ? \"reconnecting\" : \"connecting\";\n }\n return \"connecting\";\n }\n\n /** Called whenever a status may have changed (for `useSyncExternalStore`). */\n onStatus(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Close the stream and open it again for the same collections, now: the\n * server runs the plugin's `context` again, so the stream is scoped to\n * whoever `UdcClient`'s `headers` (or cookies) say is signed in now. For an\n * identity switch with a `headers` function (a demo user, an account\n * switcher, impersonation), or after signing in again, since a stream the\n * server refused is otherwise not asked for until the set of collections\n * changes. Meanwhile the collections report `reconnecting` (polling\n * resumes); once it is open, data fetched before the call is refetched. Does\n * nothing while nobody is subscribed. `UdcProvider changes={{ identity }}`\n * calls it when `identity` changes.\n */\n reconnect(): void {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = null;\n const wanted = this.collections();\n if (wanted.length === 0) {\n this.close();\n return;\n }\n // The open stream carries the previous identity's scope: nothing of it is kept.\n this.pending?.ctl.abort();\n this.current?.ctl.abort();\n this.current = null;\n this.pending = this.open(wanted, keyOf(wanted), true);\n this.emit();\n }\n\n /** Close the stream and drop every timer; the feed opens again when somebody subscribes. */\n close(): void {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.reconcileTimer = this.flushTimer = null;\n this.dirty.clear();\n this.pending?.ctl.abort();\n this.current?.ctl.abort();\n this.pending = this.current = null;\n this.emit();\n }\n\n // The stream ---------------------------------------------------------------\n\n private emit() {\n for (const l of this.listeners) l();\n }\n\n private scheduleReconcile() {\n if (this.reconcileTimer) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = setTimeout(() => {\n this.reconcileTimer = null;\n this.reconcile();\n }, this.opts.batchMs);\n }\n\n private reconcile() {\n const wanted = this.collections();\n const key = keyOf(wanted);\n if (wanted.length === 0) {\n this.close();\n return;\n }\n const cur = this.current;\n if (cur && cur.key === key) {\n // The set went back to what is open: a reopen in flight is not needed. A stream the\n // server refused for this very set stays refused until the set changes.\n if (this.pending) {\n this.pending.ctl.abort();\n this.pending = null;\n this.emit();\n }\n return;\n }\n if (this.pending?.key === key) return;\n // A set that changes while `reconnect()` is reopening: still no stream carries it.\n const resumed = cur === null && this.pending?.resumed === true;\n this.pending?.ctl.abort();\n this.pending = this.open(wanted, key, resumed);\n this.emit();\n }\n\n private open(collections: string[], key: string, resumed = false): Conn {\n const conn: Conn = {\n key,\n collections: new Set(collections),\n ctl: new AbortController(),\n state: \"connecting\",\n startedAt: Date.now(),\n resumed,\n };\n const { minDelayMs, maxDelayMs, idleTimeoutMs } = this.opts;\n const options: ChangesOptions = {\n collections,\n signal: conn.ctl.signal,\n onChange: (event) => this.deliver(conn, event),\n onOpen: ({ reconnected }) => this.opened(conn, reconnected),\n onError: () => this.dropped(conn),\n ...(minDelayMs === undefined ? {} : { minDelayMs }),\n ...(maxDelayMs === undefined ? {} : { maxDelayMs }),\n ...(idleTimeoutMs === undefined ? {} : { idleTimeoutMs }),\n };\n this.client.changes(options).then(\n () => {},\n (err: unknown) => this.refused(conn, err),\n );\n return conn;\n }\n\n private live(conn: Conn) {\n return conn === this.current || conn === this.pending;\n }\n\n private opened(conn: Conn, reconnected: boolean) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const prev = this.current;\n if (conn === this.pending) {\n // The new stream is subscribed: it takes over, the old one closes.\n this.current = conn;\n this.pending = null;\n if (prev && prev !== conn) prev.ctl.abort();\n }\n conn.state = \"live\";\n if (reconnected) {\n // Changes made while the stream was down were not sent: refetch everything it carries.\n for (const c of conn.collections) this.markDirty(c);\n } else {\n // A collection that was not carried by an open stream until now may have changed between\n // its last fetch and this subscription: refetch what was fetched before the stream was asked for.\n const carried = prev && prev !== conn && prev.state === \"live\" ? prev.collections : new Set();\n for (const c of conn.collections) if (!carried.has(c)) this.markDirty(c, conn.startedAt);\n }\n this.emit();\n }\n\n private dropped(conn: Conn) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"reconnecting\";\n this.emit();\n }\n\n /** `changes()` rejected: the server refused (401, 403, 404, 400). No reconnecting. */\n private refused(conn: Conn, err: unknown) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n conn.state = \"down\";\n if (isUnauthenticated(err))\n for (const qc of this.queryClients()) notifyUnauthenticated(qc, err);\n // A refused reopen stays as `pending` in state `down`: the old stream (if open) still carries\n // what it carried, and the same set is not asked for again until it changes.\n this.emit();\n }\n\n private deliver(conn: Conn, event: ChangeEvent) {\n if (!this.live(conn) || conn.ctl.signal.aborted) return;\n const subs = this.subs.get(event.collection);\n if (!subs) return; // Not a collection on screen.\n for (const s of [...subs]) {\n try {\n s.onEvent?.(event);\n } catch (err) {\n console.error(\"useUdcChanges: onEvent threw\", err);\n }\n }\n if (event.op === \"delete\" && event.ids?.length && this.opts.removeDeleted) {\n const gone = new Set(event.ids);\n for (const qc of this.queryClients(event.collection)) {\n qc.setQueriesData<ListCache>({ queryKey: udcKeys.lists(event.collection) }, (data) =>\n applyToListRows(data, (r) => gone.has(r.__meta.id)),\n );\n }\n }\n this.markDirty(event.collection);\n }\n\n // Invalidation -------------------------------------------------------------\n\n /**\n * Refetch `collection` after the debounce; `before` limits it to queries\n * whose data is older than that time (a later plain mark lifts the limit).\n */\n private markDirty(collection: string, before?: number) {\n const had = this.dirty.has(collection);\n const prev = this.dirty.get(collection);\n const next =\n before === undefined || (had && prev === undefined) ? undefined : Math.max(prev ?? 0, before);\n this.dirty.set(collection, next);\n this.scheduleFlush();\n }\n\n private scheduleFlush() {\n if (this.flushTimer) clearTimeout(this.flushTimer);\n this.flushTimer = setTimeout(() => this.flush(), this.opts.debounceMs);\n }\n\n private flush() {\n this.flushTimer = null;\n const clients = this.queryClients();\n // A mutation in flight invalidates when it settles; refetching under it would show the\n // row as it was before the optimistic patch. Wait for it.\n if ([...clients].some((qc) => qc.isMutating() > 0)) {\n this.scheduleFlush();\n return;\n }\n const batch = [...this.dirty];\n this.dirty.clear();\n for (const [collection, before] of batch) {\n const predicate =\n before === undefined\n ? undefined\n : (q: Query) => q.state.dataUpdatedAt > 0 && q.state.dataUpdatedAt < before;\n for (const qc of this.queryClients(collection)) {\n for (const queryKey of invalidatedKeys(collection)) {\n void qc.invalidateQueries(predicate ? { queryKey, predicate } : { queryKey });\n }\n }\n }\n }\n\n /** The query clients of `collection`'s subscribers, or of everybody's. */\n private queryClients(collection?: string): Set<QueryClient> {\n const out = new Set<QueryClient>();\n const sets = collection === undefined ? [...this.subs.values()] : [this.subs.get(collection)];\n for (const set of sets) for (const s of set ?? []) out.add(s.qc);\n return out;\n }\n}\n\n/** What a change of `collection` makes stale: its lists, the lookups into it, its picker options. */\nexport function invalidatedKeys(collection: string): (readonly unknown[])[] {\n return [\n udcKeys.lists(collection),\n udcKeys.lookups(collection),\n [\"udc\", \"lookup-options\", collection],\n ];\n}\n"],"mappings":";;;;;AA6DA,IAAM,SAAS,gBAAkC,CAAC,GAAG,WAAW,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;AAYlF,IAAa,gBAAb,MAA2B;CACzB;CACA;CAIA,uBAAwB,IAAI,IAA6B;CACzD,UAA+B;CAC/B,UAA+B;CAC/B,iBAA+D;CAC/D,aAA2D;CAC3D,wBAAyB,IAAI,IAAgC;CAC7D,4BAA6B,IAAI,IAAgB;CAEjD,YAAY,QAAmB,UAAgC,CAAC,GAAG;EACjE,KAAK,SAAS;EACd,KAAK,OAAO;GACV,YAAY,QAAQ,cAAc;GAClC,SAAS,QAAQ,WAAW;GAC5B,eAAe,QAAQ,iBAAiB;GACxC,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;GAC7E,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;GAC7E,GAAI,QAAQ,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;EACxF;CACF;;;;;;CAOA,UAAU,YAAoB,IAAiB,SAAwC;EACrF,MAAM,MAAkB;GAAE;GAAI;EAAQ;EACtC,IAAI,MAAM,KAAK,KAAK,IAAI,UAAU;EAClC,IAAI,CAAC,KAAK;GACR,sBAAM,IAAI,IAAI;GACd,KAAK,KAAK,IAAI,YAAY,GAAG;EAC/B;EACA,IAAI,IAAI,GAAG;EACX,KAAK,kBAAkB;EACvB,KAAK,KAAK;EACV,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AAK,cAAc;GACnB;EACF;EACA,MAAM,QAAQ,CAAC,GAAG,KAAK,KAAK;EAC5B,KAAK,MAAM,MAAM;EACjB,KAAK,MAAM,CAAC,YAAY,WAAW,OAAO;GACxC,MAAM,YACJ,WAAW,KAAA,IACP,KAAA,KACC,MAAa,EAAE,MAAM,gBAAgB,KAAK,EAAE,MAAM,gBAAgB;GACzE,KAAK,MAAM,MAAM,KAAK,aAAa,UAAU,GAC3C,KAAK,MAAM,YAAY,gBAAgB,UAAU,GAC/C,GAAQ,kBAAkB,YAAY;IAAE;IAAU;GAAU,IAAI,EAAE,SAAS,CAAC;EAGlF;CACF;;CAGA,aAAqB,YAAuC;EAC1D,MAAM,sBAAM,IAAI,IAAiB;EACjC,MAAM,OAAO,eAAe,KAAA,IAAY,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,KAAK,KAAK,IAAI,UAAU,CAAC;EAC5F,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC,GAAG,IAAI,IAAI,EAAE,EAAE;EAC/D,OAAO;CACT;AACF;;AAGA,SAAgB,gBAAgB,YAA4C;CAC1E,OAAO;EACL,QAAQ,MAAM,UAAU;EACxB,QAAQ,QAAQ,UAAU;EAC1B;GAAC;GAAO;GAAkB;EAAU;CACtC;AACF"}
@@ -1,6 +1,12 @@
1
1
  import { type Capabilities, type ChangeEvent } from "@jsudc/core";
2
2
  import type { UdcChangeFeed, UdcChangeFeedStatus } from "./changeFeed.js";
3
- /** The provider's change feed; `null` when `UdcProvider changes` is off (the default). */
3
+ /**
4
+ * The provider's change feed; `null` when `UdcProvider changes` is off (the
5
+ * default). A host may provide a `UdcChangeFeed` of its own here (one per
6
+ * user, say: `useMemo(() => new UdcChangeFeed(client, opts), [client, user])`,
7
+ * closed with `feed.close()` when replaced); a `UdcProvider` below it with
8
+ * the same client and without `changes` uses it.
9
+ */
4
10
  export declare const UdcChangeFeedContext: import("react").Context<UdcChangeFeed | null>;
5
11
  /** The provider's change feed, or `null` without one. */
6
12
  export declare function useUdcChangeFeed(): UdcChangeFeed | null;
@@ -4,7 +4,13 @@ import { sourcePushesChanges } from "@jsudc/core";
4
4
  import { createContext, useContext, useEffect, useRef, useSyncExternalStore } from "react";
5
5
  import { QueryClientContext, useQueries } from "@tanstack/react-query";
6
6
  // src/udc/changes.ts
7
- /** The provider's change feed; `null` when `UdcProvider changes` is off (the default). */
7
+ /**
8
+ * The provider's change feed; `null` when `UdcProvider changes` is off (the
9
+ * default). A host may provide a `UdcChangeFeed` of its own here (one per
10
+ * user, say: `useMemo(() => new UdcChangeFeed(client, opts), [client, user])`,
11
+ * closed with `feed.close()` when replaced); a `UdcProvider` below it with
12
+ * the same client and without `changes` uses it.
13
+ */
8
14
  var UdcChangeFeedContext = createContext(null);
9
15
  /** The provider's change feed, or `null` without one. */
10
16
  function useUdcChangeFeed() {