@marktiderman/genesis-core 1.12.0 → 1.14.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.
- package/README.md +77 -0
- package/dist/chunk-3B4IFDMK.js +117 -0
- package/dist/chunk-3B4IFDMK.js.map +1 -0
- package/dist/{chunk-S2ZXUNXB.js → chunk-3LZAZ5KB.js} +3 -3
- package/dist/{chunk-S2ZXUNXB.js.map → chunk-3LZAZ5KB.js.map} +1 -1
- package/dist/chunk-7FVTGKTX.js +8 -0
- package/dist/chunk-7FVTGKTX.js.map +1 -0
- package/dist/{chunk-NMFABW4Y.js → chunk-7YHGNPPO.js} +5 -5
- package/dist/{chunk-NMFABW4Y.js.map → chunk-7YHGNPPO.js.map} +1 -1
- package/dist/chunk-AUVKRXRC.js +81 -0
- package/dist/chunk-AUVKRXRC.js.map +1 -0
- package/dist/{chunk-TOU2CMDH.js → chunk-K7K6NY3C.js} +168 -168
- package/dist/chunk-K7K6NY3C.js.map +1 -0
- package/dist/chunk-LFWSTJWI.js +108 -0
- package/dist/chunk-LFWSTJWI.js.map +1 -0
- package/dist/{chunk-RCAP3Q4T.js → chunk-OYIUIW7C.js} +3 -2
- package/dist/chunk-OYIUIW7C.js.map +1 -0
- package/dist/chunk-OZYF55E3.js +6 -0
- package/dist/chunk-OZYF55E3.js.map +1 -0
- package/dist/chunk-PA6WJE5E.js +115 -0
- package/dist/chunk-PA6WJE5E.js.map +1 -0
- package/dist/chunk-PP3XFFQM.js +85 -0
- package/dist/chunk-PP3XFFQM.js.map +1 -0
- package/dist/{chunk-BGTXN2E6.js → chunk-RF6YVWHX.js} +4 -4
- package/dist/{chunk-BGTXN2E6.js.map → chunk-RF6YVWHX.js.map} +1 -1
- package/dist/{chunk-NZPJI7FC.js → chunk-UGGMJUFQ.js} +45 -13
- package/dist/chunk-UGGMJUFQ.js.map +1 -0
- package/dist/{chunk-KXVHDK3Q.js → chunk-UV3ROHQA.js} +27 -5
- package/dist/chunk-UV3ROHQA.js.map +1 -0
- package/dist/chunk-YDDPFSQ6.js +35 -0
- package/dist/chunk-YDDPFSQ6.js.map +1 -0
- package/dist/{chunk-OSPLIKSH.js → chunk-YFTGLQDQ.js} +18 -8
- package/dist/chunk-YFTGLQDQ.js.map +1 -0
- package/dist/chunk-ZIMQUFXD.js +154 -0
- package/dist/chunk-ZIMQUFXD.js.map +1 -0
- package/dist/csv.d.ts +41 -0
- package/dist/csv.js +77 -0
- package/dist/csv.js.map +1 -0
- package/dist/dates.js +1 -115
- package/dist/dates.js.map +1 -1
- package/dist/errors.d.ts +69 -0
- package/dist/errors.js +7 -0
- package/dist/errors.js.map +1 -0
- package/dist/hooks/index.d.ts +7 -43
- package/dist/hooks/index.js +14 -11
- package/dist/hooks/live-cache.d.ts +15 -0
- package/dist/hooks/live-cache.js +3 -0
- package/dist/hooks/live-cache.js.map +1 -0
- package/dist/hooks/mutation-mode.d.ts +2 -2
- package/dist/hooks/mutation-mode.js +2 -2
- package/dist/hooks/related-keys.d.ts +2 -2
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.d.ts +18 -2
- package/dist/hooks/use-infinite-resource.js +4 -3
- package/dist/hooks/use-live.d.ts +15 -3
- package/dist/hooks/use-live.js +2 -1
- package/dist/hooks/use-one.d.ts +2 -2
- package/dist/hooks/use-one.js +4 -3
- package/dist/hooks/use-resource-form.d.ts +9 -2
- package/dist/hooks/use-resource-form.js +6 -5
- package/dist/hooks/use-resource.d.ts +2 -2
- package/dist/hooks/use-resource.js +5 -4
- package/dist/hooks/use-write.d.ts +2 -2
- package/dist/index.d.ts +14 -6
- package/dist/index.js +21 -14
- package/dist/provider/index.d.ts +11 -6
- package/dist/provider/index.js +3 -2
- package/dist/resource/index.d.ts +39 -0
- package/dist/resource/index.js +3 -0
- package/dist/resource/index.js.map +1 -0
- package/dist/resource-view/index.d.ts +468 -0
- package/dist/resource-view/index.js +542 -0
- package/dist/resource-view/index.js.map +1 -0
- package/dist/schema/index.d.ts +4 -4
- package/dist/schema/index.js +1 -0
- package/dist/status-BXRokZD9.d.ts +50 -0
- package/dist/testing/index.d.ts +3 -3
- package/dist/{types-B9DDfvWa.d.ts → types-CXhqXPN1.d.ts} +21 -4
- package/dist/{types-C7FJtFXV.d.ts → types-o8j7g6O6.d.ts} +38 -1
- package/dist/urls.d.ts +18 -0
- package/dist/urls.js +3 -0
- package/dist/urls.js.map +1 -0
- package/dist/viewer-scope-77MqxvmZ.d.ts +125 -0
- package/dist/{write-outcome-B2fE29yZ.d.ts → write-outcome-CFnpciUI.d.ts} +1 -1
- package/package.json +21 -1
- package/dist/chunk-5ORRAXIV.js +0 -30
- package/dist/chunk-5ORRAXIV.js.map +0 -1
- package/dist/chunk-KXVHDK3Q.js.map +0 -1
- package/dist/chunk-NZPJI7FC.js.map +0 -1
- package/dist/chunk-OSPLIKSH.js.map +0 -1
- package/dist/chunk-RCAP3Q4T.js.map +0 -1
- package/dist/chunk-TOU2CMDH.js.map +0 -1
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// src/resource/status.ts
|
|
2
|
+
var SAVE_STATE_LABEL = {
|
|
3
|
+
saved: "Changes saved",
|
|
4
|
+
saving: "Saving\u2026",
|
|
5
|
+
unsaved: "Unsaved changes",
|
|
6
|
+
failed: "Couldn't save; trying again",
|
|
7
|
+
stopped: "Couldn't save",
|
|
8
|
+
conflict: "Changed elsewhere; reload"
|
|
9
|
+
};
|
|
10
|
+
function readinessOf(findings, options = {}) {
|
|
11
|
+
const { emptyCode, pending } = options;
|
|
12
|
+
let errors = 0;
|
|
13
|
+
let warnings = 0;
|
|
14
|
+
for (const f of findings) {
|
|
15
|
+
if (emptyCode !== void 0 && f.code === emptyCode) return { state: "empty", count: 0 };
|
|
16
|
+
if (f.level === "error") errors++;
|
|
17
|
+
else if (f.level === "warning") warnings++;
|
|
18
|
+
}
|
|
19
|
+
if (errors) return { state: "problems", count: errors };
|
|
20
|
+
if (pending) return { state: "pending", count: 0 };
|
|
21
|
+
if (warnings) return { state: "warnings", count: warnings };
|
|
22
|
+
return { state: "ready", count: 0 };
|
|
23
|
+
}
|
|
24
|
+
function readinessChip(readiness, labels = {}) {
|
|
25
|
+
switch (readiness.state) {
|
|
26
|
+
case "ready":
|
|
27
|
+
return { label: labels.ready ?? "Ready to publish", tone: "success" };
|
|
28
|
+
case "empty":
|
|
29
|
+
return { label: labels.empty ?? "Nothing to publish yet", tone: "muted" };
|
|
30
|
+
case "pending":
|
|
31
|
+
return { label: labels.pending ?? "In progress", tone: "muted" };
|
|
32
|
+
case "problems":
|
|
33
|
+
return {
|
|
34
|
+
label: labels.problems?.(readiness.count) ?? `${readiness.count} ${readiness.count === 1 ? "problem" : "problems"} to fix`,
|
|
35
|
+
tone: "danger"
|
|
36
|
+
};
|
|
37
|
+
case "warnings":
|
|
38
|
+
return { label: labels.warnings?.(readiness.count) ?? `${readiness.count} to check`, tone: "warning" };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/resource/days.ts
|
|
43
|
+
var MONTH_DAY = new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
|
|
44
|
+
var MONTH_DAY_YEAR = new Intl.DateTimeFormat("en-US", {
|
|
45
|
+
month: "short",
|
|
46
|
+
day: "numeric",
|
|
47
|
+
year: "numeric",
|
|
48
|
+
timeZone: "UTC"
|
|
49
|
+
});
|
|
50
|
+
function dayLabel(day, today) {
|
|
51
|
+
const t = Date.parse(`${day}T00:00:00Z`);
|
|
52
|
+
if (Number.isNaN(t)) return day;
|
|
53
|
+
if (today) {
|
|
54
|
+
const diff = Math.round((Date.parse(`${today}T00:00:00Z`) - t) / 864e5);
|
|
55
|
+
if (diff === 0) return "Today";
|
|
56
|
+
if (diff === 1) return "Yesterday";
|
|
57
|
+
if (day.slice(0, 4) !== today.slice(0, 4)) return MONTH_DAY_YEAR.format(t);
|
|
58
|
+
}
|
|
59
|
+
return MONTH_DAY.format(t);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/resource/share.ts
|
|
63
|
+
var RELATIVE_BASE = "http://relative.invalid";
|
|
64
|
+
function prefilledUrl(url, values) {
|
|
65
|
+
let absolute = true;
|
|
66
|
+
let u;
|
|
67
|
+
try {
|
|
68
|
+
u = new URL(url);
|
|
69
|
+
} catch {
|
|
70
|
+
absolute = false;
|
|
71
|
+
u = new URL(url, RELATIVE_BASE);
|
|
72
|
+
}
|
|
73
|
+
for (const [k, v] of Object.entries(values)) if (v) u.searchParams.set(k, v);
|
|
74
|
+
if (absolute) return u.toString();
|
|
75
|
+
const path = url.startsWith("/") ? u.pathname : u.pathname.replace(/^\//, "");
|
|
76
|
+
return `${path}${u.search}${u.hash}`;
|
|
77
|
+
}
|
|
78
|
+
var attr = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
79
|
+
function embedSnippet(url, title) {
|
|
80
|
+
return `<iframe src="${attr(url)}" title="${attr(title)}" width="100%" height="720" style="border:0;max-width:100%" loading="lazy"></iframe>`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export { SAVE_STATE_LABEL, dayLabel, embedSnippet, prefilledUrl, readinessChip, readinessOf };
|
|
84
|
+
//# sourceMappingURL=chunk-PP3XFFQM.js.map
|
|
85
|
+
//# sourceMappingURL=chunk-PP3XFFQM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resource/status.ts","../src/resource/days.ts","../src/resource/share.ts"],"names":[],"mappings":";AAOO,IAAM,gBAAA,GAA8C;AAAA,EACzD,KAAA,EAAO,eAAA;AAAA,EACP,MAAA,EAAQ,cAAA;AAAA,EACR,OAAA,EAAS,iBAAA;AAAA,EACT,MAAA,EAAQ,6BAAA;AAAA,EACR,OAAA,EAAS,eAAA;AAAA,EACT,QAAA,EAAU;AACZ;AAgCO,SAAS,WAAA,CACd,QAAA,EACA,OAAA,GAA4B,EAAC,EAClB;AACX,E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AM,MAAM,CAAA,CAAE,OAAA,CAAQ,MAAM,MAAM,CAAA;AAGtF,SAAS,YAAA,CAAa,KAAa,KAAA,EAAuB;AAC/D,EAAA,OAAO,gBAAgB,IAAA,CAAK,GAAG,CAAC,CAAA,SAAA,EAAY,IAAA,CAAK,KAAK,CAAC,CAAA,oFAAA,CAAA;AACzD","file":"chunk-PP3XFFQM.js","sourcesContent":["// Words for a resource page's chips (save state, readiness). Pure: no React, safe on a\n// server. Not about any one kind of resource: forms, courses, lessons and worksheets use\n// the same page pattern.\n\n/** Where the host's draft saving stands. */\nexport type SaveState = \"saved\" | \"saving\" | \"unsaved\" | \"failed\" | \"stopped\" | \"conflict\";\n\nexport const SAVE_STATE_LABEL: Record<SaveState, string> = {\n saved: \"Changes saved\",\n saving: \"Saving…\",\n unsaved: \"Unsaved changes\",\n failed: \"Couldn't save; trying again\",\n stopped: \"Couldn't save\",\n conflict: \"Changed elsewhere; reload\",\n};\n\n/** A chip's colour: the tinted, AA-safe Genesis badge tones. */\nexport type ChipTone = \"success\" | \"warning\" | \"danger\" | \"info\" | \"muted\";\n\n/** Whether something can be published, from an editor's checks. */\nexport interface Readiness {\n state: \"ready\" | \"problems\" | \"warnings\" | \"empty\" | \"pending\";\n /** Problems or warnings to look at (0 when ready, empty or pending). */\n count: number;\n}\n\n/** One of an editor's findings, as readinessOf reads it. */\nexport interface ReadinessFinding {\n level: \"error\" | \"warning\" | \"info\";\n code?: string | undefined;\n}\n\nexport interface ReadinessOptions {\n /** Errors are held back while something new is being written: \"pending\", not \"problems\". */\n pending?: boolean | undefined;\n /**\n * The finding code that means \"nothing to publish yet\" (for example a form builder's\n * `no-questions`): it makes the result \"empty\", not broken. None by default.\n */\n emptyCode?: string | undefined;\n}\n\n/**\n * Readiness from an editor's findings (any list of `{ level, code? }`): errors block\n * publishing, warnings ask for a look. One pass over the findings.\n */\nexport function readinessOf(\n findings: readonly ReadinessFinding[],\n options: ReadinessOptions = {},\n): Readiness {\n const { emptyCode, pending } = options;\n let errors = 0;\n let warnings = 0;\n for (const f of findings) {\n if (emptyCode !== undefined && f.code === emptyCode) return { state: \"empty\", count: 0 };\n if (f.level === \"error\") errors++;\n else if (f.level === \"warning\") warnings++;\n }\n if (errors) return { state: \"problems\", count: errors };\n if (pending) return { state: \"pending\", count: 0 };\n if (warnings) return { state: \"warnings\", count: warnings };\n return { state: \"ready\", count: 0 };\n}\n\n/** The readiness chip's words, each optional; the defaults are resource-neutral. */\nexport interface ReadinessLabels {\n /** Default \"Ready to publish\". */\n ready?: string | undefined;\n /** When there is nothing yet. Default \"Nothing to publish yet\"; a form says \"Add a question\". */\n empty?: string | undefined;\n /** Default \"In progress\". */\n pending?: string | undefined;\n /** Default \"1 problem to fix\" / \"3 problems to fix\". */\n problems?: ((count: number) => string) | undefined;\n /** Default \"2 to check\". */\n warnings?: ((count: number) => string) | undefined;\n}\n\n/** The readiness chip's label and tone. */\nexport function readinessChip(\n readiness: Readiness,\n labels: ReadinessLabels = {},\n): { label: string; tone: ChipTone } {\n switch (readiness.state) {\n case \"ready\":\n return { label: labels.ready ?? \"Ready to publish\", tone: \"success\" };\n case \"empty\":\n return { label: labels.empty ?? \"Nothing to publish yet\", tone: \"muted\" };\n case \"pending\":\n return { label: labels.pending ?? \"In progress\", tone: \"muted\" };\n case \"problems\":\n return {\n label:\n labels.problems?.(readiness.count) ??\n `${readiness.count} ${readiness.count === 1 ? \"problem\" : \"problems\"} to fix`,\n tone: \"danger\",\n };\n case \"warnings\":\n return { label: labels.warnings?.(readiness.count) ?? `${readiness.count} to check`, tone: \"warning\" };\n }\n}\n","// A day (YYYY-MM-DD) in plain words. Pure.\n\nconst MONTH_DAY = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" });\nconst MONTH_DAY_YEAR = new Intl.DateTimeFormat(\"en-US\", {\n month: \"short\",\n day: \"numeric\",\n year: \"numeric\",\n timeZone: \"UTC\",\n});\n\n/** A day (YYYY-MM-DD) in words, given today on the same clock: \"Today\", \"Yesterday\", \"Oct 21\", \"Oct 21, 2025\". */\nexport function dayLabel(day: string, today?: string): string {\n const t = Date.parse(`${day}T00:00:00Z`);\n if (Number.isNaN(t)) return day;\n if (today) {\n const diff = Math.round((Date.parse(`${today}T00:00:00Z`) - t) / 86_400_000);\n if (diff === 0) return \"Today\";\n if (diff === 1) return \"Yesterday\";\n if (day.slice(0, 4) !== today.slice(0, 4)) return MONTH_DAY_YEAR.format(t);\n }\n return MONTH_DAY.format(t);\n}\n","// Sharing a published page (ShareDialog): prefilled links and the embed snippet. Pure.\n\n/** One search param a prefilled link may set, and the values staff pick from. */\nexport interface PrefillChoice {\n key: string;\n /** The picker's accessible name, e.g. \"Location\". */\n label: string;\n /** The picker's \"leave it out\" choice, e.g. \"Any location\". */\n anyLabel: string;\n options: readonly { value: string; label: string }[];\n}\n\n// Resolves a relative link without inventing an origin for it.\nconst RELATIVE_BASE = \"http://relative.invalid\";\n\n/**\n * `url` with `values` set as search params (empty values left out), keeping what it has.\n * An absolute link stays absolute; a relative one (`/f/a?x=1`) stays relative, so it never\n * throws while a page is still working out its origin.\n */\nexport function prefilledUrl(url: string, values: Record<string, string | undefined>): string {\n let absolute = true;\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n absolute = false;\n u = new URL(url, RELATIVE_BASE);\n }\n for (const [k, v] of Object.entries(values)) if (v) u.searchParams.set(k, v);\n if (absolute) return u.toString();\n const path = url.startsWith(\"/\") ? u.pathname : u.pathname.replace(/^\\//, \"\");\n return `${path}${u.search}${u.hash}`;\n}\n\nconst attr = (s: string) =>\n s.replace(/&/g, \"&\").replace(/\"/g, \""\").replace(/</g, \"<\").replace(/>/g, \">\");\n\n/** An `<iframe>` that shows the page on another website, full width. */\nexport function embedSnippet(url: string, title: string): string {\n return `<iframe src=\"${attr(url)}\" title=\"${attr(title)}\" width=\"100%\" height=\"720\" style=\"border:0;max-width:100%\" loading=\"lazy\"></iframe>`;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { useLiveInvalidation } from './chunk-UV3ROHQA.js';
|
|
2
|
+
import { resourceKeys } from './chunk-OYIUIW7C.js';
|
|
3
3
|
import { useDataProvider } from './chunk-GGSXSI6Z.js';
|
|
4
4
|
import { useQuery } from '@tanstack/react-query';
|
|
5
5
|
|
|
@@ -35,5 +35,5 @@ function useOne(resource, id, options = {}) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
export { useOne };
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
39
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-RF6YVWHX.js.map
|
|
39
|
+
//# sourceMappingURL=chunk-RF6YVWHX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,O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AA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-RF6YVWHX.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { useLiveInvalidation } from './chunk-UV3ROHQA.js';
|
|
2
|
+
import { resourceKeys } from './chunk-OYIUIW7C.js';
|
|
3
3
|
import { useDataProvider } from './chunk-GGSXSI6Z.js';
|
|
4
|
-
import { useState, useCallback, useMemo } from 'react';
|
|
5
|
-
import { useInfiniteQuery } from '@tanstack/react-query';
|
|
4
|
+
import { useState, useCallback, useMemo, useRef } from 'react';
|
|
5
|
+
import { useInfiniteQuery, keepPreviousData } from '@tanstack/react-query';
|
|
6
6
|
|
|
7
7
|
function filterKey(filters) {
|
|
8
8
|
return JSON.stringify(
|
|
@@ -20,7 +20,8 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
20
20
|
select,
|
|
21
21
|
searchFields,
|
|
22
22
|
enabled = true,
|
|
23
|
-
live
|
|
23
|
+
live,
|
|
24
|
+
keepPreviousData: keepPreviousData$1 = false
|
|
24
25
|
} = options;
|
|
25
26
|
const provider = useDataProvider();
|
|
26
27
|
const [sort, setSort] = useState(defaultSort);
|
|
@@ -45,6 +46,7 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
45
46
|
}
|
|
46
47
|
return p;
|
|
47
48
|
}, [perPage, sort, filters, select, search, searchFields]);
|
|
49
|
+
const cursorMode = useRef(false);
|
|
48
50
|
const query = useInfiniteQuery({
|
|
49
51
|
queryKey: resourceKeys(resource).infinite(params),
|
|
50
52
|
initialPageParam: { page: 1, cursor: null },
|
|
@@ -60,11 +62,20 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
60
62
|
return last.nextCursor ? { page: lastParam.page + 1, cursor: last.nextCursor } : void 0;
|
|
61
63
|
}
|
|
62
64
|
const loaded = pages.reduce((n, p) => n + p.data.length, 0);
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
+
const first2 = pages[0];
|
|
66
|
+
const exact = !!first2 && first2.total >= 0 && !first2.totalIsEstimate;
|
|
67
|
+
if (last.data.length < params.perPage || exact && loaded >= first2.total) return void 0;
|
|
65
68
|
return { page: lastParam.page + 1, cursor: null };
|
|
66
69
|
},
|
|
67
|
-
|
|
70
|
+
getPreviousPageParam: (first2, _pages, firstParam) => (
|
|
71
|
+
// Cursor mode only: offset pages aren't dropped from the front.
|
|
72
|
+
first2.prevCursor ? { page: firstParam.page - 1, cursor: first2.prevCursor } : void 0
|
|
73
|
+
),
|
|
74
|
+
// Only once the provider is known to page by cursor: TanStack drops pages whenever maxPages is
|
|
75
|
+
// set, and offset pages can't be loaded back, so they would be lost.
|
|
76
|
+
...options.maxPages !== void 0 && options.maxPages > 0 && cursorMode.current ? { maxPages: options.maxPages } : {},
|
|
77
|
+
enabled,
|
|
78
|
+
...keepPreviousData$1 ? { placeholderData: keepPreviousData } : {}
|
|
68
79
|
});
|
|
69
80
|
useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);
|
|
70
81
|
const rows = useMemo(() => {
|
|
@@ -83,19 +94,40 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
83
94
|
}
|
|
84
95
|
return out;
|
|
85
96
|
}, [query.data]);
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
const
|
|
97
|
+
const first = query.data?.pages[0];
|
|
98
|
+
if (first && first.nextCursor !== void 0) cursorMode.current = true;
|
|
99
|
+
const paramsKey = JSON.stringify(params);
|
|
100
|
+
const lastCount = useRef(null);
|
|
101
|
+
if (first && first.total >= 0 && !query.isPlaceholderData) {
|
|
102
|
+
lastCount.current = { key: paramsKey, total: first.total, estimate: !!first.totalIsEstimate };
|
|
103
|
+
}
|
|
104
|
+
const count = lastCount.current?.key === paramsKey ? lastCount.current : null;
|
|
105
|
+
const total = count?.total;
|
|
106
|
+
const {
|
|
107
|
+
fetchNextPage: fetchNext,
|
|
108
|
+
hasNextPage,
|
|
109
|
+
isFetchingNextPage,
|
|
110
|
+
fetchPreviousPage: fetchPrevious,
|
|
111
|
+
hasPreviousPage,
|
|
112
|
+
isFetchingPreviousPage
|
|
113
|
+
} = query;
|
|
89
114
|
const fetchNextPage = useCallback(() => {
|
|
90
115
|
if (!hasNextPage || isFetchingNextPage) return;
|
|
91
116
|
void fetchNext();
|
|
92
117
|
}, [fetchNext, hasNextPage, isFetchingNextPage]);
|
|
118
|
+
const fetchPreviousPage = useCallback(() => {
|
|
119
|
+
if (!hasPreviousPage || isFetchingPreviousPage) return;
|
|
120
|
+
void fetchPrevious();
|
|
121
|
+
}, [fetchPrevious, hasPreviousPage, isFetchingPreviousPage]);
|
|
93
122
|
return {
|
|
94
123
|
query,
|
|
95
124
|
rows,
|
|
96
125
|
total,
|
|
126
|
+
totalIsEstimate: !!count?.estimate,
|
|
97
127
|
fetchNextPage,
|
|
98
128
|
hasNextPage: !!hasNextPage,
|
|
129
|
+
fetchPreviousPage,
|
|
130
|
+
hasPreviousPage: !!hasPreviousPage,
|
|
99
131
|
isFetchingNextPage,
|
|
100
132
|
params,
|
|
101
133
|
setSort,
|
|
@@ -105,5 +137,5 @@ function useInfiniteResource(resource, options = {}) {
|
|
|
105
137
|
}
|
|
106
138
|
|
|
107
139
|
export { useInfiniteResource };
|
|
108
|
-
//# sourceMappingURL=chunk-
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
//# sourceMappingURL=chunk-UGGMJUFQ.js.map
|
|
141
|
+
//# sourceMappingURL=chunk-UGGMJUFQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-infinite-resource.ts"],"names":["keepPreviousData","first","keepPrevious"],"mappings":";;;;;;AAuFA,SAAS,UAAU,OAAA,EAA4C;AAC7D,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IAAA,CACT,OAAA,IAAW,EAAC,EAAG,GAAA;AAAA,MAAI,CAAC,MACnB,MAAA,CAAO,WAAA,CAAY,OAAO,OAAA,CAAQ,CAAC,EAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAM,EAAE,aAAA,CAAc,CAAC,CAAC,CAAC;AAAA;AAC7E,GACF;AACF;AAEO,SAAS,mBAAA,CACd,QAAA,EACA,OAAA,GAAsC,EAAC,EACT;AAC9B,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,cAAA;AAAA,IACA,OAAA,GAAU,EAAA;AAAA,IACV,aAAA,GAAgB,EAAA;AAAA,IAChB,MAAA;AAAA,IACA,YAAA;AAAA,IACA,OAAA,GAAU,IAAA;AAAA,IACV,IAAA;AAAA,sBACAA,kBAAA,GAAmB;AAAA,GACrB,GAAI,OAAA;AACJ,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,CAAC,IAAA,EAAM,OAAO,CAAA,GAAI,SAAgC,WAAW,CAAA;AACnE,EAAA,MAAM,CAAC,OAAA,EAAS,aAAa,IAAI,QAAA,CAAwB,cAAA,IAAkB,EAAE,CAAA;AAC7E,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,CAAA,GAAI,SAAS,aAAa,CAAA;AAGlD,EAAA,MAAM,UAAA,GAAa,UAAU,cAAc,CAAA;AAC3C,EAAA,MAAM,CAAC,SAAA,EAAW,YAAY,CAAA,GAAI,SAAS,UAAU,CAAA;AACrD,EAAA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;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-UGGMJUFQ.js","sourcesContent":["import { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n keepPreviousData as keepPrevious,\n useInfiniteQuery,\n type InfiniteData,\n type UseInfiniteQueryResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n FilterParam,\n ListParams,\n ListResult,\n SortParam,\n} from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// useInfiniteResource — a list that grows with \"Load more\", by cursor.\n//\n// Asks for the first page with `cursor: null`. A provider that serves cursor\n// paging answers with `nextCursor` and is paged by keyset from then on; one\n// that doesn't answers without it and is paged by `page` (offset) until\n// `total` rows are loaded. Pages live under `[resource, \"infinite\", params]`,\n// so writes on the resource (which invalidate `[resource]`) refetch them,\n// and pending optimistic and undoable writes are patched into every page.\n// ---------------------------------------------------------------------------\n\nexport interface UseInfiniteResourceOptions {\n defaultSort?: SortParam;\n /** Re-synced when its value changes, like `useResource`'s. */\n defaultFilters?: FilterParam[];\n /** Rows per page. Default 25. */\n perPage?: number;\n /** The search to start with. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax. Must include the sort and key columns. */\n select?: string;\n /** Fields to search across when `setSearch` is called. */\n searchFields?: string[];\n /** Disable fetching. */\n enabled?: boolean;\n /** Refetch the loaded pages when the provider reports a change. See `UseResourceOptions.live`. */\n live?: boolean | LiveOptions;\n /**\n * Keep at most this many pages loaded (TanStack Query's `maxPages`): scrolling far drops pages\n * from the front, and scrolling back loads them again, so a long feed and a live refetch stay\n * cheap. Needs a provider that pages by cursor both ways (`prevCursor`); offset paging ignores it.\n */\n maxPages?: number;\n /**\n * Keep the current rows on screen while a new search, sort or filter loads, instead of a\n * loading state for each change. Default false.\n */\n keepPreviousData?: boolean;\n}\n\n/** Where one page starts: its offset page, and its cursor (`null` for the first). */\nexport interface InfinitePageParam {\n page: number;\n cursor: string | null;\n}\n\nexport interface UseInfiniteResourceReturn<T> {\n /** The TanStack infinite query. */\n query: UseInfiniteQueryResult<InfiniteData<ListResult<T>, InfinitePageParam>>;\n /** Every loaded row, in order. */\n rows: T[];\n /** Rows matching the filters and search, from the first page's count. */\n total: number | undefined;\n /** True when `total` is the database's estimate, so a screen says \"about\". */\n totalIsEstimate: boolean;\n /** Loads the next page. Does nothing while one is loading or none is left. */\n fetchNextPage: () => void;\n hasNextPage: boolean;\n /** Load the page before the first loaded one (after `maxPages` dropped it). No-op when there is none. */\n fetchPreviousPage: () => void;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n /** The params every page is asked with (without its page and cursor). */\n params: Omit<ListParams, \"pagination\"> & { perPage: number };\n setSort: (sort: SortParam | undefined) => void;\n setFilters: (filters: FilterParam[]) => void;\n setSearch: (query: string) => void;\n}\n\nfunction filterKey(filters: FilterParam[] | undefined): string {\n return JSON.stringify(\n (filters ?? []).map((f) =>\n Object.fromEntries(Object.entries(f).sort(([a], [b]) => a.localeCompare(b))),\n ),\n );\n}\n\nexport function useInfiniteResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseInfiniteResourceOptions = {},\n): UseInfiniteResourceReturn<T> {\n const {\n defaultSort,\n defaultFilters,\n perPage = 25,\n defaultSearch = \"\",\n select,\n searchFields,\n enabled = true,\n live,\n keepPreviousData = false,\n } = options;\n const provider = useDataProvider();\n\n const [sort, setSort] = useState<SortParam | undefined>(defaultSort);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [search, setSearch] = useState(defaultSearch);\n\n // Follow `defaultFilters` by value, during render (see useResource).\n const defaultKey = filterKey(defaultFilters);\n const [syncedKey, setSyncedKey] = useState(defaultKey);\n if (defaultKey !== syncedKey) {\n setSyncedKey(defaultKey);\n setFiltersRaw(defaultFilters ?? []);\n }\n\n const setFilters = useCallback((next: FilterParam[]) => setFiltersRaw(next), []);\n\n const params = useMemo(() => {\n const p: Omit<ListParams, \"pagination\"> & { perPage: number } = {\n perPage,\n sort,\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (search && searchFields && searchFields.length > 0) {\n p.search = { query: search, fields: searchFields };\n }\n return p;\n }, [perPage, sort, filters, select, search, searchFields]);\n\n // Whether the provider pages by cursor (it sends `nextCursor`), learnt from the first page.\n const cursorMode = useRef(false);\n const query = useInfiniteQuery<\n ListResult<T>,\n Error,\n InfiniteData<ListResult<T>, InfinitePageParam>,\n readonly unknown[],\n InfinitePageParam\n >({\n queryKey: resourceKeys(resource).infinite(params),\n initialPageParam: { page: 1, cursor: null },\n queryFn: ({ pageParam }) => {\n const { perPage: size, ...rest } = params;\n return provider.getList<T>(resource, {\n ...rest,\n pagination: { page: pageParam.page, perPage: size, cursor: pageParam.cursor },\n });\n },\n getNextPageParam: (last, pages, lastParam) => {\n if (last.nextCursor !== undefined) {\n // Cursor mode: the provider says whether there is more.\n return last.nextCursor ? { page: lastParam.page + 1, cursor: last.nextCursor } : undefined;\n }\n // Offset mode: more while the last page was full and, when the total is\n // an exact count, fewer than `total` rows are loaded. An uncounted\n // (`count: \"none\"`, total -1) or estimated total (RLS makes the planner\n // guess low) never stops the list early: only a short page does.\n const loaded = pages.reduce((n, p) => n + p.data.length, 0);\n const first = pages[0];\n const exact = !!first && first.total >= 0 && !first.totalIsEstimate;\n if (last.data.length < params.perPage || (exact && loaded >= first.total)) return undefined;\n return { page: lastParam.page + 1, cursor: null };\n },\n getPreviousPageParam: (first, _pages, firstParam) =>\n // Cursor mode only: offset pages aren't dropped from the front.\n first.prevCursor ? { page: firstParam.page - 1, cursor: first.prevCursor } : undefined,\n // Only once the provider is known to page by cursor: TanStack drops pages whenever maxPages is\n // set, and offset pages can't be loaded back, so they would be lost.\n ...(options.maxPages !== undefined && options.maxPages > 0 && cursorMode.current ? { maxPages: options.maxPages } : {}),\n enabled,\n ...(keepPreviousData ? { placeholderData: keepPrevious } : {}),\n });\n\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // A row can move between pages while the user scrolls (its sort value\n // changed, or rows before it were added): show it once, where it first appears.\n const rows = useMemo(() => {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const page of query.data?.pages ?? []) {\n for (const row of page.data) {\n const id = row?.id;\n if (id != null) {\n const key = String(id);\n if (seen.has(key)) continue;\n seen.add(key);\n }\n out.push(row);\n }\n }\n return out;\n }, [query.data]);\n const first = query.data?.pages[0];\n if (first && first.nextCursor !== undefined) cursorMode.current = true;\n // The count comes with the list's first page only. Once maxPages drops that page (or a refetch\n // starts from a back cursor) the loaded first page has no count, so keep the last one seen for\n // these params.\n const paramsKey = JSON.stringify(params);\n const lastCount = useRef<{ key: string; total: number; estimate: boolean } | null>(null);\n // Not from placeholder pages (keepPreviousData): they're the old params' rows and count.\n if (first && first.total >= 0 && !query.isPlaceholderData) {\n lastCount.current = { key: paramsKey, total: first.total, estimate: !!first.totalIsEstimate };\n }\n const count = lastCount.current?.key === paramsKey ? lastCount.current : null;\n const total = count?.total;\n\n const {\n fetchNextPage: fetchNext,\n hasNextPage,\n isFetchingNextPage,\n fetchPreviousPage: fetchPrevious,\n hasPreviousPage,\n isFetchingPreviousPage,\n } = query;\n const fetchNextPage = useCallback(() => {\n if (!hasNextPage || isFetchingNextPage) return;\n void fetchNext();\n }, [fetchNext, hasNextPage, isFetchingNextPage]);\n const fetchPreviousPage = useCallback(() => {\n if (!hasPreviousPage || isFetchingPreviousPage) return;\n void fetchPrevious();\n }, [fetchPrevious, hasPreviousPage, isFetchingPreviousPage]);\n\n return {\n query,\n rows,\n total,\n totalIsEstimate: !!count?.estimate,\n fetchNextPage,\n hasNextPage: !!hasNextPage,\n fetchPreviousPage,\n hasPreviousPage: !!hasPreviousPage,\n isFetchingNextPage,\n params,\n setSort,\n setFilters,\n setSearch,\n };\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { patchCachedRow, listCouldChange } from './chunk-AUVKRXRC.js';
|
|
1
2
|
import { useDataProvider } from './chunk-GGSXSI6Z.js';
|
|
2
3
|
import { useRef, useEffect } from 'react';
|
|
3
4
|
import { useQueryClient } from '@tanstack/react-query';
|
|
4
5
|
|
|
5
6
|
var DEFAULT_LIVE_DEBOUNCE_MS = 250;
|
|
7
|
+
var DEFAULT_LIVE_RESYNC_MS = 6e4;
|
|
6
8
|
var warnedNoSubscribe = /* @__PURE__ */ new WeakSet();
|
|
7
9
|
function useLiveInvalidation(resource, live, enabled, params, queryKey, accept) {
|
|
8
10
|
const provider = useDataProvider();
|
|
@@ -12,6 +14,10 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
12
14
|
0,
|
|
13
15
|
(typeof live === "object" ? live.debounceMs : void 0) ?? DEFAULT_LIVE_DEBOUNCE_MS
|
|
14
16
|
);
|
|
17
|
+
const resyncMs = Math.max(
|
|
18
|
+
0,
|
|
19
|
+
(typeof live === "object" ? live.resyncMs : void 0) ?? DEFAULT_LIVE_RESYNC_MS
|
|
20
|
+
);
|
|
15
21
|
const paramsKey = JSON.stringify(params);
|
|
16
22
|
const keyKey = JSON.stringify(queryKey);
|
|
17
23
|
const latest = useRef({ queryKey, accept, params });
|
|
@@ -29,15 +35,19 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
29
35
|
}
|
|
30
36
|
let timer;
|
|
31
37
|
let burstStart = 0;
|
|
38
|
+
let burst = [];
|
|
32
39
|
let active = true;
|
|
33
40
|
const maxWaitMs = debounceMs * 4;
|
|
34
41
|
const fire = () => {
|
|
35
42
|
timer = void 0;
|
|
36
43
|
if (!active) return;
|
|
37
44
|
const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
|
|
45
|
+
const rows = burst;
|
|
46
|
+
burst = [];
|
|
38
47
|
void queryClient.invalidateQueries({
|
|
39
48
|
queryKey: [...latest.current.queryKey],
|
|
40
|
-
refetchType: hidden ? "none" : "active"
|
|
49
|
+
refetchType: hidden ? "none" : "active",
|
|
50
|
+
...rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}
|
|
41
51
|
});
|
|
42
52
|
};
|
|
43
53
|
let unsubscribe;
|
|
@@ -46,6 +56,12 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
46
56
|
if (!active) return;
|
|
47
57
|
const test = latest.current.accept;
|
|
48
58
|
if (test && event.type !== "changed" && !test(event)) return;
|
|
59
|
+
if (event.type === "updated" && event.record) {
|
|
60
|
+
patchCachedRow(queryClient, resource, event.record);
|
|
61
|
+
burst?.push(event.record);
|
|
62
|
+
} else {
|
|
63
|
+
burst = null;
|
|
64
|
+
}
|
|
49
65
|
const now = Date.now();
|
|
50
66
|
if (timer === void 0) burstStart = now;
|
|
51
67
|
else clearTimeout(timer);
|
|
@@ -54,8 +70,14 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
54
70
|
} catch (error) {
|
|
55
71
|
console.error(`[genesis] subscribing to "${resource}" failed:`, error);
|
|
56
72
|
}
|
|
73
|
+
const resync = resyncMs > 0 ? setInterval(() => {
|
|
74
|
+
if (!active) return;
|
|
75
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
|
|
76
|
+
void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: "active" });
|
|
77
|
+
}, resyncMs) : void 0;
|
|
57
78
|
return () => {
|
|
58
79
|
active = false;
|
|
80
|
+
if (resync !== void 0) clearInterval(resync);
|
|
59
81
|
if (timer !== void 0) clearTimeout(timer);
|
|
60
82
|
try {
|
|
61
83
|
unsubscribe?.();
|
|
@@ -63,9 +85,9 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
63
85
|
console.error(`[genesis] unsubscribing from "${resource}" failed:`, error);
|
|
64
86
|
}
|
|
65
87
|
};
|
|
66
|
-
}, [on, provider, queryClient, resource, debounceMs, paramsKey, keyKey]);
|
|
88
|
+
}, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);
|
|
67
89
|
}
|
|
68
90
|
|
|
69
|
-
export { DEFAULT_LIVE_DEBOUNCE_MS, useLiveInvalidation };
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
71
|
-
//# sourceMappingURL=chunk-
|
|
91
|
+
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation };
|
|
92
|
+
//# sourceMappingURL=chunk-UV3ROHQA.js.map
|
|
93
|
+
//# sourceMappingURL=chunk-UV3ROHQA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-live.ts"],"names":[],"mappings":";;;;;AA0BO,IAAM,wBAAA,GAA2B;AAOjC,IAAM,sBAAA,GAAyB;AAkBtC,IAAM,iBAAA,uBAAwB,OAAA,EAAgB;AAUvC,SAAS,oBACd,QAAA,EACA,IAAA,EACA,OAAA,EACA,MAAA,EACA,UACA,MAAA,EACM;AACN,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AACnC,EAAA,MAAM,EAAA,GAAK,CAAC,CAAC,IAAA,IAAQ,OAAA;AACrB,EAAA,MAAM,aAAa,IAAA,CAAK,GAAA;AAAA,IACtB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAa,MAAA,KAAc;AAAA,GAC9D;AACA,EAAA,MAAM,WAAW,IAAA,CAAK,GAAA;AAAA,IACpB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,WAAW,MAAA,KAAc;AAAA,GAC5D;AACA,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AACvC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAItC,EAAA,MAAM,SAAS,MAAA,CAAO,EAAE,QAAA,EAAU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WAAA,IAAe,QAAA,CAAS,oBAAoB,QAAA,EAAU;AAC9E,MAAA,KAAK,WAAA,CAAY,iBAAA,CAAkB,EAAE,QAAA,EAAU,CAAC,GAAG,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAG,WAAA,EAAa,QAAA,EAAU,CAAA;AAAA,IACtG,CAAA,EAAG,QAAQ,CAAA,GACX,MAAA;AACN,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,aAAA,CAAc,MAAM,CAAA;AAC9C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAC3C,MAAA,IAAI;AACF,QAAA,WAAA,IAAc;AAAA,MAChB,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,MAC3E;AAAA,IACF,CAAA;AAAA,EAEF,CAAA,EAAG,CAAC,EAAA,EAAI,QAAA,EAAU,WAAA,EAAa,UAAU,UAAA,EAAY,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AACnF","file":"chunk-UV3ROHQA.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Live reads — refetch a resource's cached reads when the provider reports a\n// change (`DataProvider.subscribe`).\n//\n// Events are invalidation hints. When an update carries the row (the provider\n// sends one only for a resource read from its own table, under realtime's RLS),\n// the fields cached rows already have are patched at once; the refetch that\n// follows still goes through the provider's normal read, so what a user ends\n// up seeing is what that read (and its RLS) returns. Lists the change can't\n// have touched (its row matches none of their filters and isn't in them) are\n// left alone.\n//\n// Pending optimistic and undoable writes are safe: their patches are\n// re-applied to whatever a refetch brings (see mutation-mode.ts), so a row\n// deleted with undo stays hidden and an edit stays shown until the write\n// settles. The provider drops the echo of this client's own writes, which\n// already refresh through the write path.\n// ---------------------------------------------------------------------------\n\nimport { useEffect, useRef } from \"react\";\nimport { useQueryClient, type QueryKey } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ResourceChangeEvent, SubscribeParams } from \"../provider/types\";\nimport { listCouldChange, patchCachedRow } from \"./live-cache\";\n\n/** How long a burst of change events is gathered into one refetch. */\nexport const DEFAULT_LIVE_DEBOUNCE_MS = 250;\n\n/**\n * How often a live read refetches anyway while the page is visible. Realtime checks each change\n * against the row's new state, so a row the viewer stops being allowed to see (binned, made a\n * draft, moved to another practice) sends them nothing and would stay on screen.\n */\nexport const DEFAULT_LIVE_RESYNC_MS = 60_000;\n\n/** `live` as an object, to tune it. `live: true` takes the defaults. */\nexport interface LiveOptions {\n /**\n * Events arriving within this many milliseconds of each other cause one\n * refetch, not one each. Default {@link DEFAULT_LIVE_DEBOUNCE_MS}. A\n * steady stream still refetches at least every `4 × debounceMs`.\n */\n debounceMs?: number;\n /**\n * Refetch at least this often while the page is visible, for the changes realtime can't\n * deliver (a row the viewer may no longer read). Default {@link DEFAULT_LIVE_RESYNC_MS}; 0 turns\n * it off.\n */\n resyncMs?: number;\n}\n\nconst warnedNoSubscribe = new WeakSet<object>();\n\n/**\n * Subscribes while mounted and `enabled`, and invalidates `queryKey` (a\n * prefix) once per burst of events that `accept` lets through. While the\n * page is hidden the queries are only marked stale; they refetch when it is\n * shown again (TanStack Query's `refetchOnWindowFocus`) or next used.\n *\n * @internal Used by `useResource` and `useOne`'s `live` option.\n */\nexport function useLiveInvalidation(\n resource: string,\n live: boolean | LiveOptions | undefined,\n enabled: boolean,\n params: SubscribeParams,\n queryKey: QueryKey,\n accept?: (event: ResourceChangeEvent) => boolean,\n): void {\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n const on = !!live && enabled;\n const debounceMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.debounceMs : undefined) ?? DEFAULT_LIVE_DEBOUNCE_MS,\n );\n const resyncMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.resyncMs : undefined) ?? DEFAULT_LIVE_RESYNC_MS,\n );\n const paramsKey = JSON.stringify(params);\n const keyKey = JSON.stringify(queryKey);\n\n // The latest values, read when an event arrives, so a new array or\n // callback each render doesn't resubscribe.\n const latest = useRef({ queryKey, accept, params });\n latest.current = { queryKey, accept, params };\n\n useEffect(() => {\n if (!on) return;\n if (typeof provider.subscribe !== \"function\") {\n if (process.env.NODE_ENV !== \"production\" && !warnedNoSubscribe.has(provider)) {\n warnedNoSubscribe.add(provider);\n console.warn(\n `[genesis] \"${resource}\" asked for live updates, but the data provider has no subscribe(); the list will only refresh on its own reads.`,\n );\n }\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n let burstStart = 0;\n // The rows of this burst's updates; null once an event without one (a delete, an insert,\n // `changed`) means every read must refetch.\n let burst: Record<string, unknown>[] | null = [];\n let active = true;\n // A busy table must not postpone the refetch forever.\n const maxWaitMs = debounceMs * 4;\n const fire = () => {\n timer = undefined;\n if (!active) return;\n const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n const rows = burst;\n burst = [];\n void queryClient.invalidateQueries({\n queryKey: [...latest.current.queryKey],\n refetchType: hidden ? \"none\" : \"active\",\n ...(rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}),\n });\n };\n let unsubscribe: (() => void) | undefined;\n try {\n unsubscribe = provider.subscribe(resource, latest.current.params, (event) => {\n if (!active) return;\n const test = latest.current.accept;\n if (test && event.type !== \"changed\" && !test(event)) return;\n if (event.type === \"updated\" && event.record) {\n patchCachedRow(queryClient, resource, event.record);\n burst?.push(event.record);\n } else {\n burst = null;\n }\n // Coalesce: one refetch per burst, after it goes quiet (or has\n // lasted `maxWaitMs`).\n const now = Date.now();\n if (timer === undefined) burstStart = now;\n else clearTimeout(timer);\n timer = setTimeout(fire, Math.min(debounceMs, Math.max(0, burstStart + maxWaitMs - now)));\n });\n } catch (error) {\n console.error(`[genesis] subscribing to \"${resource}\" failed:`, error);\n }\n // The safety net for changes realtime can't deliver; skipped while the page is hidden (a\n // hidden page refetches when it's shown again).\n const resync =\n resyncMs > 0\n ? setInterval(() => {\n if (!active) return;\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: \"active\" });\n }, resyncMs)\n : undefined;\n return () => {\n active = false;\n if (resync !== undefined) clearInterval(resync);\n if (timer !== undefined) clearTimeout(timer);\n try {\n unsubscribe?.();\n } catch (error) {\n console.error(`[genesis] unsubscribing from \"${resource}\" failed:`, error);\n }\n };\n // `paramsKey` / `keyKey` stand for `params` / `queryKey` by value.\n }, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);\n}\n"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// src/urls.ts
|
|
2
|
+
var SAFE_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
|
|
3
|
+
function isSafeUrl(url) {
|
|
4
|
+
if (typeof url !== "string") return false;
|
|
5
|
+
const value = url.trim();
|
|
6
|
+
if (value === "" || value.length > 2048) return false;
|
|
7
|
+
if (/[\u0000- \u007f-\u009f]/.test(value)) return false;
|
|
8
|
+
if (value.startsWith("#")) return true;
|
|
9
|
+
if (value.startsWith("/")) return !value.startsWith("//") && !value.startsWith("/\\");
|
|
10
|
+
let parsed;
|
|
11
|
+
try {
|
|
12
|
+
parsed = new URL(value);
|
|
13
|
+
} catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
return SAFE_PROTOCOLS.has(parsed.protocol);
|
|
17
|
+
}
|
|
18
|
+
function normalizeLinkUrl(input) {
|
|
19
|
+
const value = input.trim();
|
|
20
|
+
if (value === "") return null;
|
|
21
|
+
if (isSafeUrl(value)) return value;
|
|
22
|
+
if (/^[^\s@/:]+@[^\s@/]+\.[^\s@/]+$/.test(value)) {
|
|
23
|
+
const mail = `mailto:${value}`;
|
|
24
|
+
return isSafeUrl(mail) ? mail : null;
|
|
25
|
+
}
|
|
26
|
+
if (!/^[a-z][a-z0-9+.-]*:/i.test(value) && /^[^\s/]+\.[^\s/]+/.test(value)) {
|
|
27
|
+
const withScheme = `https://${value}`;
|
|
28
|
+
return isSafeUrl(withScheme) ? withScheme : null;
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export { isSafeUrl, normalizeLinkUrl };
|
|
34
|
+
//# sourceMappingURL=chunk-YDDPFSQ6.js.map
|
|
35
|
+
//# sourceMappingURL=chunk-YDDPFSQ6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/urls.ts"],"names":[],"mappings":";AAGA,IAAM,cAAA,uBAAqB,GAAA,CAAI,CAAC,SAAS,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AAW9D,SAAS,UAAU,GAAA,EAA6B;AACrD,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,KAAA;AACpC,EAAA,MAAM,KAAA,GAAQ,IAAI,IAAA,EAAK;AACvB,EAAA,IAAI,KAAA,KAAU,EAAA,IAAM,KAAA,CAAM,MAAA,GAAS,MAAM,OAAO,KAAA;AAEhD,EAAA,IAAI,yBAAA,CAA0B,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AAClD,EAAA,IAAI,KAAA,CAAM,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AAClC,EAAA,IAAI,KAAA,CAAM,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,CAAC,KAAA,CAAM,UAAA,CAAW,IAAI,CAAA,IAAK,CAAC,KAAA,CAAM,WAAW,KAAK,CAAA;AACpF,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAI,IAAI,KAAK,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,cAAA,CAAe,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA;AAC3C;AAOO,SAAS,iBAAiB,KAAA,EAA8B;AAC7D,EAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,EAAK;AACzB,EAAA,IAAI,KAAA,KAAU,IAAI,OAAO,IAAA;AACzB,EAAA,IAAI,SAAA,CAAU,KAAK,CAAA,EAAG,OAAO,KAAA;AAC7B,EAAA,IAAI,gCAAA,CAAiC,IAAA,CAAK,KAAK,CAAA,EAAG;AAChD,IAAA,MAAM,IAAA,GAAO,UAAU,KAAK,CAAA,CAAA;AAC5B,IAAA,OAAO,SAAA,CAAU,IAAI,CAAA,GAAI,IAAA,GAAO,IAAA;AAAA,EAClC;AAEA,EAAA,IAAI,CAAC,uBAAuB,IAAA,CAAK,KAAK,KAAK,mBAAA,CAAoB,IAAA,CAAK,KAAK,CAAA,EAAG;AAC1E,IAAA,MAAM,UAAA,GAAa,WAAW,KAAK,CAAA,CAAA;AACnC,IAAA,OAAO,SAAA,CAAU,UAAU,CAAA,GAAI,UAAA,GAAa,IAAA;AAAA,EAC9C;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-YDDPFSQ6.js","sourcesContent":["// Links a person or a row supplies, checked before they reach an `href` or `src`. Pure: web,\n// native and the extension use the same check (docs/RESOURCE-VIEW.md, \"URLs are checked\").\n\nconst SAFE_PROTOCOLS = new Set([\"http:\", \"https:\", \"mailto:\", \"tel:\"]);\n\n/**\n * True when `url` is safe to put in an `href`: an absolute http(s), mailto or\n * tel URL, a root-relative path (`/lessons/1`) or a fragment (`#notes`).\n *\n * Rejects `javascript:`, `data:`, `vbscript:` and every other scheme, as well\n * as protocol-relative `//host` URLs and anything containing whitespace or\n * control characters (browsers strip those, which is how `java\\tscript:`\n * slips past naive checks).\n */\nexport function isSafeUrl(url: unknown): url is string {\n if (typeof url !== \"string\") return false;\n const value = url.trim();\n if (value === \"\" || value.length > 2048) return false;\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000- \\u007f-\\u009f]/.test(value)) return false;\n if (value.startsWith(\"#\")) return true;\n if (value.startsWith(\"/\")) return !value.startsWith(\"//\") && !value.startsWith(\"/\\\\\");\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n return SAFE_PROTOCOLS.has(parsed.protocol);\n}\n\n/**\n * Turn what a person typed into the link field into a safe href, or `null`.\n * `example.com/page` becomes `https://example.com/page`; an email address\n * becomes a `mailto:` link.\n */\nexport function normalizeLinkUrl(input: string): string | null {\n const value = input.trim();\n if (value === \"\") return null;\n if (isSafeUrl(value)) return value;\n if (/^[^\\s@/:]+@[^\\s@/]+\\.[^\\s@/]+$/.test(value)) {\n const mail = `mailto:${value}`;\n return isSafeUrl(mail) ? mail : null;\n }\n // No scheme but looks like a host: assume https.\n if (!/^[a-z][a-z0-9+.-]*:/i.test(value) && /^[^\\s/]+\\.[^\\s/]+/.test(value)) {\n const withScheme = `https://${value}`;\n return isSafeUrl(withScheme) ? withScheme : null;\n }\n return null;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { useOne } from './chunk-RF6YVWHX.js';
|
|
1
2
|
import { useUnsavedChangesGuard } from './chunk-XQO4OH2N.js';
|
|
2
|
-
import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-
|
|
3
|
+
import { sameValue, cachedRecord, executeWrite, invalidateResource } from './chunk-3LZAZ5KB.js';
|
|
3
4
|
import { relatedKeys } from './chunk-7NUL32W7.js';
|
|
4
|
-
import { useOne } from './chunk-BGTXN2E6.js';
|
|
5
5
|
import { useDataProvider, useStorage } from './chunk-GGSXSI6Z.js';
|
|
6
6
|
import { titleCase } from './chunk-RYEXWQFD.js';
|
|
7
7
|
import { isDataWriteError } from './chunk-LG6TUBVM.js';
|
|
@@ -193,7 +193,8 @@ function buildArrayItemDefaults(arrayFields) {
|
|
|
193
193
|
function buildDefaults(fields, data, action, prefillFromUrl) {
|
|
194
194
|
const defaults = {};
|
|
195
195
|
for (const field of fields) {
|
|
196
|
-
|
|
196
|
+
const blankOnCreate = action === "create" && data?.[field.key] === "" && field.defaultValue !== void 0;
|
|
197
|
+
if (data && field.key in data && !blankOnCreate) {
|
|
197
198
|
defaults[field.key] = data[field.key];
|
|
198
199
|
} else if (field.defaultValue !== void 0) {
|
|
199
200
|
defaults[field.key] = field.defaultValue;
|
|
@@ -249,7 +250,8 @@ function useResourceForm(options) {
|
|
|
249
250
|
mutationMode = "pessimistic",
|
|
250
251
|
undoDelayMs,
|
|
251
252
|
onUndoable,
|
|
252
|
-
visible = true
|
|
253
|
+
visible = true,
|
|
254
|
+
updates = "loaded"
|
|
253
255
|
} = options;
|
|
254
256
|
const autosaveEnabled = !!autosave;
|
|
255
257
|
const debounceMs = typeof autosave === "object" ? autosave.debounceMs ?? 1e3 : 1e3;
|
|
@@ -410,8 +412,16 @@ function useResourceForm(options) {
|
|
|
410
412
|
[form, showError, onError, action, resource]
|
|
411
413
|
);
|
|
412
414
|
const handleSubmit = useCallback(
|
|
413
|
-
async (
|
|
415
|
+
async (submitted) => {
|
|
414
416
|
const shown = structuredCloneSafe(form.getValues());
|
|
417
|
+
const opened = formSource;
|
|
418
|
+
const formData = action === "edit" && updates === "loaded" && opened ? Object.fromEntries(
|
|
419
|
+
Object.entries(submitted).filter(
|
|
420
|
+
// Changed: what an input shows differs from where it started, or, for a value saved
|
|
421
|
+
// without an input (a direct handleSave), the value itself does.
|
|
422
|
+
([k, v]) => k in opened || !sameValue(k in shown ? shown[k] : v, defaultValues[k])
|
|
423
|
+
)
|
|
424
|
+
) : submitted;
|
|
415
425
|
try {
|
|
416
426
|
let recordId;
|
|
417
427
|
if (action === "edit") {
|
|
@@ -473,7 +483,7 @@ function useResourceForm(options) {
|
|
|
473
483
|
reportError(err instanceof Error ? err : new Error(String(err)));
|
|
474
484
|
}
|
|
475
485
|
},
|
|
476
|
-
[form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved]
|
|
486
|
+
[form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues]
|
|
477
487
|
);
|
|
478
488
|
const onSubmit = useCallback(
|
|
479
489
|
(e) => form.handleSubmit(handleSubmit)(e),
|
|
@@ -493,5 +503,5 @@ function useResourceForm(options) {
|
|
|
493
503
|
}
|
|
494
504
|
|
|
495
505
|
export { buildArrayItemDefaults, useResourceForm };
|
|
496
|
-
//# sourceMappingURL=chunk-
|
|
497
|
-
//# sourceMappingURL=chunk-
|
|
506
|
+
//# sourceMappingURL=chunk-YFTGLQDQ.js.map
|
|
507
|
+
//# sourceMappingURL=chunk-YFTGLQDQ.js.map
|