@slotform/react-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +44 -2
  3. package/dist/density.d.ts +4 -0
  4. package/dist/density.d.ts.map +1 -0
  5. package/dist/density.js +8 -0
  6. package/dist/density.js.map +1 -0
  7. package/dist/index.d.ts +400 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +388 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/node/canvas.d.ts +3 -0
  12. package/dist/node/canvas.d.ts.map +1 -0
  13. package/dist/node/canvas.js +13 -0
  14. package/dist/node/canvas.js.map +1 -0
  15. package/dist/node/codegen.d.ts +6 -0
  16. package/dist/node/codegen.d.ts.map +1 -0
  17. package/dist/node/codegen.js +70 -0
  18. package/dist/node/codegen.js.map +1 -0
  19. package/dist/node/css-escape.d.ts +8 -0
  20. package/dist/node/css-escape.d.ts.map +1 -0
  21. package/dist/node/css-escape.js +12 -0
  22. package/dist/node/css-escape.js.map +1 -0
  23. package/dist/node/fonts.d.ts +6 -0
  24. package/dist/node/fonts.d.ts.map +1 -0
  25. package/dist/node/fonts.js +219 -0
  26. package/dist/node/fonts.js.map +1 -0
  27. package/dist/node/lint.d.ts +3 -0
  28. package/dist/node/lint.d.ts.map +1 -0
  29. package/dist/node/lint.js +23 -0
  30. package/dist/node/lint.js.map +1 -0
  31. package/dist/node/mode.d.ts +9 -0
  32. package/dist/node/mode.d.ts.map +1 -0
  33. package/dist/node/mode.js +38 -0
  34. package/dist/node/mode.js.map +1 -0
  35. package/dist/node/theme.d.ts +13 -0
  36. package/dist/node/theme.d.ts.map +1 -0
  37. package/dist/node/theme.js +160 -0
  38. package/dist/node/theme.js.map +1 -0
  39. package/dist/types.d.ts +250 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +80 -0
  42. package/dist/types.js.map +1 -0
  43. package/guide/acts.md +61 -0
  44. package/guide/audio.md +77 -0
  45. package/guide/blocks.md +82 -0
  46. package/guide/canvas-choosing.md +34 -0
  47. package/guide/canvas-editing.md +36 -0
  48. package/guide/canvas-layout.md +46 -0
  49. package/guide/canvas-opening.md +47 -0
  50. package/guide/canvas-overview.md +24 -0
  51. package/guide/canvas-states.md +37 -0
  52. package/guide/canvas-view.md +46 -0
  53. package/guide/canvas.md +94 -0
  54. package/guide/containers.md +60 -0
  55. package/guide/content.md +40 -0
  56. package/guide/controls.md +89 -0
  57. package/guide/density.md +48 -0
  58. package/guide/dock.md +42 -0
  59. package/guide/drag.md +38 -0
  60. package/guide/figures.md +25 -0
  61. package/guide/forms.md +82 -0
  62. package/guide/pane-bar.md +11 -0
  63. package/guide/pane.md +50 -0
  64. package/guide/reference.md +74 -0
  65. package/guide/rules.md +109 -0
  66. package/guide/section.md +29 -0
  67. package/guide/shell.md +26 -0
  68. package/guide/shots.md +37 -0
  69. package/guide/sidebar.md +30 -0
  70. package/guide/table.md +119 -0
  71. package/lint/no-arbitrary-value.grit +9 -0
  72. package/lint/no-class-on-component.grit +12 -0
  73. package/lint/no-density.grit +8 -0
  74. package/lint/no-host-look.grit +38 -0
  75. package/lint/no-img.grit +10 -0
  76. package/lint/no-navigate-act.grit +22 -0
  77. package/lint/no-raw-style.grit +8 -0
  78. package/package.json +150 -3
  79. package/src/density.ts +9 -0
  80. package/src/index.ts +503 -0
  81. package/src/node/canvas.ts +14 -0
  82. package/src/node/codegen.ts +100 -0
  83. package/src/node/css-escape.ts +27 -0
  84. package/src/node/fonts.ts +260 -0
  85. package/src/node/lint.ts +25 -0
  86. package/src/node/mode.ts +64 -0
  87. package/src/node/theme.ts +232 -0
  88. package/src/types.ts +120 -0
  89. package/src/ui/atoms/avatar/base.tsx +42 -0
  90. package/src/ui/atoms/button/glyph.tsx +244 -0
  91. package/src/ui/atoms/button/link.tsx +81 -0
  92. package/src/ui/atoms/button/look.ts +32 -0
  93. package/src/ui/atoms/button/reason.tsx +69 -0
  94. package/src/ui/atoms/chip/base.tsx +85 -0
  95. package/src/ui/atoms/count/base.tsx +27 -0
  96. package/src/ui/atoms/icon/index.tsx +51 -0
  97. package/src/ui/atoms/message/waiting.tsx +19 -0
  98. package/src/ui/atoms/prose/painted.tsx +35 -0
  99. package/src/ui/atoms/row/badges.tsx +226 -0
  100. package/src/ui/atoms/row/leading.tsx +166 -0
  101. package/src/ui/atoms/row/lock.tsx +17 -0
  102. package/src/ui/atoms/row/marks.tsx +79 -0
  103. package/src/ui/atoms/section/card.tsx +27 -0
  104. package/src/ui/atoms/spinner/index.tsx +42 -0
  105. package/src/ui/atoms/status/base.tsx +51 -0
  106. package/src/ui/atoms/status/change.tsx +29 -0
  107. package/src/ui/atoms/status/dot.tsx +45 -0
  108. package/src/ui/atoms/switch/checkbox.tsx +121 -0
  109. package/src/ui/atoms/turn.tsx +28 -0
  110. package/src/ui/components/action-bar/base.tsx +276 -0
  111. package/src/ui/components/action-bar/index.tsx +20 -0
  112. package/src/ui/components/avatar/index.tsx +21 -0
  113. package/src/ui/components/banner/index.tsx +207 -0
  114. package/src/ui/components/banner/pending.tsx +109 -0
  115. package/src/ui/components/bar-chart/index.tsx +701 -0
  116. package/src/ui/components/button/base.tsx +214 -0
  117. package/src/ui/components/button/face.tsx +84 -0
  118. package/src/ui/components/button/index.tsx +206 -0
  119. package/src/ui/components/canvas/connection.tsx +26 -0
  120. package/src/ui/components/canvas/edges.tsx +116 -0
  121. package/src/ui/components/canvas/elk.ts +260 -0
  122. package/src/ui/components/canvas/floor.ts +173 -0
  123. package/src/ui/components/canvas/geometry.ts +772 -0
  124. package/src/ui/components/canvas/ground.tsx +97 -0
  125. package/src/ui/components/canvas/group.tsx +156 -0
  126. package/src/ui/components/canvas/hit.ts +40 -0
  127. package/src/ui/components/canvas/index.tsx +497 -0
  128. package/src/ui/components/canvas/label.tsx +53 -0
  129. package/src/ui/components/canvas/layout.ts +543 -0
  130. package/src/ui/components/canvas/lift.ts +272 -0
  131. package/src/ui/components/canvas/look.ts +129 -0
  132. package/src/ui/components/canvas/node.tsx +689 -0
  133. package/src/ui/components/canvas/open.ts +243 -0
  134. package/src/ui/components/canvas/opening.ts +240 -0
  135. package/src/ui/components/canvas/view.ts +621 -0
  136. package/src/ui/components/canvas/viewport.ts +417 -0
  137. package/src/ui/components/canvas/zoom.tsx +113 -0
  138. package/src/ui/components/card/index.tsx +20 -0
  139. package/src/ui/components/chip/index.tsx +24 -0
  140. package/src/ui/components/code/frame.ts +2 -0
  141. package/src/ui/components/code/index.tsx +234 -0
  142. package/src/ui/components/columns/index.tsx +51 -0
  143. package/src/ui/components/count/index.tsx +17 -0
  144. package/src/ui/components/diff/index.tsx +249 -0
  145. package/src/ui/components/diff/word.tsx +104 -0
  146. package/src/ui/components/dock/index.tsx +262 -0
  147. package/src/ui/components/file-row/index.tsx +213 -0
  148. package/src/ui/components/form/base.tsx +280 -0
  149. package/src/ui/components/form/derive.tsx +269 -0
  150. package/src/ui/components/form/index.tsx +49 -0
  151. package/src/ui/components/form/saved.tsx +39 -0
  152. package/src/ui/components/form-field/index.tsx +658 -0
  153. package/src/ui/components/gallery/index.tsx +83 -0
  154. package/src/ui/components/gate/index.tsx +183 -0
  155. package/src/ui/components/image/base.tsx +245 -0
  156. package/src/ui/components/image/index.tsx +58 -0
  157. package/src/ui/components/input/base.tsx +246 -0
  158. package/src/ui/components/input/code.tsx +108 -0
  159. package/src/ui/components/input/drop.ts +37 -0
  160. package/src/ui/components/input/file.tsx +154 -0
  161. package/src/ui/components/input/index.tsx +132 -0
  162. package/src/ui/components/input/prose.tsx +107 -0
  163. package/src/ui/components/input/refusal.tsx +30 -0
  164. package/src/ui/components/item-header/base.tsx +410 -0
  165. package/src/ui/components/menu/base.tsx +319 -0
  166. package/src/ui/components/message/attachments.tsx +101 -0
  167. package/src/ui/components/message/base.tsx +266 -0
  168. package/src/ui/components/message-input/index.tsx +377 -0
  169. package/src/ui/components/missing/base.tsx +45 -0
  170. package/src/ui/components/pane/head.tsx +399 -0
  171. package/src/ui/components/pane/index.tsx +325 -0
  172. package/src/ui/components/picker/base.tsx +1551 -0
  173. package/src/ui/components/picker/index.tsx +224 -0
  174. package/src/ui/components/picker/list.tsx +423 -0
  175. package/src/ui/components/picker/segments.tsx +183 -0
  176. package/src/ui/components/prose/index.tsx +259 -0
  177. package/src/ui/components/qr-code/index.tsx +65 -0
  178. package/src/ui/components/row/acts.tsx +126 -0
  179. package/src/ui/components/row/fact.tsx +54 -0
  180. package/src/ui/components/row/index.tsx +1370 -0
  181. package/src/ui/components/row/progress.tsx +38 -0
  182. package/src/ui/components/row/status.tsx +54 -0
  183. package/src/ui/components/row/title.ts +7 -0
  184. package/src/ui/components/rules/index.tsx +290 -0
  185. package/src/ui/components/section/band.tsx +39 -0
  186. package/src/ui/components/section/head.tsx +267 -0
  187. package/src/ui/components/section/index.tsx +409 -0
  188. package/src/ui/components/section/rows.tsx +356 -0
  189. package/src/ui/components/sheet/base.tsx +272 -0
  190. package/src/ui/components/sheet/confirm.tsx +79 -0
  191. package/src/ui/components/sheet/docked.tsx +218 -0
  192. package/src/ui/components/sheet/form.tsx +76 -0
  193. package/src/ui/components/sheet/head.tsx +120 -0
  194. package/src/ui/components/sheet/index.tsx +45 -0
  195. package/src/ui/components/sheet/layer.tsx +168 -0
  196. package/src/ui/components/sheet/outlet.tsx +58 -0
  197. package/src/ui/components/sheet/task.tsx +41 -0
  198. package/src/ui/components/shell/cut.tsx +116 -0
  199. package/src/ui/components/shell/drag.tsx +45 -0
  200. package/src/ui/components/shell/host.tsx +71 -0
  201. package/src/ui/components/shell/index.tsx +737 -0
  202. package/src/ui/components/shell/panes.tsx +76 -0
  203. package/src/ui/components/shell/preview.ts +230 -0
  204. package/src/ui/components/shell/rail.tsx +163 -0
  205. package/src/ui/components/shell/row.ts +11 -0
  206. package/src/ui/components/shell/switcher.tsx +143 -0
  207. package/src/ui/components/shell/tree.tsx +252 -0
  208. package/src/ui/components/slider/base.tsx +139 -0
  209. package/src/ui/components/slider/index.tsx +57 -0
  210. package/src/ui/components/stages/index.tsx +198 -0
  211. package/src/ui/components/stats/count-links.tsx +47 -0
  212. package/src/ui/components/stats/index.tsx +203 -0
  213. package/src/ui/components/stats/meter.tsx +213 -0
  214. package/src/ui/components/stats/parts.ts +10 -0
  215. package/src/ui/components/step-count/index.tsx +45 -0
  216. package/src/ui/components/switch/base.tsx +86 -0
  217. package/src/ui/components/switch/index.tsx +38 -0
  218. package/src/ui/components/table/columns.tsx +131 -0
  219. package/src/ui/components/table/index.tsx +2215 -0
  220. package/src/ui/components/text/index.tsx +37 -0
  221. package/src/ui/components/thread/index.tsx +503 -0
  222. package/src/ui/components/thread/latest.tsx +59 -0
  223. package/src/ui/components/toast/index.tsx +113 -0
  224. package/src/ui/components/toast/layer.tsx +26 -0
  225. package/src/ui/components/toolbar/filters.tsx +161 -0
  226. package/src/ui/components/toolbar/index.tsx +125 -0
  227. package/src/ui/components/waveform/index.tsx +205 -0
  228. package/src/ui/globals.css +427 -0
  229. package/src/ui/lib/act.ts +60 -0
  230. package/src/ui/lib/age.ts +49 -0
  231. package/src/ui/lib/bound.ts +16 -0
  232. package/src/ui/lib/canvas-layout.ts +11 -0
  233. package/src/ui/lib/caret.ts +9 -0
  234. package/src/ui/lib/chip-lines.ts +3 -0
  235. package/src/ui/lib/closed.ts +8 -0
  236. package/src/ui/lib/code.tsx +184 -0
  237. package/src/ui/lib/columns.ts +39 -0
  238. package/src/ui/lib/commit.ts +24 -0
  239. package/src/ui/lib/container.ts +112 -0
  240. package/src/ui/lib/copy.ts +29 -0
  241. package/src/ui/lib/drag.ts +575 -0
  242. package/src/ui/lib/empty.tsx +85 -0
  243. package/src/ui/lib/field.ts +39 -0
  244. package/src/ui/lib/focus.ts +175 -0
  245. package/src/ui/lib/folds.ts +67 -0
  246. package/src/ui/lib/follow.ts +220 -0
  247. package/src/ui/lib/form.ts +19 -0
  248. package/src/ui/lib/guards.ts +38 -0
  249. package/src/ui/lib/heading.ts +14 -0
  250. package/src/ui/lib/ink.ts +26 -0
  251. package/src/ui/lib/lang.ts +7 -0
  252. package/src/ui/lib/leave.ts +14 -0
  253. package/src/ui/lib/lockup.tsx +145 -0
  254. package/src/ui/lib/measure.ts +22 -0
  255. package/src/ui/lib/media.ts +63 -0
  256. package/src/ui/lib/modality.ts +69 -0
  257. package/src/ui/lib/moment.ts +13 -0
  258. package/src/ui/lib/more.tsx +76 -0
  259. package/src/ui/lib/navigate.ts +210 -0
  260. package/src/ui/lib/noop.ts +3 -0
  261. package/src/ui/lib/not-found.tsx +40 -0
  262. package/src/ui/lib/paint.tsx +55 -0
  263. package/src/ui/lib/parts-line.tsx +54 -0
  264. package/src/ui/lib/picked.ts +18 -0
  265. package/src/ui/lib/player-store.ts +38 -0
  266. package/src/ui/lib/player.ts +139 -0
  267. package/src/ui/lib/portal.ts +12 -0
  268. package/src/ui/lib/read.tsx +269 -0
  269. package/src/ui/lib/region.tsx +49 -0
  270. package/src/ui/lib/reorder.ts +154 -0
  271. package/src/ui/lib/rest.ts +16 -0
  272. package/src/ui/lib/saved.ts +29 -0
  273. package/src/ui/lib/scramble.tsx +147 -0
  274. package/src/ui/lib/scrolls.ts +70 -0
  275. package/src/ui/lib/style.ts +6 -0
  276. package/src/ui/lib/swap.tsx +107 -0
  277. package/src/ui/lib/toast.ts +39 -0
  278. package/src/ui/lib/walk-classes.ts +16 -0
  279. package/src/ui/lib/window.tsx +376 -0
  280. package/src/ui/worker.d.ts +4 -0
