strata-react 0.1.4 → 0.1.6
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 +16 -6
- package/dist/components/theme.d.ts +51 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +24 -141
- package/dist/index.js.map +1 -1
- package/dist/lib/format.d.ts +30 -10
- package/dist/query-CmdlXVW_.js +345 -0
- package/dist/query-CmdlXVW_.js.map +1 -0
- package/dist/testing/index.d.ts +10 -3
- package/dist/testing/intersection-observer.d.ts +34 -0
- package/dist/testing/layout.d.ts +13 -0
- package/dist/testing.js +175 -9
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
- package/dist/query-Bi7rfvwp.js +0 -80
- package/dist/query-Bi7rfvwp.js.map +0 -1
package/dist/testing.js
CHANGED
|
@@ -1,9 +1,170 @@
|
|
|
1
|
-
import { n as createQueryClient, t as StrataQueryProvider } from "./query-
|
|
1
|
+
import { c as ThemeProvider, n as createQueryClient, t as StrataQueryProvider } from "./query-CmdlXVW_.js";
|
|
2
2
|
import "react";
|
|
3
3
|
import { jsx } from "react/jsx-runtime";
|
|
4
4
|
import { MemoryRouter } from "react-router";
|
|
5
|
-
import { render } from "@testing-library/react";
|
|
5
|
+
import { act, render } from "@testing-library/react";
|
|
6
|
+
// src/testing/layout.ts
|
|
7
|
+
/** A DOMRect-shaped object, for stand-ins that report geometry. */
|
|
8
|
+
function box(x, y, width, height) {
|
|
9
|
+
return {
|
|
10
|
+
x,
|
|
11
|
+
y,
|
|
12
|
+
width,
|
|
13
|
+
height,
|
|
14
|
+
top: y,
|
|
15
|
+
left: x,
|
|
16
|
+
right: x + width,
|
|
17
|
+
bottom: y + height,
|
|
18
|
+
toJSON() {
|
|
19
|
+
return this;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a
|
|
25
|
+
* ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.
|
|
26
|
+
* Call once in a Vitest setup file; returns a function that puts the originals back.
|
|
27
|
+
*/
|
|
28
|
+
function installLayoutShims({ width = 640, height = 280 } = {}) {
|
|
29
|
+
const restore = [];
|
|
30
|
+
const replace = (target, prop, descriptor) => {
|
|
31
|
+
const before = Object.getOwnPropertyDescriptor(target, prop);
|
|
32
|
+
Object.defineProperty(target, prop, {
|
|
33
|
+
configurable: true,
|
|
34
|
+
...descriptor
|
|
35
|
+
});
|
|
36
|
+
restore.push(() => {
|
|
37
|
+
if (before) Object.defineProperty(target, prop, before);
|
|
38
|
+
else delete target[prop];
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
class FixedResizeObserver {
|
|
42
|
+
callback;
|
|
43
|
+
constructor(callback) {
|
|
44
|
+
this.callback = callback;
|
|
45
|
+
}
|
|
46
|
+
observe(target) {
|
|
47
|
+
this.callback([{
|
|
48
|
+
target,
|
|
49
|
+
contentRect: {
|
|
50
|
+
width,
|
|
51
|
+
height
|
|
52
|
+
}
|
|
53
|
+
}], this);
|
|
54
|
+
}
|
|
55
|
+
unobserve() {}
|
|
56
|
+
disconnect() {}
|
|
57
|
+
}
|
|
58
|
+
if (!globalThis.ResizeObserver) replace(globalThis, "ResizeObserver", {
|
|
59
|
+
writable: true,
|
|
60
|
+
value: FixedResizeObserver
|
|
61
|
+
});
|
|
62
|
+
replace(Element.prototype, "getBoundingClientRect", {
|
|
63
|
+
writable: true,
|
|
64
|
+
value: () => box(0, 0, width, height)
|
|
65
|
+
});
|
|
66
|
+
for (const [prop, value] of [
|
|
67
|
+
["offsetWidth", width],
|
|
68
|
+
["offsetHeight", height],
|
|
69
|
+
["clientWidth", width],
|
|
70
|
+
["clientHeight", height]
|
|
71
|
+
]) replace(HTMLElement.prototype, prop, { get: () => value });
|
|
72
|
+
return () => {
|
|
73
|
+
for (const undo of restore.reverse()) undo();
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// src/testing/intersection-observer.ts
|
|
77
|
+
function entryFor(target, isIntersecting) {
|
|
78
|
+
const rect = target.getBoundingClientRect();
|
|
79
|
+
return {
|
|
80
|
+
target,
|
|
81
|
+
isIntersecting,
|
|
82
|
+
intersectionRatio: isIntersecting ? 1 : 0,
|
|
83
|
+
boundingClientRect: rect,
|
|
84
|
+
intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),
|
|
85
|
+
rootBounds: null,
|
|
86
|
+
time: performance.now()
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in
|
|
91
|
+
* `beforeEach` and call `uninstall()` in `afterEach`.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* let io: FakeIntersectionObserverControls;
|
|
95
|
+
* beforeEach(() => { io = installFakeIntersectionObserver(); });
|
|
96
|
+
* afterEach(() => io.uninstall());
|
|
97
|
+
*
|
|
98
|
+
* it("loads the next page at the end of the list", async () => {
|
|
99
|
+
* renderWithStrata(<Pieces />);
|
|
100
|
+
* await screen.findByRole("list", { name: "Pieces" });
|
|
101
|
+
* io.scrollToEnd();
|
|
102
|
+
* expect(await screen.findByText("Celadon bowl")).toBeInTheDocument();
|
|
103
|
+
* });
|
|
104
|
+
*/
|
|
105
|
+
function installFakeIntersectionObserver() {
|
|
106
|
+
const previous = Object.getOwnPropertyDescriptor(globalThis, "IntersectionObserver");
|
|
107
|
+
const observers = [];
|
|
108
|
+
class FakeIntersectionObserver {
|
|
109
|
+
root;
|
|
110
|
+
rootMargin;
|
|
111
|
+
thresholds;
|
|
112
|
+
scrollMargin = "0px";
|
|
113
|
+
record;
|
|
114
|
+
constructor(callback, options = {}) {
|
|
115
|
+
this.root = options.root ?? null;
|
|
116
|
+
this.rootMargin = options.rootMargin ?? "0px";
|
|
117
|
+
const threshold = options.threshold ?? 0;
|
|
118
|
+
this.thresholds = Array.isArray(threshold) ? threshold : [threshold];
|
|
119
|
+
this.record = {
|
|
120
|
+
callback,
|
|
121
|
+
options,
|
|
122
|
+
targets: /* @__PURE__ */ new Set(),
|
|
123
|
+
self: this
|
|
124
|
+
};
|
|
125
|
+
observers.push(this.record);
|
|
126
|
+
}
|
|
127
|
+
observe(target) {
|
|
128
|
+
this.record.targets.add(target);
|
|
129
|
+
}
|
|
130
|
+
unobserve(target) {
|
|
131
|
+
this.record.targets.delete(target);
|
|
132
|
+
}
|
|
133
|
+
disconnect() {
|
|
134
|
+
this.record.targets.clear();
|
|
135
|
+
}
|
|
136
|
+
takeRecords() {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
Object.defineProperty(globalThis, "IntersectionObserver", {
|
|
141
|
+
configurable: true,
|
|
142
|
+
writable: true,
|
|
143
|
+
value: FakeIntersectionObserver
|
|
144
|
+
});
|
|
145
|
+
const deliver = (observer, targets, isIntersecting) => {
|
|
146
|
+
act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
observers,
|
|
150
|
+
intersect(el, isIntersecting = true) {
|
|
151
|
+
const watching = observers.filter((o) => o.targets.has(el));
|
|
152
|
+
for (const o of watching) deliver(o, [el], isIntersecting);
|
|
153
|
+
return watching.length;
|
|
154
|
+
},
|
|
155
|
+
scrollToEnd() {
|
|
156
|
+
const batches = observers.map((o) => [o, [...o.targets]]).filter(([, targets]) => targets.length > 0);
|
|
157
|
+
for (const [o, targets] of batches) deliver(o, targets, true);
|
|
158
|
+
return batches.reduce((n, [, targets]) => n + targets.length, 0);
|
|
159
|
+
},
|
|
160
|
+
uninstall() {
|
|
161
|
+
if (previous) Object.defineProperty(globalThis, "IntersectionObserver", previous);
|
|
162
|
+
else delete globalThis.IntersectionObserver;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
6
166
|
// src/testing/index.tsx
|
|
167
|
+
/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
|
|
7
168
|
function createTestQueryClient() {
|
|
8
169
|
return createQueryClient({ defaultOptions: { queries: {
|
|
9
170
|
retry: false,
|
|
@@ -11,12 +172,17 @@ function createTestQueryClient() {
|
|
|
11
172
|
gcTime: Infinity
|
|
12
173
|
} } });
|
|
13
174
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
175
|
+
/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
|
|
176
|
+
function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", ...options } = {}) {
|
|
177
|
+
const Wrapper = ({ children }) => /* @__PURE__ */ jsx(ThemeProvider, {
|
|
178
|
+
defaultPreference: colorScheme,
|
|
179
|
+
storageKey: null,
|
|
180
|
+
children: /* @__PURE__ */ jsx(StrataQueryProvider, {
|
|
181
|
+
client,
|
|
182
|
+
children: /* @__PURE__ */ jsx(MemoryRouter, {
|
|
183
|
+
initialEntries: [route],
|
|
184
|
+
children
|
|
185
|
+
})
|
|
20
186
|
})
|
|
21
187
|
});
|
|
22
188
|
return {
|
|
@@ -27,6 +193,6 @@ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), .
|
|
|
27
193
|
})
|
|
28
194
|
};
|
|
29
195
|
}
|
|
30
|
-
export { createTestQueryClient, renderWithStrata };
|
|
196
|
+
export { createTestQueryClient, installFakeIntersectionObserver, installLayoutShims, renderWithStrata };
|
|
31
197
|
|
|
32
198
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/index.tsx"],"sourcesContent":["/**\n * Test helpers: render a component inside a router and a query client, as a Strata app runs it.\n * Use with MSW for the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay.\n\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), ...options }: RenderOptions & { route?: string; client?: QueryClient } = {},\n) {\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataQueryProvider client={client}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataQueryProvider>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n"],"mappings":";;;;;;AAiBA,SAAgB,wBAAwB;CACtC,OAAO,kBAAkB,EAAE,gBAAgB,EAAE,SAAS;EAAE,OAAO;EAAO,WAAW;EAAU,QAAQ;CAAS,EAAE,EAAE,CAAC;AACnH;AAEA,SAAgB,iBACd,IACA,EAAE,QAAQ,KAAK,SAAS,sBAAsB,GAAG,GAAG,YAAsE,CAAC,GAC3H;CACA,MAAM,WAAW,EAAE,eACjB,oBAAC,qBAAD;EAA6B;EAC3B,UAAA,oBAAC,cAAD;GAAc,gBAAgB,CAAC,KAAK;GAAI;EAAuB,CAAA;CAC5C,CAAA;CAEvB,OAAO;EAAE;EAAQ,GAAG,OAAO,IAAI;GAAE,SAAS;GAAS,GAAG;EAAQ,CAAC;CAAE;AACnE"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../src/testing/layout.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width, DataTable and VirtualList through TanStack Virtual) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe. Real layout is checked by the visual suite in Chromium, never here.\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component inside a router and a query client, as a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n {\n route = \"/\",\n client = createTestQueryClient(),\n colorScheme = \"light\",\n ...options\n }: RenderOptions & { route?: string; client?: QueryClient; colorScheme?: ColorSchemePreference } = {},\n) {\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataQueryProvider>\n </ThemeProvider>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,IAAI,GAAW,GAAW,O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C;GAC1D,KAAK,MAAM,KAAK,UAAU,QAAQ,GAAG,CAAC,EAAE,GAAG,cAAc;GACzD,OAAO,SAAS;EAClB;EACA,cAAc;GAIZ,MAAM,UAAU,UAAU,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAU,CAAC,CAAC,QAAQ,GAAG,aAAa,QAAQ,SAAS,CAAC;GAC7G,KAAK,MAAM,CAAC,GAAG,YAAY,SAAS,QAAQ,GAAG,SAAS,IAAI;GAC5D,OAAO,QAAQ,QAAQ,GAAG,GAAG,aAAa,IAAI,QAAQ,QAAQ,CAAC;EACjE;EACA,YAAY;GACV,IAAI,UAAU,OAAO,eAAe,YAAY,wBAAwB,QAAQ;QAC3E,OAAQ,WAAkD;EACjE;CACF;AACF;;;AC7FA,SAAgB,wBAAwB;CACtC,OAAO,kBAAkB,EAAE,gBAAgB,EAAE,SAAS;EAAE,OAAO;EAAO,WAAW;EAAU,QAAQ;CAAS,EAAE,EAAE,CAAC;AACnH;;AAGA,SAAgB,iBACd,IACA,EACE,QAAQ,KACR,SAAS,sBAAsB,GAC/B,cAAc,SACd,GAAG,YAC8F,CAAC,GACpG;CACA,MAAM,WAAW,EAAE,eACjB,oBAAC,eAAD;EAAe,mBAAmB;EAAa,YAAY;EACzD,UAAA,oBAAC,qBAAD;GAA6B;GAC3B,UAAA,oBAAC,cAAD;IAAc,gBAAgB,CAAC,KAAK;IAAI;GAAuB,CAAA;EAC5C,CAAA;CACR,CAAA;CAEjB,OAAO;EAAE;EAAQ,GAAG,OAAO,IAAI;GAAE,SAAS;GAAS,GAAG;EAAQ,CAAC;CAAE;AACnE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "strata-react",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "React + Tailwind v4 components that ship structure, behaviour, states and a token contract, and no look: each product brings a theme generated from its own subject.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
package/dist/query-Bi7rfvwp.js
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import * as React from "react";
|
|
2
|
-
import { jsx } from "react/jsx-runtime";
|
|
3
|
-
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
|
4
|
-
// src/lib/errors.ts
|
|
5
|
-
/** Thrown by `fetchJson` on a non-2xx response; carries the status for `describeHttpError` and `describeActionError`. */
|
|
6
|
-
var HttpError = class extends Error {
|
|
7
|
-
status;
|
|
8
|
-
statusText;
|
|
9
|
-
url;
|
|
10
|
-
constructor(status, statusText, url) {
|
|
11
|
-
super(`${status} ${statusText} from ${url}`);
|
|
12
|
-
this.status = status;
|
|
13
|
-
this.statusText = statusText;
|
|
14
|
-
this.url = url;
|
|
15
|
-
this.name = "HttpError";
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
function refused(error) {
|
|
19
|
-
return `The request was refused (${error.status}): ${error.statusText || "no reason given"}.`;
|
|
20
|
-
}
|
|
21
|
-
/** The default `DescribeError` for loads: the HTTP status in a sentence, else the error's message, else a plain fallback. */
|
|
22
|
-
var describeHttpError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}). Nothing was changed.` : refused(error) : error instanceof Error && error.message ? error.message : "The data could not be loaded. Nothing was changed.";
|
|
23
|
-
/** The default for `useAsyncAction`: the HTTP status in a sentence, else the thrown Error's message, else undefined (the retry label alone). */
|
|
24
|
-
var describeActionError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}).` : refused(error) : error instanceof Error && error.message ? error.message : void 0;
|
|
25
|
-
// src/query/index.tsx
|
|
26
|
-
/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */
|
|
27
|
-
function createQueryClient(overrides) {
|
|
28
|
-
return new QueryClient({
|
|
29
|
-
...overrides,
|
|
30
|
-
defaultOptions: {
|
|
31
|
-
...overrides?.defaultOptions,
|
|
32
|
-
queries: {
|
|
33
|
-
retry: 1,
|
|
34
|
-
staleTime: 3e4,
|
|
35
|
-
refetchOnWindowFocus: false,
|
|
36
|
-
...overrides?.defaultOptions?.queries
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
/** Provides a query client (Strata's defaults unless one is passed) to the app. */
|
|
42
|
-
function StrataQueryProvider({ client, children }) {
|
|
43
|
-
const [fallback] = React.useState(() => client ?? createQueryClient());
|
|
44
|
-
return /* @__PURE__ */ jsx(QueryClientProvider, {
|
|
45
|
-
client: client ?? fallback,
|
|
46
|
-
children
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
/** Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`. */
|
|
50
|
-
function toLoad(query, describe = describeHttpError) {
|
|
51
|
-
if (query.status === "success") return {
|
|
52
|
-
status: "ready",
|
|
53
|
-
data: query.data
|
|
54
|
-
};
|
|
55
|
-
if (query.status === "error") return {
|
|
56
|
-
status: "error",
|
|
57
|
-
message: describe(query.error),
|
|
58
|
-
retry: () => void query.refetch()
|
|
59
|
-
};
|
|
60
|
-
return { status: "loading" };
|
|
61
|
-
}
|
|
62
|
-
/** `useQuery`, returned as a `Load<T>` for `DataView`. */
|
|
63
|
-
function useLoad(options) {
|
|
64
|
-
const { describeError, ...rest } = options;
|
|
65
|
-
return toLoad(useQuery(rest), describeError);
|
|
66
|
-
}
|
|
67
|
-
/** fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default. */
|
|
68
|
-
async function fetchJson(input, init) {
|
|
69
|
-
const headers = new Headers(init?.headers);
|
|
70
|
-
if (!headers.has("Accept")) headers.set("Accept", "application/json");
|
|
71
|
-
const res = await fetch(input, {
|
|
72
|
-
...init,
|
|
73
|
-
headers
|
|
74
|
-
});
|
|
75
|
-
if (!res.ok) throw new HttpError(res.status, res.statusText, String(input));
|
|
76
|
-
return await res.json();
|
|
77
|
-
}
|
|
78
|
-
export { useLoad as a, describeHttpError as c, toLoad as i, createQueryClient as n, HttpError as o, fetchJson as r, describeActionError as s, StrataQueryProvider as t };
|
|
79
|
-
|
|
80
|
-
//# sourceMappingURL=query-Bi7rfvwp.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-Bi7rfvwp.js","names":[],"sources":["../src/lib/errors.ts","../src/query/index.tsx"],"sourcesContent":["// Errors, described for a person. Anything that fails in front of someone (a load in DataView, an\n// action in AsyncButton) says what happened in a sentence, in the product's words, not the\n// developer's: `HttpError`'s own message (\"409 Conflict from /api/bookings\") is for logs. Loads\n// and actions share HttpError's status sentences, so the same failure reads the same everywhere,\n// and differ only in what is true afterwards: a failed load changed nothing, while a failed action\n// may have reached the server, so its sentence does not promise that.\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n }\n}\n\n/** Writes an error for a person: what happened, in a sentence. A product passes its own words. */\nexport type DescribeError = (error: unknown) => string;\n\nfunction refused(error: HttpError) {\n return `The request was refused (${error.status}): ${error.statusText || \"no reason given\"}.`;\n}\n\n/** The default `DescribeError` for loads: the HTTP status in a sentence, else the error's message, else a plain fallback. */\nexport const describeHttpError: DescribeError = (error) =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}). Nothing was changed.`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : \"The data could not be loaded. Nothing was changed.\";\n\n/** The default for `useAsyncAction`: the HTTP status in a sentence, else the thrown Error's message, else undefined (the retry label alone). */\nexport const describeActionError = (error: unknown): string | undefined =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}).`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : undefined;\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport { HttpError, describeHttpError, type DescribeError } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, type DescribeError };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/** Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`. */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), describeError);\n}\n\n/** fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default. */\nexport async function fetchJson<T>(input: string | URL, init?: RequestInit): Promise<T> {\n // Headers, tuple arrays and plain objects are all valid HeadersInit; normalise before adding the\n // default so a caller's Authorization (or their own Accept) is never dropped.\n const headers = new Headers(init?.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n const res = await fetch(input, { ...init, headers });\n if (!res.ok) throw new HttpError(res.status, res.statusText, String(input));\n return (await res.json()) as T;\n}\n"],"mappings":";;;;;AAQA,IAAa,YAAb,cAA+B,MAAM;CAExB;CACA;CACA;CAHX,YACE,QACA,YACA,KACA;EACA,MAAM,GAAG,OAAO,GAAG,WAAW,QAAQ,KAAK;EAJlC,KAAA,SAAA;EACA,KAAA,aAAA;EACA,KAAA,MAAA;EAGT,KAAK,OAAO;CACd;AACF;AAKA,SAAS,QAAQ,OAAkB;CACjC,OAAO,4BAA4B,MAAM,OAAO,KAAK,MAAM,cAAc,kBAAkB;AAC7F;;AAGA,IAAa,qBAAoC,UAC/C,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,2BAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN;;AAGR,IAAa,uBAAuB,UAClC,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,MAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN,KAAA;;;ACpBR,SAAgB,kBAAkB,WAA0D;CAC1F,OAAO,IAAI,YAAY;EACrB,GAAG;EACH,gBAAgB;GACd,GAAG,WAAW;GACd,SAAS;IAAE,OAAO;IAAG,WAAW;IAAQ,sBAAsB;IAAO,GAAG,WAAW,gBAAgB;GAAQ;EAC7G;CACF,CAAC;AACH;;AAGA,SAAgB,oBAAoB,EAAE,QAAQ,YAAiE;CAC7G,MAAM,CAAC,YAAY,MAAM,eAAe,UAAU,kBAAkB,CAAC;C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