strata-react 1.0.40 → 1.0.41
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 +25 -1
- package/UPGRADING.md +6 -0
- package/bin/strata-stock-classes.js +5 -0
- package/dist/components/compare-parts.d.ts +25 -0
- package/dist/components/compare-video.d.ts +4 -2
- package/dist/components/compare.d.ts +4 -2
- package/dist/components/toast.d.ts +3 -2
- package/dist/index.js +113 -6
- package/dist/index.js.map +1 -1
- package/dist/migrate/cli.d.ts +2 -0
- package/dist/migrate/stock-classes.d.ts +11 -0
- package/dist/migrate-cli.js +128 -0
- package/dist/migrate-cli.js.map +1 -0
- package/dist/{query-D163gXXZ.js → query-B934ufsW.js} +33 -2
- package/dist/query-B934ufsW.js.map +1 -0
- package/dist/strata.css +6 -0
- package/dist/strata.migrate.css +224 -0
- package/dist/testing.js +1 -1
- package/package.json +7 -2
- package/dist/query-D163gXXZ.js.map +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** What kind of stock class it is, named as the roles that replace it are. */
|
|
2
|
+
export type StockKind = "colour" | "text size" | "radius" | "shadow" | "font";
|
|
3
|
+
/** One stock class found at a line of a file. */
|
|
4
|
+
export type StockClass = {
|
|
5
|
+
line: number;
|
|
6
|
+
className: string;
|
|
7
|
+
kind: StockKind;
|
|
8
|
+
instead: string;
|
|
9
|
+
};
|
|
10
|
+
/** Stock classes in `source`, one entry per use. In a `.css` file only `@apply` lines are read. */
|
|
11
|
+
export declare function findStockClasses(source: string, file?: string): StockClass[];
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
// src/migrate/stock-classes.ts
|
|
5
|
+
var rules = [
|
|
6
|
+
{
|
|
7
|
+
kind: "colour",
|
|
8
|
+
test: new RegExp(`^(?:bg|text|border(?:-[xytblrse])?|ring|ring-offset|fill|stroke|from|via|to|divide|outline|accent|caret|decoration|placeholder|shadow|inset-shadow|inset-ring|text-shadow)-(?:(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|100|200|300|400|500|600|700|800|900|950)|white|black)(?:/\\d+)?$`),
|
|
9
|
+
instead: "a colour role: bg-primary, bg-muted, text-muted-foreground, border-border, bg-danger-subtle…"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
kind: "text size",
|
|
13
|
+
test: /^text-(?:xs|sm|base|lg|xl|[2-9]xl)(?:\/[\w.[\]-]+)?$/,
|
|
14
|
+
instead: "a type step: type-caption, type-label, type-body-sm, type-body, type-heading, type-title"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
kind: "radius",
|
|
18
|
+
test: /^rounded(?:-(?:t|r|b|l|s|e|tl|tr|br|bl|ss|se|ee|es))?-(?:xs|sm|md|lg|xl|2xl|3xl|4xl)$/,
|
|
19
|
+
instead: "a radius role: rounded-control, rounded-surface, rounded-overlay or rounded-pill"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
kind: "shadow",
|
|
23
|
+
test: /^(?:inset-)?shadow-(?:2xs|xs|sm|md|lg|xl|2xl|inner)$/,
|
|
24
|
+
instead: "shadow-overlay for what floats, a border for what sits on the page"
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
kind: "font",
|
|
28
|
+
test: /^font-serif$/,
|
|
29
|
+
instead: "font-display, or a face your theme names"
|
|
30
|
+
}
|
|
31
|
+
];
|
|
32
|
+
/** Stock classes in `source`, one entry per use. In a `.css` file only `@apply` lines are read. */
|
|
33
|
+
function findStockClasses(source, file = "") {
|
|
34
|
+
const css = /\.css$/.test(file);
|
|
35
|
+
const found = [];
|
|
36
|
+
let applying = false;
|
|
37
|
+
source.split("\n").forEach((text, i) => {
|
|
38
|
+
if (css) {
|
|
39
|
+
if (!applying && !text.includes("@apply")) return;
|
|
40
|
+
applying = !/[;}]/.test(text.slice(Math.max(0, text.indexOf("@apply"))));
|
|
41
|
+
}
|
|
42
|
+
for (const token of text.match(/[^\s"'`<>{}()=,;]+/g) ?? []) {
|
|
43
|
+
const className = token.slice(token.lastIndexOf(":") + 1).replace(/^!|!$/g, "");
|
|
44
|
+
const rule = rules.find((r) => r.test.test(className));
|
|
45
|
+
if (rule) found.push({
|
|
46
|
+
line: i + 1,
|
|
47
|
+
className: token.replace(/^!/, ""),
|
|
48
|
+
kind: rule.kind,
|
|
49
|
+
instead: rule.instead
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
return found;
|
|
54
|
+
}
|
|
55
|
+
// src/migrate/cli.ts
|
|
56
|
+
var usage = `Usage: strata-stock-classes [options] [folder or file ...]
|
|
57
|
+
|
|
58
|
+
Lists the stock Tailwind classes (colours such as bg-stone-100, text-sm, rounded-xl, shadow-lg, font-serif)
|
|
59
|
+
that strata.css would stop compiling, so an app on strata.migrate.css knows what is left to convert. Reads
|
|
60
|
+
.ts .tsx .js .jsx .mjs .html .mdx .vue .svelte files, and the @apply lines of .css files. Default: ./src.
|
|
61
|
+
|
|
62
|
+
--fail exit 1 when any are found (for a CI step that holds the line while migrating)
|
|
63
|
+
--help show this
|
|
64
|
+
`;
|
|
65
|
+
var readable = /\.(?:[cm]?[jt]sx?|html|mdx|vue|svelte|css)$/;
|
|
66
|
+
var skipped = /* @__PURE__ */ new Set([
|
|
67
|
+
"node_modules",
|
|
68
|
+
"dist",
|
|
69
|
+
".git",
|
|
70
|
+
"storybook-static",
|
|
71
|
+
"coverage"
|
|
72
|
+
]);
|
|
73
|
+
function* walk(path) {
|
|
74
|
+
if (statSync(path).isFile()) {
|
|
75
|
+
if (readable.test(path)) yield path;
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
for (const name of readdirSync(path).sort()) if (!skipped.has(name)) yield* walk(join(path, name));
|
|
79
|
+
}
|
|
80
|
+
/** Runs the command; the exit code. */
|
|
81
|
+
async function main(argv, out = (t) => console.log(t)) {
|
|
82
|
+
const { values, positionals } = parseArgs({
|
|
83
|
+
args: argv,
|
|
84
|
+
options: {
|
|
85
|
+
fail: { type: "boolean" },
|
|
86
|
+
help: { type: "boolean" }
|
|
87
|
+
},
|
|
88
|
+
allowPositionals: true
|
|
89
|
+
});
|
|
90
|
+
if (values.help) {
|
|
91
|
+
out(usage);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
const roots = positionals.length ? positionals : ["src"];
|
|
95
|
+
const all = [];
|
|
96
|
+
for (const root of roots) {
|
|
97
|
+
try {
|
|
98
|
+
statSync(root);
|
|
99
|
+
} catch {
|
|
100
|
+
out(`strata-stock-classes: ${root} does not exist`);
|
|
101
|
+
return 2;
|
|
102
|
+
}
|
|
103
|
+
for (const file of walk(root)) {
|
|
104
|
+
const found = findStockClasses(readFileSync(file, "utf8"), file);
|
|
105
|
+
if (found.length) all.push({
|
|
106
|
+
file: relative(process.cwd(), file),
|
|
107
|
+
found
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const total = all.reduce((n, f) => n + f.found.length, 0);
|
|
112
|
+
if (!total) {
|
|
113
|
+
out("No stock Tailwind classes left. Switch the import to strata-react/strata.css.");
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
117
|
+
for (const { file, found } of all) for (const f of found) {
|
|
118
|
+
out(`${file}:${f.line} ${f.className} (${f.kind})`);
|
|
119
|
+
byKind.set(f.kind, (byKind.get(f.kind) ?? 0) + 1);
|
|
120
|
+
}
|
|
121
|
+
out("");
|
|
122
|
+
out(`${total} stock classes in ${all.length} files: ${[...byKind].map(([k, n]) => `${n} ${k}`).join(", ")}.`);
|
|
123
|
+
for (const rule of new Set(all.flatMap((f) => f.found.map((x) => `${x.kind}: ${x.instead}`)))) out(` ${rule}`);
|
|
124
|
+
return values.fail ? 1 : 0;
|
|
125
|
+
}
|
|
126
|
+
export { main };
|
|
127
|
+
|
|
128
|
+
//# sourceMappingURL=migrate-cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate-cli.js","names":[],"sources":["../src/migrate/stock-classes.ts","../src/migrate/cli.ts"],"sourcesContent":["// Finds the stock Tailwind classes an app still uses, for an app moving onto Strata one screen at a time (issue #225).\n// `strata.css` clears Tailwind's colour, type-size, radius, shadow and font namespaces, so `bg-stone-100`, `text-sm`,\n// `rounded-xl` and `shadow-lg` stop compiling the moment it is imported. `strata.migrate.css` keeps them, and this lists\n// what is left to convert so the app knows when `strata.css` is one import away. It reads class names as text (no Tailwind\n// build, no dependency), so it is a list to work from, not a proof: a class built from parts (\"bg-\" + tone) is invisible\n// to it and to Tailwind's own scanner alike, and a word that only looks like a class in a string can be listed.\n\n/** What kind of stock class it is, named as the roles that replace it are. */\nexport type StockKind = \"colour\" | \"text size\" | \"radius\" | \"shadow\" | \"font\";\n\n/** One stock class found at a line of a file. */\nexport type StockClass = { line: number; className: string; kind: StockKind; instead: string };\n\nconst COLOURS = \"slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose\";\nconst COLOUR_UTILITIES = \"bg|text|border(?:-[xytblrse])?|ring|ring-offset|fill|stroke|from|via|to|divide|outline|accent|caret|decoration|placeholder|shadow|inset-shadow|inset-ring|text-shadow\";\nconst colour = new RegExp(`^(?:${COLOUR_UTILITIES})-(?:(?:${COLOURS})-(?:50|100|200|300|400|500|600|700|800|900|950)|white|black)(?:/\\\\d+)?$`);\nconst textSize = /^text-(?:xs|sm|base|lg|xl|[2-9]xl)(?:\\/[\\w.[\\]-]+)?$/;\nconst radius = /^rounded(?:-(?:t|r|b|l|s|e|tl|tr|br|bl|ss|se|ee|es))?-(?:xs|sm|md|lg|xl|2xl|3xl|4xl)$/;\nconst shadow = /^(?:inset-)?shadow-(?:2xs|xs|sm|md|lg|xl|2xl|inner)$/;\nconst font = /^font-serif$/;\n\nconst rules: { kind: StockKind; test: RegExp; instead: string }[] = [\n { kind: \"colour\", test: colour, instead: \"a colour role: bg-primary, bg-muted, text-muted-foreground, border-border, bg-danger-subtle…\" },\n { kind: \"text size\", test: textSize, instead: \"a type step: type-caption, type-label, type-body-sm, type-body, type-heading, type-title\" },\n { kind: \"radius\", test: radius, instead: \"a radius role: rounded-control, rounded-surface, rounded-overlay or rounded-pill\" },\n { kind: \"shadow\", test: shadow, instead: \"shadow-overlay for what floats, a border for what sits on the page\" },\n { kind: \"font\", test: font, instead: \"font-display, or a face your theme names\" },\n];\n\n/** Stock classes in `source`, one entry per use. In a `.css` file only `@apply` lines are read. */\nexport function findStockClasses(source: string, file = \"\"): StockClass[] {\n const css = /\\.css$/.test(file);\n const found: StockClass[] = [];\n // In a stylesheet an `@apply` runs to its `;` (or the closing brace), however many lines it is written over.\n let applying = false;\n source.split(\"\\n\").forEach((text, i) => {\n if (css) {\n if (!applying && !text.includes(\"@apply\")) return;\n applying = !/[;}]/.test(text.slice(Math.max(0, text.indexOf(\"@apply\"))));\n }\n for (const token of text.match(/[^\\s\"'`<>{}()=,;]+/g) ?? []) {\n // The utility is what follows the last variant (`dark:hover:bg-stone-100`), without an important mark.\n const className = token.slice(token.lastIndexOf(\":\") + 1).replace(/^!|!$/g, \"\");\n const rule = rules.find((r) => r.test.test(className));\n if (rule) found.push({ line: i + 1, className: token.replace(/^!/, \"\"), kind: rule.kind, instead: rule.instead });\n }\n });\n return found;\n}\n","// The strata-stock-classes command: lists the stock Tailwind classes still in an app's source (see stock-classes.ts).\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { findStockClasses, type StockClass } from \"./stock-classes\";\n\nconst usage = `Usage: strata-stock-classes [options] [folder or file ...]\n\nLists the stock Tailwind classes (colours such as bg-stone-100, text-sm, rounded-xl, shadow-lg, font-serif)\nthat strata.css would stop compiling, so an app on strata.migrate.css knows what is left to convert. Reads\n.ts .tsx .js .jsx .mjs .html .mdx .vue .svelte files, and the @apply lines of .css files. Default: ./src.\n\n --fail exit 1 when any are found (for a CI step that holds the line while migrating)\n --help show this\n`;\n\nconst readable = /\\.(?:[cm]?[jt]sx?|html|mdx|vue|svelte|css)$/;\nconst skipped = new Set([\"node_modules\", \"dist\", \".git\", \"storybook-static\", \"coverage\"]);\n\nfunction* walk(path: string): Generator<string> {\n if (statSync(path).isFile()) {\n if (readable.test(path)) yield path;\n return;\n }\n for (const name of readdirSync(path).sort()) if (!skipped.has(name)) yield* walk(join(path, name));\n}\n\n/** Runs the command; the exit code. */\nexport async function main(argv: string[], out: (text: string) => void = (t) => console.log(t)): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, options: { fail: { type: \"boolean\" }, help: { type: \"boolean\" } }, allowPositionals: true });\n if (values.help) {\n out(usage);\n return 0;\n }\n const roots = positionals.length ? positionals : [\"src\"];\n const all: { file: string; found: StockClass[] }[] = [];\n for (const root of roots) {\n try {\n statSync(root);\n } catch {\n out(`strata-stock-classes: ${root} does not exist`);\n return 2;\n }\n for (const file of walk(root)) {\n const found = findStockClasses(readFileSync(file, \"utf8\"), file);\n if (found.length) all.push({ file: relative(process.cwd(), file), found });\n }\n }\n const total = all.reduce((n, f) => n + f.found.length, 0);\n if (!total) {\n out(\"No stock Tailwind classes left. Switch the import to strata-react/strata.css.\");\n return 0;\n }\n const byKind = new Map<string, number>();\n for (const { file, found } of all) {\n for (const f of found) {\n out(`${file}:${f.line} ${f.className} (${f.kind})`);\n byKind.set(f.kind, (byKind.get(f.kind) ?? 0) + 1);\n }\n }\n out(\"\");\n out(`${total} stock classes in ${all.length} files: ${[...byKind].map(([k, n]) => `${n} ${k}`).join(\", \")}.`);\n for (const rule of new Set(all.flatMap((f) => f.found.map((x) => `${x.kind}: ${x.instead}`)))) out(` ${rule}`);\n return values.fail ? 1 : 0;\n}\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;EACpD,OAAO,IAAI,EAAE,OAAO,OAAO,IAAI,EAAE,IAAI,KAAK,KAAK,CAAC;CAClD;CAEF,IAAI,EAAE;CACN,IAAI,GAAG,MAAM,oBAAoB,IAAI,OAAO,UAAU,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,OAAO,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE;CAC5G,KAAK,MAAM,QAAQ,IAAI,IAAI,IAAI,SAAS,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,EAAE,KAAK,IAAI,EAAE,SAAS,CAAC,CAAC,GAAG,IAAI,KAAK,MAAM;CAC9G,OAAO,OAAO,OAAO,IAAI;AAC3B"}
|
|
@@ -42,8 +42,39 @@ var marks = {
|
|
|
42
42
|
color: "text-warning"
|
|
43
43
|
}
|
|
44
44
|
};
|
|
45
|
-
|
|
45
|
+
var mounted = [];
|
|
46
|
+
var watchers = /* @__PURE__ */ new Set();
|
|
47
|
+
var changed = () => watchers.forEach((w) => w());
|
|
48
|
+
var watch = (w) => {
|
|
49
|
+
watchers.add(w);
|
|
50
|
+
return () => void watchers.delete(w);
|
|
51
|
+
};
|
|
52
|
+
/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */
|
|
53
|
+
function useOwnsQueue() {
|
|
54
|
+
const id = React.useId();
|
|
55
|
+
React.useLayoutEffect(() => {
|
|
56
|
+
mounted.push(id);
|
|
57
|
+
changed();
|
|
58
|
+
return () => {
|
|
59
|
+
mounted.splice(mounted.indexOf(id), 1);
|
|
60
|
+
changed();
|
|
61
|
+
};
|
|
62
|
+
}, [id]);
|
|
63
|
+
const owns = React.useSyncExternalStore(watch, () => mounted[0] === id, () => true);
|
|
64
|
+
const [warned, setWarned] = React.useState(false);
|
|
65
|
+
React.useEffect(() => {
|
|
66
|
+
if (owns || warned || mounted.indexOf(id) < 1) return;
|
|
67
|
+
setWarned(true);
|
|
68
|
+
}, [
|
|
69
|
+
owns,
|
|
70
|
+
warned,
|
|
71
|
+
id
|
|
72
|
+
]);
|
|
73
|
+
return owns;
|
|
74
|
+
}
|
|
75
|
+
/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */
|
|
46
76
|
function StrataToastRegion({ label = "Notifications", className }) {
|
|
77
|
+
if (!useOwnsQueue()) return null;
|
|
47
78
|
return /* @__PURE__ */ jsx(UNSTABLE_ToastRegion, {
|
|
48
79
|
queue,
|
|
49
80
|
"aria-label": label,
|
|
@@ -175,4 +206,4 @@ async function fetchJson(input, init, { readError = readErrorBody } = {}) {
|
|
|
175
206
|
}
|
|
176
207
|
export { toLoad as a, toast as c, staleOf as i, toastTimeout as l, createQueryClient as n, useLoad as o, fetchJson as r, StrataToastRegion as s, StrataQueryProvider as t, overlaySurface as u };
|
|
177
208
|
|
|
178
|
-
//# sourceMappingURL=query-
|
|
209
|
+
//# sourceMappingURL=query-B934ufsW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-B934ufsW.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.tsx"],"sourcesContent":["// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","import * as React from \"react\";\nimport { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// - One region at a time, enforced (issue #230): the first mounted owns the queue and a second one draws nothing and\n// says so in development, naming the fix. Two regions on one queue show every toast twice, which looks like a bug in\n// the toast and (in a test) fails `findByText` with \"Found multiple elements\"; the usual cause is a route tree that\n// draws the region in its root layout while a test helper draws one too (`renderRoutes(..., { toasts: false })`),\n// or an app with a region in a layout and another in a page. Ownership is held by a mounted-order list, not by the\n// queue, so unmounting the owner hands it to the next region.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n// The regions mounted now, oldest first: the first draws, the rest stay empty.\nconst mounted: string[] = [];\nconst watchers = new Set<() => void>();\nconst changed = () => watchers.forEach((w) => w());\nconst watch = (w: () => void) => {\n watchers.add(w);\n return () => void watchers.delete(w);\n};\n\n/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */\nfunction useOwnsQueue(): boolean {\n const id = React.useId();\n React.useLayoutEffect(() => {\n mounted.push(id);\n changed();\n return () => {\n mounted.splice(mounted.indexOf(id), 1);\n changed();\n };\n }, [id]);\n const owns = React.useSyncExternalStore(watch, () => mounted[0] === id, () => true);\n const [warned, setWarned] = React.useState(false);\n React.useEffect(() => {\n if (owns || warned || mounted.indexOf(id) < 1) return;\n setWarned(true);\n if (import.meta.env?.DEV) {\n console.warn(\"strata-react: a StrataToastRegion is already mounted, so this one draws nothing. Render it once at the app root; in a test of a route tree that draws its own, pass `toasts: false` to renderRoutes.\");\n }\n }, [owns, warned, id]);\n return owns;\n}\n\n/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n const owns = useOwnsQueue();\n if (!owns) return null;\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\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, Stale } from \"../components/data-view\";\nimport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody };\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/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\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/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(input: string | URL, init?: RequestInit, { readError = readErrorBody }: FetchJsonOptions = {}): 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) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { useInfiniteLoad, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, type Job, type JobOptions } from \"./job\";\n"],"mappings":";;;;;;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AAG;EAAM;CAAQ,CAAC;CACnD,IAAI,CAAC,IAAI,IAAI;EAGX,MAAM,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE;EAC3C,IAAI,OAAgB,OAAO,KAAA;EAC3B,IAAI;GACF,IAAI,KAAK,OAAO,KAAK,MAAM,GAAG;EAChC,QAAQ,CAER;EACA,MAAM,IAAI,UAAU,IAAI,QAAQ,IAAI,YAAY,OAAO,KAAK,GAAG,MAAM,UAAU,IAAI,CAAC;CACtF;CAGA,MAAM,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,IAAI,KAAK;CACtD,OAAQ,OAAO,KAAK,MAAM,IAAI,IAAI,KAAA;AACpC"}
|
package/dist/strata.css
CHANGED
|
@@ -6,8 +6,13 @@
|
|
|
6
6
|
@import "./theme.generated.css"; (palette.mjs output: shadcn roles + 12-step ramps)
|
|
7
7
|
@import "./theme.css"; (status roles, fonts, any subject colours, with reasons)
|
|
8
8
|
|
|
9
|
+
An app that already has its own Tailwind colours and sizes imports "strata-react/strata.migrate.css"
|
|
10
|
+
instead: this file without the reset below, so its stock classes keep compiling while it moves
|
|
11
|
+
screens over (the build writes it from this file: scripts/copy-css.mjs). The README says when.
|
|
12
|
+
|
|
9
13
|
The research behind every value is in jburnhams/ux-research, ui-library/tokens.md. */
|
|
10
14
|
|
|
15
|
+
/* strata:strict-begin */
|
|
11
16
|
/* Clear Tailwind's stock namespaces right after Tailwind's own theme loads. With these gone,
|
|
12
17
|
`bg-indigo-500`, `text-sm`, `rounded-xl` and `shadow-lg` do not compile at all: the only colours,
|
|
13
18
|
type steps, radii and shadows that exist are the ones the product's theme names. That is the
|
|
@@ -19,6 +24,7 @@
|
|
|
19
24
|
--shadow-*: initial;
|
|
20
25
|
--font-*: initial;
|
|
21
26
|
}
|
|
27
|
+
/* strata:strict-end */
|
|
22
28
|
|
|
23
29
|
/* React Aria's state variants (`selected:`, `pressed:`, `hover:`, `focus-visible:`, `disabled:`, `open:`,
|
|
24
30
|
`invalid:`, `expanded:`, `sort-ascending:`…): each reads the `data-*` attribute React Aria Components
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/* strata-react: the token contract, the namespace reset, the type steps, motion utilities and the
|
|
2
|
+
base layer. It ships no colours. A product imports it between Tailwind and its own theme:
|
|
3
|
+
|
|
4
|
+
@import "tailwindcss";
|
|
5
|
+
@import "strata-react/strata.css";
|
|
6
|
+
@import "./theme.generated.css"; (palette.mjs output: shadcn roles + 12-step ramps)
|
|
7
|
+
@import "./theme.css"; (status roles, fonts, any subject colours, with reasons)
|
|
8
|
+
|
|
9
|
+
An app that already has its own Tailwind colours and sizes imports "strata-react/strata.migrate.css"
|
|
10
|
+
instead: this file without the reset below, so its stock classes keep compiling while it moves
|
|
11
|
+
screens over (the build writes it from this file: scripts/copy-css.mjs). The README says when.
|
|
12
|
+
|
|
13
|
+
The research behind every value is in jburnhams/ux-research, ui-library/tokens.md. */
|
|
14
|
+
|
|
15
|
+
/* MIGRATION MODE (strata.migrate.css): Tailwind's stock colours, sizes, radii, shadows and fonts are NOT cleared here, so an
|
|
16
|
+
app's own `bg-stone-100` and `text-sm` keep compiling beside Strata's roles. Switch the import to strata.css once
|
|
17
|
+
`strata-stock-classes` finds nothing left. */
|
|
18
|
+
|
|
19
|
+
/* React Aria's state variants (`selected:`, `pressed:`, `hover:`, `focus-visible:`, `disabled:`, `open:`,
|
|
20
|
+
`invalid:`, `expanded:`, `sort-ascending:`…): each reads the `data-*` attribute React Aria Components
|
|
21
|
+
sets, so state is styled once where it is used and never copied into a variant map. On a plain
|
|
22
|
+
element `hover:`, `focus-visible:` and `disabled:` still mean the browser's own (the plugin only takes
|
|
23
|
+
over on elements React Aria marks with `data-rac`). The plugin is a dependency of strata-react, so an
|
|
24
|
+
app needs no install step for it. */
|
|
25
|
+
@plugin "tailwindcss-react-aria-components";
|
|
26
|
+
|
|
27
|
+
@custom-variant dark (&:is(.dark *));
|
|
28
|
+
|
|
29
|
+
/* Status roles are part of the contract but not of the generated palette: the product solves them
|
|
30
|
+
(pale tint + dark ink of one hue, ink >= 6:1 on its tint and on the ground) and sets the
|
|
31
|
+
variables in its theme. Strata only names them. Never the accent. */
|
|
32
|
+
@theme inline {
|
|
33
|
+
--color-success: var(--success);
|
|
34
|
+
--color-success-subtle: var(--success-subtle);
|
|
35
|
+
--color-warning: var(--warning);
|
|
36
|
+
--color-warning-subtle: var(--warning-subtle);
|
|
37
|
+
--color-danger: var(--danger);
|
|
38
|
+
--color-danger-subtle: var(--danger-subtle);
|
|
39
|
+
--color-info: var(--info);
|
|
40
|
+
--color-info-subtle: var(--info-subtle);
|
|
41
|
+
--color-surface-sunken: var(--surface-sunken);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
@theme {
|
|
45
|
+
/* System faces until the product names its own (a later @theme block wins). One family on an
|
|
46
|
+
Operate surface; --font-display is for page titles only. */
|
|
47
|
+
--font-sans: ui-sans-serif, system-ui, sans-serif;
|
|
48
|
+
--font-mono: ui-monospace, "SFMono-Regular", Menlo, monospace;
|
|
49
|
+
--font-display: var(--font-sans);
|
|
50
|
+
|
|
51
|
+
/* Radius by role. Optical nesting: inner = outer - padding, so a control inside an 8px overlay
|
|
52
|
+
with 4px padding is 4px, never the same value as its container. */
|
|
53
|
+
--radius-control: 4px;
|
|
54
|
+
--radius-surface: 6px;
|
|
55
|
+
--radius-overlay: 8px;
|
|
56
|
+
--radius-pill: 9999px;
|
|
57
|
+
|
|
58
|
+
/* One elevation channel per surface: hairlines for things on the page, a shadow only for what
|
|
59
|
+
floats above it. */
|
|
60
|
+
--shadow-overlay: 0 1px 2px oklch(0% 0 0 / 0.08), 0 8px 24px oklch(0% 0 0 / 0.12);
|
|
61
|
+
|
|
62
|
+
/* Effects (colour, opacity) never overshoot; spatial gets Material Standard's barely visible
|
|
63
|
+
settle. Expressive springs are a product allowance, recorded in its DESIGN.md. */
|
|
64
|
+
--ease-effects: cubic-bezier(0.34, 0.8, 0.34, 1);
|
|
65
|
+
--ease-spatial: cubic-bezier(0.27, 1.06, 0.18, 1);
|
|
66
|
+
--ease-moment: cubic-bezier(0.23, 1, 0.32, 1);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/* Non-colour defaults in the base layer, so any unlayered rule in the product's theme wins
|
|
70
|
+
regardless of import order. */
|
|
71
|
+
@layer base {
|
|
72
|
+
:root {
|
|
73
|
+
--surface-sunken: var(--neutral-2);
|
|
74
|
+
|
|
75
|
+
/* Density: control heights move together (button, input, select). */
|
|
76
|
+
--control-h: 2.5rem;
|
|
77
|
+
--control-h-sm: 2rem;
|
|
78
|
+
/* A button's side padding and icon size, a role like its height (issue #210): a second look scopes them on a class. */
|
|
79
|
+
--control-px: 1rem;
|
|
80
|
+
--control-px-sm: 0.75rem;
|
|
81
|
+
--control-icon: 1rem;
|
|
82
|
+
|
|
83
|
+
--motion-effects: 200ms;
|
|
84
|
+
--motion-spatial: 350ms;
|
|
85
|
+
/* Press feedback is the one motion on a frequent action: 100ms, 2%, felt more than seen. A
|
|
86
|
+
moment is the rare, earned one; slower, hard ease-out, no overshoot. */
|
|
87
|
+
--motion-press: 100ms;
|
|
88
|
+
--motion-moment: 500ms;
|
|
89
|
+
|
|
90
|
+
/* The page title's voice. A product with a display face sets these with it. */
|
|
91
|
+
--title-weight: 650;
|
|
92
|
+
--title-stretch: 100%;
|
|
93
|
+
--title-tracking: -0.01em;
|
|
94
|
+
}
|
|
95
|
+
.dark {
|
|
96
|
+
--surface-sunken: var(--neutral-1);
|
|
97
|
+
}
|
|
98
|
+
/* `default` exists so a region can step back to ordinary density inside a compact page. */
|
|
99
|
+
[data-density="default"] {
|
|
100
|
+
--control-h: 2.5rem;
|
|
101
|
+
--control-h-sm: 2rem;
|
|
102
|
+
}
|
|
103
|
+
[data-density="compact"] {
|
|
104
|
+
--control-h: 2rem;
|
|
105
|
+
--control-h-sm: 1.75rem;
|
|
106
|
+
}
|
|
107
|
+
/* After the density rules, so a coarse pointer always wins: every control stays a 44px target. */
|
|
108
|
+
@media (pointer: coarse) {
|
|
109
|
+
:root,
|
|
110
|
+
[data-density="default"],
|
|
111
|
+
[data-density="compact"] {
|
|
112
|
+
--control-h: 2.75rem;
|
|
113
|
+
--control-h-sm: 2.75rem;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/* Type steps as utilities, not --text-* keys: a compound of size, line height and weight that
|
|
119
|
+
cn() can tell apart from text colours. Operate scale, ratio about 1.2, fixed rem; nothing above
|
|
120
|
+
28px except `type-display`, which is for Persuade surfaces only. */
|
|
121
|
+
/* Each step reads its own variables and falls back to today's value, so a product with another scale (or a
|
|
122
|
+
region with a second look) sets `--type-body-size`, `--type-body-leading`, `--type-heading-weight`… on a
|
|
123
|
+
class and every component with that step follows (issue #210). Names: --type-<step>-size, -leading, -weight. */
|
|
124
|
+
@utility type-caption { font-size: var(--type-caption-size, 0.75rem); line-height: var(--type-caption-leading, 1rem); font-weight: var(--type-caption-weight, 400); }
|
|
125
|
+
@utility type-label { font-size: var(--type-label-size, 0.875rem); line-height: var(--type-label-leading, 1.25rem); font-weight: var(--type-label-weight, 500); }
|
|
126
|
+
@utility type-body-sm { font-size: var(--type-body-sm-size, 0.875rem); line-height: var(--type-body-sm-leading, 1.25rem); font-weight: var(--type-body-sm-weight, 400); }
|
|
127
|
+
@utility type-body { font-size: var(--type-body-size, 1rem); line-height: var(--type-body-leading, 1.5rem); font-weight: var(--type-body-weight, 400); }
|
|
128
|
+
@utility type-heading { font-size: var(--type-heading-size, 1.125rem); line-height: var(--type-heading-leading, 1.5rem); font-weight: var(--type-heading-weight, 600); }
|
|
129
|
+
@utility type-title {
|
|
130
|
+
font-family: var(--font-display);
|
|
131
|
+
font-size: var(--type-title-size, 1.75rem);
|
|
132
|
+
line-height: var(--type-title-leading, 2.25rem);
|
|
133
|
+
font-weight: var(--title-weight);
|
|
134
|
+
font-stretch: var(--title-stretch);
|
|
135
|
+
letter-spacing: var(--title-tracking);
|
|
136
|
+
}
|
|
137
|
+
@utility type-figure { font-size: var(--type-figure-size, 1.75rem); line-height: var(--type-figure-leading, 2.25rem); font-weight: var(--type-figure-weight, 500); font-variant-numeric: tabular-nums; }
|
|
138
|
+
@utility type-display {
|
|
139
|
+
font-family: var(--font-display);
|
|
140
|
+
font-size: clamp(2.25rem, 1.5rem + 3vw, 4rem);
|
|
141
|
+
line-height: 1.05;
|
|
142
|
+
font-weight: var(--title-weight);
|
|
143
|
+
font-stretch: var(--title-stretch);
|
|
144
|
+
letter-spacing: -0.02em;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/* State transitions: named properties only (never `transition: all`). `scale` is listed for the
|
|
148
|
+
press feedback and runs at the shorter press duration. */
|
|
149
|
+
@utility transition-state {
|
|
150
|
+
transition-property: color, background-color, border-color, opacity, box-shadow, scale;
|
|
151
|
+
transition-duration: var(--motion-effects), var(--motion-effects), var(--motion-effects), var(--motion-effects),
|
|
152
|
+
var(--motion-effects), var(--motion-press);
|
|
153
|
+
transition-timing-function: var(--ease-effects);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* Press feedback: 2% is the most a control used tens of times a day can move without feeling slow. */
|
|
157
|
+
@utility press {
|
|
158
|
+
&:active:not(:disabled) { scale: 0.98; }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/* A moment's entrance: CSS only, runs once when the element mounts. Reduced motion collapses it. */
|
|
162
|
+
@utility enter-moment {
|
|
163
|
+
transition-property: opacity, translate;
|
|
164
|
+
transition-duration: var(--motion-moment);
|
|
165
|
+
transition-timing-function: var(--ease-moment);
|
|
166
|
+
@starting-style { opacity: 0; translate: 0 -0.75rem; }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* Stacking, once, for every floating thing, so an app never writes a z-index. A bar (the undo
|
|
170
|
+
bar, toasts) sits above panes and sticky headers; overlays (dialogs, popovers, menus) above
|
|
171
|
+
bars; a tooltip above everything, since it can name a control inside an overlay. */
|
|
172
|
+
@utility layer-bar { z-index: 50; }
|
|
173
|
+
@utility layer-overlay { z-index: 60; }
|
|
174
|
+
@utility layer-tip { z-index: 70; }
|
|
175
|
+
|
|
176
|
+
/* The dim behind a dialog or full-screen view. Black at an alpha, not the foreground role: in a dark
|
|
177
|
+
theme `foreground` is light, so a foreground scrim brightened the page instead of dimming it
|
|
178
|
+
(strata-react issue #136). Not a theme role, so no app has anything to add; darker in the dark
|
|
179
|
+
scheme, where the same alpha would barely show. */
|
|
180
|
+
@utility scrim {
|
|
181
|
+
background-color: rgb(0 0 0 / 0.4);
|
|
182
|
+
:where(.dark) & { background-color: rgb(0 0 0 / 0.65); }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/* An overlay's entrance: an ordinary effect (fade and 2% scale), CSS only, once on mount. Overlays
|
|
186
|
+
are occasional (character.md), so the effects duration and no overshoot; they close at once.
|
|
187
|
+
Reduced motion collapses it in the rule below. */
|
|
188
|
+
@utility enter-overlay {
|
|
189
|
+
transition-property: opacity, scale;
|
|
190
|
+
transition-duration: var(--motion-effects);
|
|
191
|
+
transition-timing-function: var(--ease-effects);
|
|
192
|
+
@starting-style { opacity: 0; scale: 0.98; }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
@layer base {
|
|
196
|
+
html { color-scheme: light; }
|
|
197
|
+
.dark { color-scheme: dark; }
|
|
198
|
+
body {
|
|
199
|
+
background-color: var(--background);
|
|
200
|
+
color: var(--foreground);
|
|
201
|
+
font-family: var(--font-sans);
|
|
202
|
+
font-size: 1rem;
|
|
203
|
+
line-height: 1.5rem;
|
|
204
|
+
-webkit-font-smoothing: antialiased;
|
|
205
|
+
}
|
|
206
|
+
/* One focus treatment for everything focusable, so no component can forget it. */
|
|
207
|
+
:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
|
|
208
|
+
/* Except where a script moved focus to a heading to announce a result (Done): the heading is not
|
|
209
|
+
a control, so a ring around it says "press me" to nobody. */
|
|
210
|
+
h1[tabindex="-1"]:focus-visible, h2[tabindex="-1"]:focus-visible { outline: none; }
|
|
211
|
+
::selection { background-color: var(--primary-5); color: var(--foreground); }
|
|
212
|
+
a { text-underline-offset: 0.2em; }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
@media (prefers-reduced-motion: reduce) {
|
|
216
|
+
*, *::before, *::after {
|
|
217
|
+
animation-duration: 0.01ms !important;
|
|
218
|
+
animation-iteration-count: 1 !important;
|
|
219
|
+
transition-duration: 0.01ms !important;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/* The built components, so their classes are generated. */
|
|
224
|
+
@source "./*.js";
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as toast, n as createQueryClient, s as StrataToastRegion, t as StrataQueryProvider } from "./query-
|
|
1
|
+
import { c as toast, n as createQueryClient, s as StrataToastRegion, t as StrataQueryProvider } from "./query-B934ufsW.js";
|
|
2
2
|
import { r as ThemeProvider } from "./theme-DVaIxyNn.js";
|
|
3
3
|
import "react";
|
|
4
4
|
import { jsx, jsxs } from "react/jsx-runtime";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "strata-react",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.41",
|
|
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",
|
|
@@ -38,6 +38,10 @@
|
|
|
38
38
|
"style": "./dist/strata.css",
|
|
39
39
|
"default": "./dist/strata.css"
|
|
40
40
|
},
|
|
41
|
+
"./strata.migrate.css": {
|
|
42
|
+
"style": "./dist/strata.migrate.css",
|
|
43
|
+
"default": "./dist/strata.migrate.css"
|
|
44
|
+
},
|
|
41
45
|
"./package.json": "./package.json",
|
|
42
46
|
"./hls": {
|
|
43
47
|
"types": "./dist/hls/index.d.ts",
|
|
@@ -179,6 +183,7 @@
|
|
|
179
183
|
]
|
|
180
184
|
},
|
|
181
185
|
"bin": {
|
|
182
|
-
"strata-visual": "./bin/strata-visual.js"
|
|
186
|
+
"strata-visual": "./bin/strata-visual.js",
|
|
187
|
+
"strata-stock-classes": "./bin/strata-stock-classes.js"
|
|
183
188
|
}
|
|
184
189
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-D163gXXZ.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.tsx"],"sourcesContent":["// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","import { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n/** The one place toasts appear. Render it once at the app root. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\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, Stale } from \"../components/data-view\";\nimport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody };\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/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\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/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(input: string | URL, init?: RequestInit, { readError = readErrorBody }: FetchJsonOptions = {}): 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) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { useInfiniteLoad, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, type Job, type JobOptions } from \"./job\";\n"],"mappings":";;;;;;;;AAGA,IAAa,iBACX;;ACkCF,IAAM,QAAQ,IAAIA,oBAA8B,EAAE,kBAAkB,EAAE,CAAC;;AAGvE,SAAgB,aAAa,S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