@@ -0,0 +1,260 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { basename } from "node:path";
4
+ import { fallbackFace } from "@slotform/ui-core/tokens";
5
+ import type { Plugin, ResolvedConfig, Rolldown } from "vite";
6
+ import type { FontEntry } from "../types.ts";
7
+ import { cssString, cssTokenValue, cssUrl } from "./css-escape.ts";
8
+
9
+ export type { FontEntry };
10
+
11
+ // IBM Plex Sans's variable files on their weight axis, upright and italic.
12
+ // The fallback metrics size Arial to Plex Sans's box (ascender 1025 and
13
+ // descender 275 over a 1000 em, at the ratio of Plex Sans's average width
14
+ // 451/1000 to Arial's 913/2048), so the swap moves nothing. A family declares
15
+ // one fallback face, so the italic carries the upright's metrics.
16
+ const plexSansFallback: FontEntry["fallback"] = {
17
+ family: "Arial",
18
+ ascentOverride: "101.32%",
19
+ descentOverride: "27.18%",
20
+ lineGapOverride: "0%",
21
+ sizeAdjust: "101.17%",
22
+ };
23
+
24
+ const plexSans: FontEntry = {
25
+ family: "IBM Plex Sans",
26
+ specifier:
27
+ "@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-normal.woff2",
28
+ weight: "100 700",
29
+ style: "normal",
30
+ fallback: plexSansFallback,
31
+ };
32
+
33
+ const plexSansItalic: FontEntry = {
34
+ family: "IBM Plex Sans",
35
+ specifier:
36
+ "@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-italic.woff2",
37
+ weight: "100 700",
38
+ style: "italic",
39
+ fallback: plexSansFallback,
40
+ };
41
+
42
+ // IBM Plex Mono ships static cuts only: 400 for code, 500 for emphasis inside
43
+ // it, 600 for the one-time-code digit. The fallback metrics size Courier New
44
+ // to Plex Mono's box (ascender 1025 and descender 275 over a 1000 em, at the
45
+ // ratio of its 600/1000 advance to Courier New's 1229/2048).
46
+ function plexMono(weight: "400" | "500" | "600"): FontEntry {
47
+ return {
48
+ family: "IBM Plex Mono",
49
+ specifier: `@fontsource/ibm-plex-mono/files/ibm-plex-mono-latin-${weight}-normal.woff2`,
50
+ weight,
51
+ style: "normal",
52
+ fallback: {
53
+ family: "Courier New",
54
+ ascentOverride: "102.52%",
55
+ descentOverride: "27.5%",
56
+ lineGapOverride: "0%",
57
+ sizeAdjust: "99.98%",
58
+ },
59
+ };
60
+ }
61
+
62
+ export const defaultFonts: FontEntry[] = [
63
+ plexSans,
64
+ plexSansItalic,
65
+ plexMono("400"),
66
+ plexMono("500"),
67
+ plexMono("600"),
68
+ ];
69
+
70
+ class MissingFontError extends Error {
71
+ constructor(font: FontEntry, cause: unknown) {
72
+ const detail = cause instanceof Error ? cause.message : String(cause);
73
+ super(
74
+ `[react-ui] could not resolve font specifier ${JSON.stringify(
75
+ font.specifier,
76
+ )} for family ${JSON.stringify(font.family)}.\n` +
77
+ " - Ensure the package providing the font file is installed in your workspace.\n" +
78
+ " - Check the specifier path is correct (typos, wrong `files/` subpath, missing weight).\n" +
79
+ ` - Underlying resolver error: ${detail}`,
80
+ );
81
+ this.name = "MissingFontError";
82
+ }
83
+ }
84
+
85
+ function resolveFontAbs(font: FontEntry): string {
86
+ try {
87
+ const require = createRequire(import.meta.url);
88
+ return require.resolve(font.specifier);
89
+ } catch (err) {
90
+ throw new MissingFontError(font, err);
91
+ }
92
+ }
93
+
94
+ function joinBase(base: string, path: string): string {
95
+ const b = base.endsWith("/") ? base : `${base}/`;
96
+ const p = path.startsWith("/") ? path.slice(1) : path;
97
+ return `${b}${p}`;
98
+ }
99
+
100
+ function findBundleUrl(
101
+ bundle: Rolldown.OutputBundle,
102
+ base: string,
103
+ fontAbs: string,
104
+ ): string | null {
105
+ const target = basename(fontAbs);
106
+ for (const entry of Object.values(bundle)) {
107
+ if (entry.type !== "asset") continue;
108
+ if (entry.originalFileNames.some((n) => n.endsWith(target))) {
109
+ return joinBase(base, entry.fileName);
110
+ }
111
+ if (entry.fileName.endsWith(`/${target}`) || entry.fileName === target) {
112
+ return joinBase(base, entry.fileName);
113
+ }
114
+ }
115
+ return null;
116
+ }
117
+
118
+ // The system fonts a metric fallback may stand on: the named font, then the
119
+ // metric-compatible cuts a machine without it carries (Liberation and its
120
+ // ChromeOS twins Arimo and Cousine share Arial's and Courier New's advances),
121
+ // so the fallback face resolves on Linux as well.
122
+ const compatible: Record<string, string[]> = {
123
+ Arial: ["Arial", "Liberation Sans", "Arimo", "Helvetica"],
124
+ "Courier New": ["Courier New", "Liberation Mono", "Cousine"],
125
+ };
126
+
127
+ function localSources(family: string): string {
128
+ return (compatible[family] ?? [family])
129
+ .map((name) => `local(${cssString(name)})`)
130
+ .join(", ");
131
+ }
132
+
133
+ function buildFontFaceCss(
134
+ fonts: Array<{ font: FontEntry; href: string }>,
135
+ ): string {
136
+ const blocks: string[] = [];
137
+ // A family's static cuts share one metric fallback face.
138
+ const fallbacks = new Set<string>();
139
+ for (const { font, href } of fonts) {
140
+ // Every consumer-supplied value crosses the CSS escape boundary: docs/architecture/codegen.md, "CSS escape boundary".
141
+ blocks.push(`@font-face {
142
+ font-family: ${cssString(font.family)};
143
+ src: ${cssUrl(href)} format("woff2");
144
+ font-weight: ${cssTokenValue(font.weight)};
145
+ font-style: ${font.style};
146
+ font-display: swap;
147
+ }`);
148
+ if (fallbacks.has(font.family)) continue;
149
+ fallbacks.add(font.family);
150
+ blocks.push(`@font-face {
151
+ font-family: ${cssString(fallbackFace(font.family))};
152
+ src: ${localSources(font.fallback.family)};
153
+ ascent-override: ${cssTokenValue(font.fallback.ascentOverride)};
154
+ descent-override: ${cssTokenValue(font.fallback.descentOverride)};
155
+ line-gap-override: ${cssTokenValue(font.fallback.lineGapOverride)};
156
+ size-adjust: ${cssTokenValue(font.fallback.sizeAdjust)};
157
+ }`);
158
+ }
159
+ return blocks.join("\n");
160
+ }
161
+
162
+ // The fonts argument is required: docs/architecture/plugins/react-ui.md, "Fonts".
163
+ export function themeFontsPlugin(fonts: FontEntry[]): Plugin {
164
+ let config: ResolvedConfig;
165
+
166
+ return {
167
+ name: "fcalell:theme-fonts",
168
+
169
+ configResolved(c) {
170
+ config = c;
171
+ },
172
+
173
+ // Nothing in the module graph imports the woff2 files — the
174
+ // @font-face CSS is injected as a raw <style> tag in
175
+ // transformIndexHtml below, not through an `import` Rolldown can trace
176
+ // — so a build never bundles them on its own. Emit each configured
177
+ // font as a build asset explicitly; transformIndexHtml then finds it
178
+ // in `ctx.bundle` by original filename (`findBundleUrl`).
179
+ // `transformIndexHtml`'s hook `this` is only a
180
+ // `MinimalPluginContext` (no `emitFile`/`getFileName`), so the
181
+ // emission has to happen in a real build hook like this one.
182
+ buildStart() {
183
+ if (config.command !== "build") return;
184
+ for (const font of fonts) {
185
+ const abs = resolveFontAbs(font);
186
+ this.emitFile({
187
+ type: "asset",
188
+ name: basename(abs),
189
+ originalFileName: abs,
190
+ source: readFileSync(abs),
191
+ });
192
+ }
193
+ },
194
+
195
+ transformIndexHtml: {
196
+ order: "post",
197
+ handler(_html, ctx) {
198
+ const tags: Array<{
199
+ tag: string;
200
+ injectTo: "head" | "head-prepend";
201
+ attrs?: Record<string, string | boolean>;
202
+ children?: string;
203
+ }> = [];
204
+
205
+ const resolved: Array<{ font: FontEntry; href: string }> = [];
206
+
207
+ for (const font of fonts) {
208
+ // Throws MissingFontError with an actionable message if the
209
+ // consumer's specifier is bogus. Better to surface that at
210
+ // build time than to emit CSS pointing at a missing woff2.
211
+ const abs = resolveFontAbs(font);
212
+ let href: string;
213
+ if (config.command === "build" && ctx.bundle) {
214
+ const fromBundle = findBundleUrl(ctx.bundle, config.base, abs);
215
+ if (!fromBundle) {
216
+ // `buildStart` above emits every configured font before
217
+ // this hook runs, so this branch is an internal
218
+ // invariant violation (e.g. another plugin stripped the
219
+ // asset from the bundle), not an author-land mistake.
220
+ throw new Error(
221
+ `[react-ui] internal error: resolved ${JSON.stringify(
222
+ font.specifier,
223
+ )} for family ${JSON.stringify(font.family)}, ` +
224
+ "but it was not found in the emitted bundle even though " +
225
+ "buildStart emits it as an asset. This should not happen — " +
226
+ "please report a bug.",
227
+ );
228
+ }
229
+ href = fromBundle;
230
+ } else {
231
+ href = `/@fs/${abs}`;
232
+ }
233
+ resolved.push({ font, href });
234
+
235
+ tags.push({
236
+ tag: "link",
237
+ injectTo: "head",
238
+ attrs: {
239
+ rel: "preload",
240
+ as: "font",
241
+ type: "font/woff2",
242
+ href,
243
+ crossorigin: "",
244
+ },
245
+ });
246
+ }
247
+
248
+ if (resolved.length > 0) {
249
+ tags.push({
250
+ tag: "style",
251
+ injectTo: "head",
252
+ children: buildFontFaceCss(resolved),
253
+ });
254
+ }
255
+
256
+ return tags;
257
+ },
258
+ },
259
+ };
260
+ }
@@ -0,0 +1,25 @@
1
+ import { posix } from "node:path";
2
+ import type { LintPlugin } from "@slotform/cli/specs";
3
+ import { APP_SOURCE_DIR } from "./codegen.ts";
4
+
5
+ // The `.grit` files of this package's `lint/`, each a rule of the web rules page
6
+ // (`guide/rules.md`); a file's header states what it forbids.
7
+ const LINT_RULES = [
8
+ "no-class-on-component",
9
+ "no-host-look",
10
+ "no-arbitrary-value",
11
+ "no-raw-style",
12
+ "no-img",
13
+ "no-density",
14
+ "no-navigate-act",
15
+ ] as const;
16
+
17
+ // The rules run on the app's own sources: docs/architecture/plugins/react-ui.md, "Lint rules".
18
+ export function lintPlugins(routesDir: string | null): LintPlugin[] {
19
+ const appDir = routesDir === null ? APP_SOURCE_DIR : posix.dirname(routesDir);
20
+ const includes = [appDir === "." ? "**" : `${appDir}/**`];
21
+ return LINT_RULES.map((rule) => ({
22
+ path: `@slotform/react-ui/lint/${rule}.grit`,
23
+ includes,
24
+ }));
25
+ }
@@ -0,0 +1,64 @@
1
+ import {
2
+ LOADING_REGIONS,
3
+ type LoadingPaint,
4
+ type LoadingRegion,
5
+ } from "@slotform/ui-core/tokens";
6
+ import { scriptHash } from "@slotform/vite/csp";
7
+ import type { Plugin } from "vite";
8
+
9
+ type Mode = "light" | "dark";
10
+
11
+ // The glyph regions a theme paints by the scramble, by region (`theme.loading`;
12
+ // a region left out pulses).
13
+ type Loading = Partial<Record<LoadingRegion, LoadingPaint>>;
14
+
15
+ // The mode before first paint: docs/architecture/plugins/react-ui.md, "Mode script and CSP".
16
+ export function modeScript(
17
+ defaultMode: Mode | undefined,
18
+ loading: Loading = {},
19
+ ): string {
20
+ const fallback = defaultMode
21
+ ? JSON.stringify(defaultMode)
22
+ : "matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'";
23
+ const follow = defaultMode
24
+ ? ""
25
+ : "try{var q=matchMedia('(prefers-color-scheme: dark)');q.addEventListener('change',function(e){var s;try{s=localStorage.getItem('theme')}catch(x){}if(s!=='light'&&s!=='dark')document.documentElement.classList.toggle('dark',e.matches);});}catch(e){}";
26
+ return `(function(){${loadingScript(loading)}try{var t;try{t=localStorage.getItem('theme')}catch(e){}if(t!=='light'&&t!=='dark')t=${fallback};if(t==='dark')document.documentElement.classList.add('dark');}catch(e){}${follow}})();`;
27
+ }
28
+
29
+ // The paint each glyph region waits in: docs/architecture/plugins/react-ui.md, "Mode script and CSP".
30
+ function loadingScript(loading: Loading): string {
31
+ return LOADING_REGIONS.filter((region) => loading[region] === "scramble")
32
+ .map(
33
+ (region) =>
34
+ `document.documentElement.dataset.loading${region[0]?.toUpperCase()}${region.slice(1)}='scramble';`,
35
+ )
36
+ .join("");
37
+ }
38
+
39
+ // The CSP that lets the page run `modeScript`: docs/architecture/plugins/react-ui.md, "Mode script and CSP".
40
+ export function modeScriptPolicy(
41
+ defaultMode: Mode | undefined,
42
+ loading: Loading = {},
43
+ ): string {
44
+ return `script-src 'self' ${scriptHash(modeScript(defaultMode, loading))}`;
45
+ }
46
+
47
+ export function themeModePlugin(
48
+ defaultMode?: Mode,
49
+ loading: Loading = {},
50
+ ): Plugin {
51
+ return {
52
+ name: "fcalell:theme-mode",
53
+ transformIndexHtml: {
54
+ order: "post",
55
+ handler: () => [
56
+ {
57
+ tag: "script",
58
+ injectTo: "head-prepend",
59
+ children: modeScript(defaultMode, loading),
60
+ },
61
+ ],
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,232 @@
1
+ import type { ResolvedTheme } from "@slotform/ui-core/derive";
2
+ import {
3
+ densityTokens,
4
+ modeTokens,
5
+ RAISED_GROUND_TOKENS,
6
+ reducedMotionTokens,
7
+ roomScope,
8
+ rootTokens,
9
+ SOFT_GROUND_TOKENS,
10
+ shadowUtilities,
11
+ themeTokens,
12
+ } from "@slotform/ui-core/emit";
13
+ import {
14
+ actsStackedMax,
15
+ definitionsOneRow,
16
+ rowOneLine,
17
+ rulesOneRow,
18
+ trailWhole,
19
+ } from "@slotform/ui-core/overflow";
20
+ import {
21
+ BREAKPOINT_PX,
22
+ BREAKPOINTS,
23
+ COLOR_NAMES,
24
+ DURATIONS,
25
+ EASINGS,
26
+ LABEL_TRACKING_NAME,
27
+ MODES,
28
+ RADIUS_ROLES,
29
+ RAISED_GROUNDS,
30
+ SHADOW_ELEVATIONS,
31
+ SIZES,
32
+ SOFT_GROUNDS,
33
+ SPACING_ROLES,
34
+ TRACKED_ROLES,
35
+ TYPE_ROLES,
36
+ WIDTHS,
37
+ } from "@slotform/ui-core/tokens";
38
+ import { DESKTOP_MEDIA, ROOM_SCOPE, TOUCH_MEDIA } from "../density.ts";
39
+ import type { CssBlock, CssLayer, CssSourceInline } from "../types.ts";
40
+ import { renderMediaRule, renderRule } from "./codegen.ts";
41
+
42
+ // Web-only keyframe tokens: docs/architecture/ui-core/motion.md, "Web motion".
43
+ const WEB_ONLY: Record<string, string> = {
44
+ "--animate-content-show":
45
+ "content-show var(--transition-duration-base) var(--ease-out)",
46
+ "--animate-content-hide":
47
+ "content-hide var(--transition-duration-base) var(--ease-in)",
48
+ "--animate-spin": "spin var(--transition-duration-loop) linear infinite",
49
+ };
50
+
51
+ // The `@theme` block seeds the light palette and the touch set, then the
52
+ // web's animations.
53
+ export function themeBlock(resolved: ResolvedTheme): CssBlock {
54
+ return {
55
+ kind: "theme",
56
+ declarations: { ...themeTokens(resolved), ...WEB_ONLY },
57
+ };
58
+ }
59
+
60
+ // Every contract utility is generated: docs/architecture/plugins/react-ui.md, "Stylesheet assembly".
61
+ export function tokenSources(): CssSourceInline[] {
62
+ const set = (names: readonly string[]) => `{${names.join(",")}}`;
63
+ return [
64
+ `{bg,text,border,outline,divide}-${set(COLOR_NAMES)}`,
65
+ `{p,px,py,pt,pb,pl,pr,gap,gap-x,gap-y,w}-${set(SPACING_ROLES)}`,
66
+ `{h,w,min-h,min-w,max-w,size,p,translate-x}-${set(SIZES)}`,
67
+ `{w,min-w,max-w}-${set(WIDTHS)}`,
68
+ `{text,leading}-${set(TYPE_ROLES)}`,
69
+ `tracking-${set([...TRACKED_ROLES, LABEL_TRACKING_NAME])}`,
70
+ `rounded-${set(RADIUS_ROLES)}`,
71
+ `shadow-${set(SHADOW_ELEVATIONS)}`,
72
+ `duration-${set([...DURATIONS, "loop"])}`,
73
+ `ease-${set(EASINGS)}`,
74
+ ];
75
+ }
76
+
77
+ // `--shadow-*` is one of the reset namespaces, so the elevation ladder ships
78
+ // as custom utilities, each reading its mode's variable.
79
+ export function shadowBlocks(): CssBlock[] {
80
+ return Object.entries(shadowUtilities()).map(([name, declarations]) => ({
81
+ kind: "utility",
82
+ name,
83
+ declarations,
84
+ }));
85
+ }
86
+
87
+ // The root's own values: the hairline, the focus ring and the light shadows,
88
+ // which no utility reads and no mode scope has to be present for.
89
+ export function rootLayer(resolved: ResolvedTheme): CssLayer {
90
+ return { name: "base", content: renderRule(":root", rootTokens(resolved)) };
91
+ }
92
+
93
+ // The desktop and room sets: docs/architecture/plugins/react-ui.md, "Density".
94
+ const PINNED_DESKTOP = ':root[data-density="desktop"]';
95
+ const PINNED_TOUCH = ':root[data-density="touch"]';
96
+
97
+ export function densityLayer(resolved: ResolvedTheme): CssLayer {
98
+ const desktop = densityTokens(resolved, "desktop");
99
+ const rules = [
100
+ renderMediaRule(DESKTOP_MEDIA, renderRule(":root", desktop)),
101
+ renderMediaRule(
102
+ DESKTOP_MEDIA,
103
+ renderRule(PINNED_TOUCH, densityTokens(resolved, "touch")),
104
+ ),
105
+ renderRule(PINNED_DESKTOP, desktop),
106
+ renderRule(
107
+ ROOM_SCOPE,
108
+ roomScope(resolved.knobs.radius, resolved.knobs.size),
109
+ ),
110
+ ];
111
+ return { name: "base", content: rules.join("\n") };
112
+ }
113
+
114
+ const slot = (selector: string) => `${selector} & {\n\t@slot;\n}`;
115
+
116
+ // The `touch:` variant: docs/architecture/plugins/react-ui.md, "Density".
117
+ export function touchVariant(): CssBlock {
118
+ return {
119
+ kind: "variant",
120
+ name: "touch",
121
+ content: [
122
+ slot(PINNED_TOUCH),
123
+ slot(ROOM_SCOPE),
124
+ renderMediaRule(TOUCH_MEDIA, slot(':root:not([data-density="desktop"])')),
125
+ ].join("\n"),
126
+ };
127
+ }
128
+
129
+ // The size containers and their variants: docs/architecture/plugins/react-ui.md, "Size containers and variants".
130
+ export function pageVariants(resolved: ResolvedTheme): CssBlock[] {
131
+ const size = resolved.knobs.size;
132
+ const row: CssBlock = {
133
+ kind: "variant",
134
+ name: "row-two-line",
135
+ content: `@container row (width < ${rowOneLine(size)}px) {\n\t@slot;\n}`,
136
+ };
137
+ const rules: CssBlock = {
138
+ kind: "variant",
139
+ name: "rules-stacked",
140
+ content: `@container rules (width < ${rulesOneRow(size)}px) {\n\t@slot;\n}`,
141
+ };
142
+ const definitions: CssBlock = {
143
+ kind: "variant",
144
+ name: "definitions-stacked",
145
+ content: `@container page (width < ${definitionsOneRow(size)}px) {\n\t@slot;\n}`,
146
+ };
147
+ const trail: CssBlock = {
148
+ kind: "variant",
149
+ name: "trail-whole",
150
+ content: `@container page (width >= ${trailWhole(size)}px) {\n\t@slot;\n}`,
151
+ };
152
+ const time: CssBlock = {
153
+ kind: "variant",
154
+ name: "time-fits",
155
+ content: "@container time (width >= 1ch) {\n\t@slot;\n}",
156
+ };
157
+ const acts: CssBlock = {
158
+ kind: "variant",
159
+ name: "acts-stacked",
160
+ content: `@container acts (width <= ${actsStackedMax(size)}px) {\n\t@slot;\n}`,
161
+ };
162
+ const sized = (["page", "place"] as const).flatMap((container) =>
163
+ BREAKPOINTS.flatMap((bp): CssBlock[] => {
164
+ const px = `${BREAKPOINT_PX[bp]}px`;
165
+ return [
166
+ {
167
+ kind: "variant",
168
+ name: `${container}-${bp}`,
169
+ content: `@container ${container} (width >= ${px}) {\n\t@slot;\n}`,
170
+ },
171
+ {
172
+ kind: "variant",
173
+ name: `${container}-max-${bp}`,
174
+ content: `@container ${container} (width < ${px}) {\n\t@slot;\n}`,
175
+ },
176
+ ];
177
+ }),
178
+ );
179
+ return [...sized, row, rules, definitions, trail, time, acts];
180
+ }
181
+
182
+ // `pb-safe` keeps a bottom bar clear of the home indicator and `pt-safe` the
183
+ // top of the column clear of the notch or status bar, under `viewport-fit=cover`.
184
+ export function safeAreaUtilities(): CssBlock[] {
185
+ return [
186
+ {
187
+ kind: "utility",
188
+ name: "pb-safe",
189
+ declarations: { "padding-bottom": "env(safe-area-inset-bottom)" },
190
+ },
191
+ {
192
+ kind: "utility",
193
+ name: "pt-safe",
194
+ declarations: { "padding-top": "env(safe-area-inset-top)" },
195
+ },
196
+ ];
197
+ }
198
+
199
+ // Each mode is a class scope in `@layer base`: docs/architecture/plugins/react-ui.md, "Modes".
200
+ export function modeLayer(resolved: ResolvedTheme): CssLayer {
201
+ const rules = MODES.map((mode) =>
202
+ renderRule(`.${mode}`, {
203
+ "color-scheme": mode,
204
+ ...modeTokens(resolved, mode),
205
+ }),
206
+ );
207
+ rules.push(
208
+ renderRule(
209
+ RAISED_GROUNDS.map((ground) => `.bg-${ground}`).join(", "),
210
+ RAISED_GROUND_TOKENS,
211
+ ),
212
+ renderRule(
213
+ SOFT_GROUNDS.map((ground) => `.bg-${ground}`).join(", "),
214
+ SOFT_GROUND_TOKENS,
215
+ ),
216
+ );
217
+ return { name: "base", content: rules.join("\n") };
218
+ }
219
+
220
+ // Under reduced motion every duration rung is 0, so no transition or
221
+ // animation that reads one moves.
222
+ const REDUCED_MOTION = "(prefers-reduced-motion: reduce)";
223
+
224
+ export function motionLayer(): CssLayer {
225
+ return {
226
+ name: "base",
227
+ content: renderMediaRule(
228
+ REDUCED_MOTION,
229
+ renderRule(":root", reducedMotionTokens()),
230
+ ),
231
+ };
232
+ }
package/src/types.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { themeSchema, wordsSchema } from "@slotform/ui-core/schema";
2
+ import { z } from "zod";
3
+ import { isCssIdent, isCssSupportsExpression } from "./node/css-escape.ts";
4
+
5
+ // A CSS `@import`, shorthand or structured: docs/architecture/slot-catalog.md, "`reactUi.slots.*` (the `react-ui` plugin)".
6
+ export const cssImportSchema = z.union([
7
+ z.string().min(1, "css @import url must be a non-empty string"),
8
+ z.object({
9
+ url: z.string().min(1, "css @import url must be a non-empty string"),
10
+ layer: z
11
+ .string()
12
+ .optional()
13
+ .refine(
14
+ (v) => v === undefined || isCssIdent(v),
15
+ "css @import layer(...) argument must be a CSS <ident>",
16
+ ),
17
+ supports: z
18
+ .string()
19
+ .optional()
20
+ .refine(
21
+ (v) => v === undefined || isCssSupportsExpression(v),
22
+ "css @import supports(...) argument must be a balanced parenthesized feature query without ';' / '{' / '}'",
23
+ ),
24
+ // Tailwind v4's `source(none)`: no automatic content detection, so only
25
+ // the sheet's `@source` declarations are scanned.
26
+ source: z.literal("none").optional(),
27
+ }),
28
+ ]);
29
+
30
+ export type CssImport = z.input<typeof cssImportSchema>;
31
+
32
+ // `@layer <name>` — name must be a CSS <ident>.
33
+ export const cssLayerSchema = z.object({
34
+ name: z
35
+ .string()
36
+ .refine((v) => isCssIdent(v), "css @layer name must be a CSS <ident>"),
37
+ content: z.string(),
38
+ });
39
+
40
+ export type CssLayer = z.input<typeof cssLayerSchema>;
41
+
42
+ // A top-level `@theme`, `@utility` or `@custom-variant` block: docs/architecture/slot-catalog.md, "`reactUi.slots.*` (the `react-ui` plugin)".
43
+ const cssDeclarationsSchema = z.record(z.string(), z.string());
44
+
45
+ export const cssBlockSchema = z.discriminatedUnion("kind", [
46
+ z.object({
47
+ kind: z.literal("theme"),
48
+ declarations: cssDeclarationsSchema,
49
+ }),
50
+ z.object({
51
+ kind: z.literal("utility"),
52
+ // Validated at the render boundary by `cssIdent`, so a malformed name
53
+ // throws an error that names the contributing plugin.
54
+ name: z.string(),
55
+ declarations: cssDeclarationsSchema,
56
+ }),
57
+ z.object({
58
+ kind: z.literal("variant"),
59
+ name: z.string(),
60
+ content: z.string(),
61
+ }),
62
+ ]);
63
+
64
+ export type CssBlock = z.input<typeof cssBlockSchema>;
65
+
66
+ // An `@source inline` pattern: docs/architecture/slot-catalog.md, "`reactUi.slots.*` (the `react-ui` plugin)".
67
+ export const cssSourceInlineSchema = z
68
+ .string()
69
+ .regex(
70
+ /^[a-z0-9{},.:-]+$/,
71
+ "css @source inline(...) pattern must be class characters and braces",
72
+ );
73
+
74
+ export type CssSourceInline = z.input<typeof cssSourceInlineSchema>;
75
+
76
+ // The inputs of `.slotform/app.css`: docs/architecture/slot-catalog.md, "`reactUi.slots.*` (the `react-ui` plugin)".
77
+ export interface CodegenAppCssPayload {
78
+ imports: CssImport[];
79
+ sources: CssSourceInline[];
80
+ blocks: CssBlock[];
81
+ layers: CssLayer[];
82
+ }
83
+
84
+ // A webfont file: docs/architecture/plugins/react-ui.md, "Fonts".
85
+ const fontEntrySchema = z.object({
86
+ // CSS family name used in `font-family` declarations (e.g. "IBM Plex Sans").
87
+ family: z.string(),
88
+ // Node module path or workspace-relative path to the actual woff2 file
89
+ // (e.g. "@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-normal.woff2").
90
+ specifier: z.string(),
91
+ // A single weight ("400") or a variable-font range ("100 900").
92
+ weight: z.string(),
93
+ style: z.enum(["normal", "italic"]),
94
+ // Fallback-font metrics used to generate a sibling `@font-face` that
95
+ // matches the webfont's metrics on top of a system family. Prevents CLS
96
+ // while the woff2 loads.
97
+ fallback: z.object({
98
+ family: z.string(),
99
+ ascentOverride: z.string(),
100
+ descentOverride: z.string(),
101
+ lineGapOverride: z.string(),
102
+ sizeAdjust: z.string(),
103
+ }),
104
+ });
105
+
106
+ export type FontEntry = z.infer<typeof fontEntrySchema>;
107
+
108
+ // The options: plugins/react-ui/guide/reference.md, "Options".
109
+ export const reactUiOptionsSchema = z.object({
110
+ fonts: z.array(fontEntrySchema).optional(),
111
+ theme: themeSchema.optional(),
112
+ words: wordsSchema.optional(),
113
+ });
114
+
115
+ export type ReactUiOptions = z.input<typeof reactUiOptionsSchema>;
116
+
117
+ // The `theme` option's own type. It is ui-core's, re-exported here so a
118
+ // consumer reaches it through the plugin it configures.
119
+ export type { Theme } from "@slotform/ui-core/schema";
120
+ export type { Words } from "@slotform/ui-core/tokens";