@typed-grid-areas/solid 0.1.1 → 0.1.3

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 (3) hide show
  1. package/README.md +90 -1343
  2. package/REFERENCE.md +1464 -0
  3. package/package.json +6 -5
package/REFERENCE.md ADDED
@@ -0,0 +1,1464 @@
1
+ # typed-grid-areas
2
+
3
+ Type-safe, declarative CSS grid layouts for components whose slots come and
4
+ go. Describe a grid once, as its areas and a few text templates, and the
5
+ library works out the layout for every combination of present slots, at
6
+ every breakpoint, as generated CSS: no `:has()` rules or layout JavaScript
7
+ of your own. Everything that names an area is checked at compile time.
8
+
9
+ Framework-free at the core (`typed-grid-areas`); each UI framework's adapter
10
+ is a package of its own. The React adapter, `@typed-grid-areas/react`,
11
+ renders a definition as typed slot components (`<Card>`, `<Card.icon>`).
12
+
13
+ [Docs](https://michaelbuss.github.io/typed-grid-areas/) ·
14
+ [Try it in your browser](https://michaelbuss.github.io/typed-grid-areas/try-it/)
15
+
16
+ This is the complete API reference, for every adapter, as of the version it
17
+ ships with: every package carries it next to its [README](README.md), the
18
+ overview.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ npm i typed-grid-areas @typed-grid-areas/react
24
+ ```
25
+
26
+ `@typed-grid-areas/react` needs `react` 19 or later. The core on its own
27
+ (`npm i typed-grid-areas`) has no framework dependency.
28
+
29
+ Moving from `typed-grid-areas/react` (0.1)? Install `@typed-grid-areas/react`
30
+ and import `createGridComponent` from it instead; nothing else changes.
31
+
32
+ ### Agent skill
33
+
34
+ The `typed-grid-areas` package ships an agent skill (in its
35
+ `skills/typed-grid-areas/`) that walks a coding agent through writing,
36
+ converting and debugging layouts, versioned with each release. Enable it in your project with
37
+ [TanStack Intent](https://tanstack.com/intent):
38
+
39
+ ```sh
40
+ npx @tanstack/intent@latest install
41
+ ```
42
+
43
+ The first run asks which packages' skills to enable, so it needs an
44
+ interactive terminal, and Intent needs Node.js 20.12 or newer.
45
+
46
+ ## At a glance
47
+
48
+ ```tsx
49
+ import { defineLayout } from "typed-grid-areas";
50
+ import { createGridComponent } from "@typed-grid-areas/react";
51
+
52
+ const Card = createGridComponent(
53
+ defineLayout({
54
+ areas: ["icon?", "information", "cardTag?"],
55
+ layouts: [
56
+ {
57
+ template: "icon information cardTag",
58
+ columns: "min-content minmax(0, 1fr) auto",
59
+ },
60
+ ],
61
+ }),
62
+ );
63
+
64
+ function Example({ tag }: { tag?: string }) {
65
+ return (
66
+ <Card className="gap-2">
67
+ <Card.icon>★</Card.icon>
68
+ <Card.information>Weekly digest</Card.information>
69
+ {tag && <Card.cardTag>{tag}</Card.cardTag>}
70
+ </Card>
71
+ );
72
+ }
73
+ ```
74
+
75
+ Without a tag, the library's derived layout for "no `cardTag`" applies:
76
+ `icon information`, with the tag's column gone. See
77
+ [the examples](#examples-preferencecard-and-id-card) for complete cards.
78
+
79
+ ## Defining a grid: `defineLayout()`
80
+
81
+ Describe a grid once: its areas, and the layouts that arrange them, drawn as
82
+ text templates. Everything that names an area is checked against `areas` at
83
+ the type level.
84
+
85
+ ```ts
86
+ import { defineLayout } from "typed-grid-areas";
87
+
88
+ const cardGrid = defineLayout({
89
+ areas: ["icon?", "information", "cardTag?"],
90
+ layouts: [
91
+ {
92
+ template: `
93
+ icon cardTag
94
+ information information`,
95
+ columns: "min-content minmax(0, 1fr)",
96
+ align: { cardTag: { justify: "end" } },
97
+ breakpoints: {
98
+ "@sm": {
99
+ template: "icon information cardTag",
100
+ columns: "min-content minmax(0, 1fr) auto",
101
+ },
102
+ },
103
+ },
104
+ { unless: ["cardTag"], template: "icon information" },
105
+ ],
106
+ });
107
+ ```
108
+
109
+ - **Areas:** a trailing `?` marks an area optional (its slot may be absent);
110
+ the area is still called `icon`.
111
+ - **Templates:** rows are separated by newlines or `/`, cells by whitespace.
112
+ `.` is an empty cell, and `base+layer` draws `layer` over `base`.
113
+ - **Track lists:** `rows` and `columns` are one CSS track list each.
114
+ Whitespace inside parentheses doesn't split a track, so
115
+ `"min-content minmax(0, 1fr)"` is two tracks.
116
+
117
+ Compile-time checks, each reported on the offending property:
118
+
119
+ - an unknown area in a cell (also inside `a+b`): `{ _unknownArea: "iconn" }`
120
+ on `template`
121
+ - rows with different cell counts:
122
+ `{ _raggedRow: { row: 2; cells: 1; expected: 2 } }` on `template`
123
+ - a track count that doesn't match the template:
124
+ `{ _columnCountError: { expected: 2; got: 3 } }` on `columns` (and
125
+ `_rowCountError` on `rows`); skipped for `repeat(` and non-literal strings
126
+ - unknown `align` keys and unknown `when`/`unless` values
127
+ - a breakpoint key that isn't allowed: `{ _unsupportedBreakpoint: "@[50%]" }`
128
+ on the key, and breakpoints in more than one unit:
129
+ `{ _mixedBreakpointUnits: "…: ch is mixed with rem" }` on every key (see
130
+ [Breakpoints](#breakpoints)); skipped for keys that aren't literals
131
+
132
+ There is no autocomplete inside a template string, and each template reports
133
+ one problem at a time.
134
+
135
+ In development, `defineLayout` also runs `validateGridConfig()` once per
136
+ definition and logs what types can't check: areas and layers that aren't
137
+ rectangles, malformed cells, and breakpoint keys that aren't allowed or
138
+ mix units (also when the keys aren't literals). `validateGridConfig()` returns those
139
+ warnings as strings, so it is also useful for definitions assembled
140
+ dynamically.
141
+
142
+ ## Optional areas and derived layouts
143
+
144
+ Mark an area optional with a `?` suffix in `areas`; everywhere else it is
145
+ named without the `?`. Every other area is required: its slot is always
146
+ expected to be rendered. Draw each layout with every area present, and the
147
+ library derives a layout for every combination of absent optional areas that
148
+ the layout uses and its condition doesn't mention:
149
+
150
+ ```ts
151
+ defineLayout({
152
+ areas: ["icon?", "information", "cardTag?", "children?"],
153
+ layouts: [
154
+ {
155
+ template: `
156
+ icon cardTag
157
+ information information
158
+ children children`,
159
+ },
160
+ ],
161
+ });
162
+ // without children: icon cardTag / information information
163
+ // without cardTag: icon / information / children
164
+ ```
165
+
166
+ A derived layout is the authored one (and each of its breakpoint
167
+ arrangements) with the absent areas taken out:
168
+
169
+ 1. A row or column is dropped, with its track size, when it held an absent
170
+ area and everything else in it is also absent or continues into a
171
+ neighbouring track (a spanning area just gets one track shorter).
172
+ 2. A hole that can't be dropped is filled by a neighbouring area (left, then
173
+ right, up, down) if that area stays a rectangle; otherwise it stays empty.
174
+ 3. Cells written as `"."` are never dropped or filled.
175
+
176
+ The generated CSS grows with the number of combinations (2ⁿ for n optional
177
+ areas in one grid), so it is deduplicated, and nesting grids keeps n small
178
+ per grid: the two-grid PreferenceCard below stays under 10 KB.
179
+
180
+ ## Overrides: `when` and `unless`
181
+
182
+ Where a derived layout isn't what you want, write an **override**: a layout
183
+ with a **condition**, declared after the layout it replaces. A condition is
184
+ `when` (areas that must be present) plus `unless` (areas that must be
185
+ absent); areas named in neither don't affect it. A layout without a
186
+ condition is a **base** layout, which always applies.
187
+
188
+ ```ts
189
+ defineLayout({
190
+ areas: ["icon?", "information", "cardTag?", "children?"],
191
+ layouts: [
192
+ {
193
+ template: `
194
+ icon cardTag
195
+ information information
196
+ children children`,
197
+ columns: "min-content minmax(0, 1fr)",
198
+ },
199
+ // The derived layout without a tag would stack icon and information in
200
+ // the min-content column; put them side by side instead.
201
+ { unless: ["cardTag"], template: "icon information / children children" },
202
+ ],
203
+ });
204
+ ```
205
+
206
+ Conditions are checked with `:has()` / `:not(:has())` on the grid's direct
207
+ children, so layouts react to which slots are actually rendered, without any
208
+ layout JavaScript. When several layouts match, the one declared **last**
209
+ wins, however many areas each one mentions. An override gets derived layouts
210
+ of its own for the optional areas its condition doesn't mention.
211
+
212
+ Every layout is self-contained: while it applies it sets the tracks, the
213
+ placement and the alignment (`justify` / `align`: `start`, `center`, `end`,
214
+ `stretch`, `baseline`) of every area, so nothing leaks in from another
215
+ matching layout:
216
+
217
+ ```ts
218
+ defineLayout({
219
+ areas: ["icon", "info", "tag"],
220
+ layouts: [
221
+ { template: "info tag", align: { tag: { justify: "end" } } },
222
+ {
223
+ when: ["icon"],
224
+ unless: ["tag"],
225
+ template: "icon info",
226
+ align: { icon: { justify: "center", align: "start" } },
227
+ },
228
+ ],
229
+ });
230
+ ```
231
+
232
+ An area a layout's template leaves out is **hidden** (`display: none
233
+ !important`) while that layout applies.
234
+
235
+ All generated CSS sits in the `typed-grid-areas` cascade layer, so your own
236
+ unlayered classes on the grid or a slot (say `justify-self`) always win. The
237
+ one exception is hiding: it is `!important`, so a `display` class on a slot
238
+ can't bring back an area the current layout leaves out
239
+ ([ADR 0003](https://github.com/MichaelBuss/typed-grid-areas/blob/main/docs/adr/0003-hidden-areas-are-important.md)).
240
+
241
+ ## Breakpoints
242
+
243
+ `breakpoints` give a layout different arrangements once the grid is given
244
+ at least a certain width. Keys are Tailwind's default `@container` sizes
245
+ (`@xs` through `@7xl`) or an arbitrary length in Tailwind's arbitrary-value
246
+ syntax (`"@[40rem]"`):
247
+
248
+ ```ts
249
+ defineLayout({
250
+ areas: ["icon", "info"],
251
+ layouts: [
252
+ {
253
+ template: "info",
254
+ breakpoints: {
255
+ "@sm": { template: "icon info" },
256
+ "@[40rem]": { template: "info icon", columns: "1fr auto" },
257
+ },
258
+ },
259
+ ],
260
+ });
261
+ ```
262
+
263
+ **Every breakpoint of a definition uses one unit**, across all its layouts,
264
+ and the named sizes count as `rem`. An arbitrary key is a plain,
265
+ non-negative number and one of `px`, `rem`, `em`, `ch`, `ex`, `vw`, `vh`,
266
+ `vi` or `vb`: `"@[27.5rem]"`, `"@[40ch]"`. The generated CSS relies on
267
+ breakpoints being ordered by width, and breakpoints in different units can't
268
+ be ordered when it's generated, because how they compare depends on font
269
+ sizes and the viewport. So `"@[20ch]"` next to `"@sm"` is a type error.
270
+ Percentages, `calc()` and container query units (`cqw`, `cqi`, …, which in
271
+ a query measure a container above the grid) aren't allowed either.
272
+
273
+ A breakpoint arrangement beats its own layout's base arrangement, but a
274
+ later layout still beats an earlier layout's breakpoints. Breakpoint
275
+ arrangements take their own `rows`, `columns` and `align`; nothing is
276
+ inherited from the layout. Derived layouts apply to each breakpoint
277
+ arrangement too.
278
+
279
+ **A breakpoint measures the space the grid itself is given**, never the
280
+ viewport or a container somewhere above it, so a grid behaves the same
281
+ wherever it's placed. A container query can't measure the element it
282
+ styles, so a grid with breakpoints renders inside its own size container: a
283
+ wrapper `div` with `container-type: inline-size` and a container name unique
284
+ to the definition, which its `@container` queries target by name (see
285
+ [ADR 0002](https://github.com/MichaelBuss/typed-grid-areas/blob/main/docs/adr/0002-grid-owns-its-size-container.md)). Grids without
286
+ breakpoints get no wrapper and are not size containers.
287
+
288
+ Inline-size containment has a cost: **a grid with breakpoints can't size to
289
+ its content.** That's fine in a `1fr`, `minmax(0, 1fr)` or stretched track,
290
+ but in an `auto` or `min-content` track of a parent grid it collapses to zero
291
+ width. A nested grid with breakpoints also switches at a wider outer width
292
+ than a flat one would, since it measures only its own area.
293
+
294
+ ## Layers: `base+layer`
295
+
296
+ A cell written `base+layer` (or `base+layer+layer…`) is owned by `base` as
297
+ usual, and also has `layer` drawn on top of it. A layer covers the bounding
298
+ rectangle of the cells it appears in and is drawn above its base, whatever
299
+ their order in the DOM. Several layers can share a host, each in its own
300
+ cells, and an area can be a layer in one layout and own cells in another:
301
+
302
+ ```ts
303
+ defineLayout({
304
+ areas: ["photo", "identity", "details", "logo?", "qr?", "badge?"],
305
+ layouts: [
306
+ {
307
+ template: `
308
+ photo+logo photo photo+badge
309
+ photo photo photo
310
+ photo+identity photo+identity photo+identity
311
+ details details qr`,
312
+ rows: "40px 80px 40px 60px",
313
+ columns: "60px 1fr 60px",
314
+ breakpoints: {
315
+ "@md": {
316
+ template: `
317
+ photo photo+badge identity logo
318
+ photo photo details qr`,
319
+ rows: "40px 120px",
320
+ columns: "100px 40px 1fr 80px",
321
+ },
322
+ },
323
+ },
324
+ ],
325
+ });
326
+ ```
327
+
328
+ On narrow cards `logo`, `badge` and `identity` sit in the photo's corners;
329
+ from `@md` the photo is a column of its own and only `badge` stays on it.
330
+ Use `align` to pin a layer within its cells.
331
+
332
+ In derived layouts, a missing optional layer just disappears from its cells:
333
+ it never leaves a hole for a neighbour to fill. A row or column is only
334
+ dropped if every layer in it also continues into a neighbouring track.
335
+
336
+ **Track sizing.** Layers sit in grid tracks, so their content takes part in
337
+ sizing those tracks just like the base's does. Give the host area's tracks
338
+ fixed or `minmax()` sizes, or a large layer can stretch the area it sits on.
339
+
340
+ ### Restyling layered content: `--tga-over`
341
+
342
+ Every layered slot gets the custom property `--tga-over`, set to the name of
343
+ the area underneath it (the one owning its top-left cell); every other slot
344
+ gets `none`. Content inside a slot can restyle itself with a container style
345
+ query, for example white text while it sits over a photo:
346
+
347
+ ```css
348
+ @container style(--tga-over: photo) {
349
+ .identity-name {
350
+ color: white;
351
+ }
352
+ }
353
+ ```
354
+
355
+ Every element is a style container, so the query reads the nearest
356
+ ancestor's value: put the rule on the slot's content, not the slot itself.
357
+
358
+ Browser support for style queries on custom properties
359
+ ([MDN browser-compat-data](https://github.com/mdn/browser-compat-data/blob/main/css/at-rules/container.json)
360
+ `css.at-rules.container.style_queries_for_custom_properties`, and
361
+ [caniuse](https://caniuse.com/css-container-queries-style), checked
362
+ 2026-10-31):
363
+
364
+ | Browser | Supported since |
365
+ | ------- | --------------- |
366
+ | Chrome | 111 |
367
+ | Safari | 18 |
368
+ | Firefox | 151 |
369
+
370
+ All on by default. Only custom-property queries are supported (which is all
371
+ `--tga-over` needs); the range syntax (`style(--x > 1)`) isn't in Safari.
372
+ The library's own tests only run in Chromium. In older browsers the query
373
+ simply never matches, so write the unlayered look as the default and the
374
+ layered look inside the query.
375
+
376
+ ## Accessibility: reading order
377
+
378
+ Each layout, and each of its breakpoints, can put the areas in a different
379
+ visual order, but keyboard focus follows the DOM: the order the slots are
380
+ rendered in. One DOM order can't match every layout.
381
+
382
+ `reading-flow` on the grid makes keyboard focus follow the layout that
383
+ currently applies instead, at every breakpoint. The library doesn't set it:
384
+ give the grid a class of your own.
385
+
386
+ ```css
387
+ .card {
388
+ reading-flow: grid-rows;
389
+ }
390
+ ```
391
+
392
+ `grid-rows` reads the grid row by row; use `grid-columns` when the design
393
+ reads down its columns first. Put the class on the grid like any other:
394
+ `className` in React, `class` (or `className`) in Preact, `class` in Vue,
395
+ Svelte, Solid and Octane and on the element carrying `[tgaGrid]` in Angular,
396
+ and the grid's `class` option in Lit. With Tailwind, the arbitrary property
397
+ `[reading-flow:grid-rows]` does the same.
398
+
399
+ - **A progressive enhancement.** Supported in Chrome and Edge 137+; other
400
+ browsers keep DOM order. So still render the slots in the order that makes
401
+ sense for the most important layout
402
+ ([WCAG 1.3.2, Meaningful Sequence](https://www.w3.org/WAI/WCAG22/Understanding/meaningful-sequence.html)),
403
+ and let `reading-flow` follow the others where it's supported.
404
+ - **Layers.** Slots are read in the order of the cell each starts in. A
405
+ layer that starts in the same cell as its base ties with it, and a tie
406
+ falls back to DOM order: render whichever of the two should be read first
407
+ earlier.
408
+ - **Not `order`.** `order` only moves auto-placed elements, and every slot
409
+ is placed by its area name, so it moves nothing. It doesn't change focus
410
+ order either.
411
+ - **Why it isn't built in.** Setting `reading-flow` in the generated CSS
412
+ would override a DOM order you chose on purpose.
413
+
414
+ What this gives you is keyboard focus that follows the layout. The CSS
415
+ specification applies `reading-flow` to the reading order passed to
416
+ assistive technology too, but it has been checked for keyboard focus in
417
+ Chromium only, not with screen readers.
418
+
419
+ ## Rendering with React: grid components
420
+
421
+ `createGridComponent(definition)` turns a definition into the component it
422
+ renders as. Create it once, at module level:
423
+
424
+ ```tsx
425
+ import { defineLayout } from "typed-grid-areas";
426
+ import { createGridComponent } from "@typed-grid-areas/react";
427
+
428
+ const Card = createGridComponent(
429
+ defineLayout({
430
+ areas: ["icon", "info"],
431
+ layouts: [{ template: "icon info", columns: "48px 1fr" }],
432
+ }),
433
+ );
434
+
435
+ function Example() {
436
+ return (
437
+ <Card className="gap-4" aria-label="Card">
438
+ <Card.icon>★</Card.icon>
439
+ <Card.info className="truncate">Information</Card.info>
440
+ </Card>
441
+ );
442
+ }
443
+ ```
444
+
445
+ - **`<Card>`** renders the grid: a `div` with the definition's
446
+ `data-grid-id`, which the generated CSS gives `display: grid` (layered, so
447
+ your own class can change it), taking `className`, `style`, `ref`,
448
+ `children` and any other `div` props. When the definition has breakpoints
449
+ the grid sits inside its own size container (a wrapper `div`); your props
450
+ still go on the grid itself.
451
+ - **`<Card.icon>`** is the slot for the `icon` area: a static component per
452
+ area, named exactly like the area, so `<Card.iconn>` is a type error. It
453
+ takes the same props and renders a `div` marked `data-area="icon"`.
454
+ Placement lives in the generated CSS, not on the slot.
455
+ - **`asChild`** (on slots and on the grid) renders your own single child
456
+ element instead of a `div`, with the props merged onto it (Radix `Slot`),
457
+ so it needs no extra wrapper:
458
+
459
+ ```tsx
460
+ import { defineLayout } from "typed-grid-areas";
461
+ import { createGridComponent } from "@typed-grid-areas/react";
462
+
463
+ const Row = createGridComponent(
464
+ defineLayout({ areas: ["input", "content"], layouts: [{ template: "input content" }] }),
465
+ );
466
+
467
+ function Example() {
468
+ return (
469
+ <Row>
470
+ <Row.input asChild>
471
+ <label htmlFor="notify">
472
+ <input id="notify" type="checkbox" />
473
+ </label>
474
+ </Row.input>
475
+ <Row.content>Notify me</Row.content>
476
+ </Row>
477
+ );
478
+ }
479
+ ```
480
+
481
+ Slots must be **direct children** of their grid (fragments and conditionals
482
+ are fine). Render an area's slot even while the current layout hides it;
483
+ leave it out only to make an optional area absent.
484
+
485
+ Grid components work with React Compiler and in Strict Mode, and the
486
+ adapter's tests run under both.
487
+
488
+ ### Nesting: `nest`
489
+
490
+ A grid can fill another grid's area. `nest` makes the area's slot the root
491
+ of the nested grid, and reaches that grid's slots through it:
492
+
493
+ ```tsx
494
+ import { defineLayout } from "typed-grid-areas";
495
+ import { createGridComponent } from "@typed-grid-areas/react";
496
+
497
+ const Content = createGridComponent(
498
+ defineLayout({ areas: ["icon?", "title"], layouts: [{ template: "icon title" }] }),
499
+ );
500
+
501
+ const Card = createGridComponent(
502
+ defineLayout({ areas: ["input?", "content"], layouts: [{ template: "input content" }] }),
503
+ { nest: { content: Content } },
504
+ );
505
+
506
+ function Example() {
507
+ return (
508
+ <Card>
509
+ <Card.content className="p-4">
510
+ <Card.content.icon>★</Card.content.icon>
511
+ <Card.content.title>Title</Card.content.title>
512
+ </Card.content>
513
+ </Card>
514
+ );
515
+ }
516
+ ```
517
+
518
+ `<Card.content>` is both the `content` slot of `Card` and the root of
519
+ `Content`. If the nested grid has breakpoints, the outer grid's area goes on
520
+ its size container, the outermost element. Nest where the design has panels
521
+ of their own (padding, background, border): it also keeps each grid's
522
+ optional areas, and so its CSS, small.
523
+
524
+ ### CSS and development warnings
525
+
526
+ Each definition's CSS goes into a `<style href precedence>` element, which
527
+ React 19 hoists into `<head>` and emits once, however many instances render.
528
+
529
+ In development (`process.env.NODE_ENV === "development"`), a grid warns on
530
+ the console when:
531
+
532
+ - a required area's slot isn't rendered, or
533
+ - it has a direct child that isn't one of its slots.
534
+
535
+ `defineLayout` also warns, once per definition, about areas and layers that
536
+ aren't rectangles.
537
+
538
+ ## Examples: PreferenceCard and ID card
539
+
540
+ **PreferenceCard:** an optional input panel (a checkbox, as a `<label>`)
541
+ beside a content panel with its own padding. The content panel is a nested
542
+ grid of an optional icon, the information, an optional tag and optional
543
+ children. With both an icon and a tag, the two share the top row above
544
+ the information on narrow cards, and from `@sm` all three share one row.
545
+ With only one of them, it sits beside the information at every width (the
546
+ second override: the derived layout without an icon would stack the tag
547
+ above the information). Children always take a full-width last row. The
548
+ library's browser acceptance tests render this design in every combination.
549
+
550
+ ```tsx
551
+ import type { ReactNode } from "react";
552
+ import { defineLayout } from "typed-grid-areas";
553
+ import { createGridComponent } from "@typed-grid-areas/react";
554
+
555
+ const PreferenceContent = createGridComponent(
556
+ defineLayout({
557
+ areas: ["icon?", "information", "cardTag?", "children?"],
558
+ layouts: [
559
+ {
560
+ template: `
561
+ icon cardTag
562
+ information information
563
+ children children`,
564
+ columns: "min-content minmax(0, 1fr)",
565
+ align: { cardTag: { justify: "end" } },
566
+ breakpoints: {
567
+ "@sm": {
568
+ template: "icon information cardTag / children children children",
569
+ columns: "min-content minmax(0, 1fr) auto",
570
+ },
571
+ },
572
+ },
573
+ { unless: ["cardTag"], template: "icon information / children children" },
574
+ {
575
+ when: ["cardTag"],
576
+ unless: ["icon"],
577
+ template: "information cardTag / children children",
578
+ columns: "minmax(0, 1fr) auto",
579
+ },
580
+ ],
581
+ }),
582
+ );
583
+
584
+ const Card = createGridComponent(
585
+ defineLayout({
586
+ areas: ["input?", "content"],
587
+ // `content` has breakpoints, so it needs a `minmax(0, 1fr)` track, not `auto`.
588
+ layouts: [{ template: "input content", columns: "auto minmax(0, 1fr)" }],
589
+ }),
590
+ { nest: { content: PreferenceContent } },
591
+ );
592
+
593
+ type PreferenceCardProps = {
594
+ input?: ReactNode;
595
+ icon?: ReactNode;
596
+ title: ReactNode;
597
+ tag?: ReactNode;
598
+ children?: ReactNode;
599
+ };
600
+
601
+ export function PreferenceCard({ input, icon, title, tag, children }: PreferenceCardProps) {
602
+ return (
603
+ <Card className="rounded-lg border">
604
+ {input && (
605
+ <Card.input asChild className="border-r p-4">
606
+ <label>{input}</label>
607
+ </Card.input>
608
+ )}
609
+ <Card.content className="gap-2 p-4">
610
+ {icon && <Card.content.icon>{icon}</Card.content.icon>}
611
+ <Card.content.information>{title}</Card.content.information>
612
+ {tag && <Card.content.cardTag>{tag}</Card.content.cardTag>}
613
+ {children && <Card.content.children>{children}</Card.content.children>}
614
+ </Card.content>
615
+ </Card>
616
+ );
617
+ }
618
+ ```
619
+
620
+ **ID card:** the layered card from [Layers](#layers-baselayer). On narrow
621
+ cards the logo, badge and identity sit in the photo's corners, and the name
622
+ turns white over the photo; from `@md` the photo is a column of its own and
623
+ everything else moves beside it.
624
+
625
+ ```tsx
626
+ import { defineLayout } from "typed-grid-areas";
627
+ import { createGridComponent } from "@typed-grid-areas/react";
628
+
629
+ const Card = createGridComponent(
630
+ defineLayout({
631
+ areas: ["photo", "identity", "details", "logo?", "qr?", "badge?"],
632
+ layouts: [
633
+ {
634
+ template: `
635
+ photo+logo photo photo+badge
636
+ photo photo photo
637
+ photo+identity photo+identity photo+identity
638
+ details details qr`,
639
+ rows: "40px 80px 40px 60px",
640
+ columns: "60px 1fr 60px",
641
+ breakpoints: {
642
+ "@md": {
643
+ template: `
644
+ photo photo+badge identity logo
645
+ photo photo details qr`,
646
+ rows: "40px 120px",
647
+ columns: "100px 40px 1fr 80px",
648
+ },
649
+ },
650
+ },
651
+ ],
652
+ }),
653
+ );
654
+
655
+ type Person = { name: string; role: string; photoUrl: string; verified?: boolean };
656
+
657
+ export function IdCard({ person, qrUrl }: { person: Person; qrUrl?: string }) {
658
+ return (
659
+ <Card className="overflow-hidden rounded-xl">
660
+ <Card.photo asChild>
661
+ <img src={person.photoUrl} alt="" className="h-full w-full object-cover" />
662
+ </Card.photo>
663
+ <Card.logo>ACME</Card.logo>
664
+ {person.verified && <Card.badge>✓</Card.badge>}
665
+ <Card.identity>
666
+ {/* White over the photo, through `@container style(--tga-over: photo)`. */}
667
+ <span className="identity-name">{person.name}</span>
668
+ </Card.identity>
669
+ <Card.details>{person.role}</Card.details>
670
+ {qrUrl && (
671
+ <Card.qr asChild>
672
+ <img src={qrUrl} alt="QR code" />
673
+ </Card.qr>
674
+ )}
675
+ </Card>
676
+ );
677
+ }
678
+ ```
679
+
680
+ ## Rendering with Angular: grid directives
681
+
682
+ ```sh
683
+ npm i typed-grid-areas @typed-grid-areas/angular
684
+ ```
685
+
686
+ `@typed-grid-areas/angular` supports Angular 22 (`@angular/core`
687
+ `^22.0.0`). Instead of components, it gives you three standalone attribute
688
+ directives that go on your own elements, and a typed reference per
689
+ definition that the template names grids and areas through:
690
+
691
+ ```ts angular
692
+ import { Component, input } from "@angular/core";
693
+ import { defineLayout } from "typed-grid-areas";
694
+ import { createGrid, TgaArea, TgaGrid, TgaSizeContainer } from "@typed-grid-areas/angular";
695
+
696
+ const Content = createGrid(
697
+ defineLayout({
698
+ areas: ["icon?", "title"],
699
+ layouts: [{ template: "title", breakpoints: { "@sm": { template: "icon title" } } }],
700
+ }),
701
+ );
702
+
703
+ const Card = createGrid(
704
+ defineLayout({ areas: ["input?", "content"], layouts: [{ template: "input content" }] }),
705
+ { nest: { content: Content } },
706
+ );
707
+
708
+ @Component({
709
+ selector: "app-card",
710
+ imports: [TgaGrid, TgaArea, TgaSizeContainer],
711
+ template: `
712
+ <div [tgaGrid]="Card" class="gap-2">
713
+ @if (selectable()) {
714
+ <label [tgaArea]="Card.input"><input type="checkbox" /></label>
715
+ }
716
+ <div tgaSizeContainer>
717
+ <div [tgaGrid]="Card.content" class="p-4">
718
+ <span [tgaArea]="Card.content.icon">★</span>
719
+ <h2 [tgaArea]="Card.content.title">Title</h2>
720
+ </div>
721
+ </div>
722
+ </div>
723
+ `,
724
+ })
725
+ export class CardComponent {
726
+ protected readonly Card = Card;
727
+ readonly selectable = input(false);
728
+ }
729
+ ```
730
+
731
+ - **`createGrid(definition, { nest })`** returns the definition's reference:
732
+ the grid itself, with one property per area (`Card.input`). An area nested
733
+ through `nest` is the nested grid's reference (`Card.content`), whose
734
+ properties are its areas (`Card.content.icon`). Create references at module
735
+ level and expose them to the template from the component
736
+ (`protected readonly Card = Card`).
737
+ - **`[tgaGrid]="Card"`** makes the element it's on the grid. It takes a grid
738
+ reference, so with `strictTemplates`, `[tgaGrid]="Card.input"` doesn't
739
+ compile.
740
+ - **`[tgaArea]="Card.input"`** makes the element it's on the slot that fills
741
+ an area. It takes an area reference, not a string, so a misspelled area
742
+ (`Card.inputt`, `Card.content.iconn`), a plain string or a grid reference
743
+ doesn't compile. Slots must be direct children of their grid's element;
744
+ make an optional area absent with `@if`.
745
+ - **`tgaSizeContainer`** marks the element around a grid with breakpoints as
746
+ its size container (a directive can't wrap its own element). It gets the
747
+ container styles, and when the grid is nested, the outer grid's
748
+ `data-area`. Leave it out for grids without breakpoints.
749
+
750
+ **Your own element as a slot** needs nothing extra: put `[tgaArea]` (or
751
+ `[tgaGrid]`) on any element, including a component's host element
752
+ (`<app-avatar [tgaArea]="Card.content.icon" />`). Your classes and
753
+ attributes stay where you wrote them.
754
+
755
+ **CSS.** Each definition's CSS goes into a
756
+ `<style data-typed-grid-areas="…">` in the `<head>` of Angular's `DOCUMENT`,
757
+ once, however many instances render, carrying the `CSP_NONCE` value when
758
+ your app provides one. Without server rendering it's inserted when the
759
+ first grid of a definition renders. With server rendering (`@angular/ssr`)
760
+ it's in the rendered `<head>`, and client hydration reuses it rather than
761
+ adding a second copy. Nothing to set up either way.
762
+
763
+ **Development warnings.** In development mode (`isDevMode()`), in the
764
+ browser, a grid warns on the console after every render when a required
765
+ area's slot is missing, when it has a direct child that isn't one of its
766
+ slots, or when it has breakpoints but its parent isn't its size container.
767
+ Production builds and server rendering log nothing.
768
+
769
+ ## Rendering with Vue: `@typed-grid-areas/vue`
770
+
771
+ ```sh
772
+ npm i typed-grid-areas @typed-grid-areas/vue
773
+ ```
774
+
775
+ `@typed-grid-areas/vue` needs `vue` 3.5 or later. It has the React
776
+ adapter's shape: `createGridComponent(definition, { nest })` returns the
777
+ grid's component, with a member component per area that templates use as a
778
+ tag (`<Card.input>`):
779
+
780
+ ```vue
781
+ <script setup lang="ts">
782
+ import { defineLayout } from "typed-grid-areas";
783
+ import { createGridComponent } from "@typed-grid-areas/vue";
784
+
785
+ defineProps<{ selectable: boolean }>();
786
+
787
+ const Content = createGridComponent(
788
+ defineLayout({ areas: ["icon?", "title"], layouts: [{ template: "icon title" }] }),
789
+ );
790
+ const Card = createGridComponent(
791
+ defineLayout({ areas: ["input?", "content"], layouts: [{ template: "input content" }] }),
792
+ { nest: { content: Content } },
793
+ );
794
+ </script>
795
+
796
+ <template>
797
+ <Card class="gap-4" aria-label="Card">
798
+ <Card.input v-if="selectable" as-child>
799
+ <label><input type="checkbox" /></label>
800
+ </Card.input>
801
+ <Card.content class="p-4">
802
+ <Card.content.icon>★</Card.content.icon>
803
+ <Card.content.title>Title</Card.content.title>
804
+ </Card.content>
805
+ </Card>
806
+ </template>
807
+ ```
808
+
809
+ - **`<Card>`** renders the grid, a `div` taking `class`, `style` and any other
810
+ attribute (inside its own size container when the definition has
811
+ breakpoints; your attributes still go on the grid). **`<Card.input>`** is
812
+ the slot for the `input` area, a `div` marked `data-area="input"`.
813
+ **`<Card.content>`** is both the `content` slot and the nested grid, so
814
+ `<Card.content.icon>` is one of its slots. Leave an optional area out with
815
+ `v-if`; slots must be direct children of their grid.
816
+ - **Bind grid components in `<script setup>`** (or return them from
817
+ `setup()`): Vue resolves member tags like `<Card.input>` only from there.
818
+ Registering them under `components:` (Options API) and in-DOM templates
819
+ aren't supported. Run `vue-tsc` to type-check templates: `<Card.inputt>`
820
+ and `<Card.content.iconn>` are type errors.
821
+ - **`as-child`** (on slots and on the grid) renders your own single child
822
+ element instead of a `div`, the way Reka UI's `as-child` does: the slot's
823
+ attributes are merged into the child's (the child's own win, classes and
824
+ styles combine, event handlers both run), it always gets the slot's
825
+ `data-area` (or the grid's `data-grid-id`), and its own `ref` still
826
+ reaches it.
827
+ - **Area names Vue reserves** on a component (`length`, `props`, `emits`,
828
+ `slots`, `inheritAttrs`, `displayName`, `compatConfig`, and any starting
829
+ with `__`) can't be members: `createGridComponent` rejects them, as a type
830
+ error and at runtime.
831
+
832
+ **CSS.** In the browser, each grid puts its definition's CSS into `<head>`
833
+ once (a `<style data-typed-grid-areas>`), however many instances render, and
834
+ leaves it there. Vue has no API for `<head>` on the server, so when you
835
+ server-render, add the grids' style tags to your page's `<head>` in your
836
+ server entry with `renderGridStyles`:
837
+
838
+ ```js
839
+ import { renderToString } from "vue/server-renderer";
840
+ import { renderGridStyles } from "@typed-grid-areas/vue";
841
+
842
+ /** @param {import("vue").App} app the app from `createSSRApp` */
843
+ export async function render(app) {
844
+ const ctx = {};
845
+ const html = await renderToString(app, ctx);
846
+ return { html, head: renderGridStyles(ctx) };
847
+ }
848
+ ```
849
+
850
+ It returns one tag per definition rendered with that `ctx`, and hydration
851
+ reuses them instead of adding a second. Without it, server-rendered grids
852
+ still work: their CSS is inserted on hydration, so the page lays out once
853
+ the app's script runs.
854
+
855
+ **Development warnings.** In development (`process.env.NODE_ENV ===
856
+ "development"`), a grid warns on the console after it mounts and after each
857
+ update when a required area's slot isn't rendered, or when it has a direct
858
+ child that isn't one of its slots. Production builds and server rendering
859
+ log nothing.
860
+
861
+ ## Rendering with Solid: `@typed-grid-areas/solid`
862
+
863
+ ```sh
864
+ npm i typed-grid-areas @typed-grid-areas/solid
865
+ ```
866
+
867
+ `@typed-grid-areas/solid` supports Solid 1.x: it needs `solid-js` 1.9 or
868
+ later within 1.x. Solid 2 will be supported by a new major of the adapter.
869
+
870
+ The API is the React adapter's: `createGridComponent(definition, { nest })`
871
+ returns the grid component, with a slot component per area (`<Card.icon>`),
872
+ and a nested grid's slots reached through its area (`<Card.content.icon>`).
873
+ Create it once, at module level. Slots and the grid take `class`, `style`,
874
+ `ref`, `children` and any other attribute of the element they render.
875
+
876
+ ```tsx solid
877
+ import { createSignal, Show } from "solid-js";
878
+ import { defineLayout } from "typed-grid-areas";
879
+ import { createGridComponent } from "@typed-grid-areas/solid";
880
+
881
+ const Content = createGridComponent(
882
+ defineLayout({ areas: ["icon?", "title", "tag?"], layouts: [{ template: "icon title tag" }] }),
883
+ );
884
+
885
+ const Card = createGridComponent(
886
+ defineLayout({ areas: ["input?", "content"], layouts: [{ template: "input content" }] }),
887
+ { nest: { content: Content } },
888
+ );
889
+
890
+ function Example(props: { tag?: string }) {
891
+ const [hasIcon, setHasIcon] = createSignal(true);
892
+ return (
893
+ <Card class="gap-4" aria-label="Card">
894
+ <Card.input as="label" for="notify">
895
+ <input id="notify" type="checkbox" onChange={() => setHasIcon(!hasIcon())} />
896
+ </Card.input>
897
+ <Card.content class="p-4">
898
+ <Show when={hasIcon()}>
899
+ <Card.content.icon>★</Card.content.icon>
900
+ </Show>
901
+ <Card.content.title>Weekly digest</Card.content.title>
902
+ <Show when={props.tag}>
903
+ <Card.content.tag>{props.tag}</Card.content.tag>
904
+ </Show>
905
+ </Card.content>
906
+ </Card>
907
+ );
908
+ }
909
+ ```
910
+
911
+ - **Optional areas** are absent when their slot isn't rendered: use Solid's
912
+ own `<Show>` (or any conditional). Slots stay reactive, through a nested
913
+ grid's root too, and so does the layout.
914
+ - **Your own element as a slot: `as`.** Solid's JSX creates real DOM nodes,
915
+ so there's no `asChild`; instead `as` (on slots and the grid) renders the
916
+ slot as a tag name, a component or a render function, with no wrapper.
917
+ The other props are typed from `as`: with `as="label"`, `for` type-checks
918
+ and `ref` gets an `HTMLLabelElement`, and an attribute a label doesn't take
919
+ is an error. A component (or render function) gets the slot's props,
920
+ including its `data-area`, and must spread them onto its root element.
921
+ Annotate a render function's `props` for the slot to take that element's
922
+ attributes:
923
+
924
+ ```tsx solid
925
+ import type { JSX } from "solid-js";
926
+ import { defineLayout } from "typed-grid-areas";
927
+ import { createGridComponent } from "@typed-grid-areas/solid";
928
+
929
+ const Row = createGridComponent(
930
+ defineLayout({ areas: ["icon", "input"], layouts: [{ template: "icon input" }] }),
931
+ );
932
+
933
+ function Icon(props: JSX.SvgSVGAttributes<SVGSVGElement> & { size: number }) {
934
+ return <svg {...props} width={props.size} height={props.size} />;
935
+ }
936
+
937
+ function Example() {
938
+ return (
939
+ <Row as="section">
940
+ <Row.icon as={Icon} size={16} />
941
+ <Row.input
942
+ as={(props: JSX.LabelHTMLAttributes<HTMLLabelElement>) => <label {...props} />}
943
+ for="notify"
944
+ >
945
+ <input id="notify" type="checkbox" />
946
+ </Row.input>
947
+ </Row>
948
+ );
949
+ }
950
+ ```
951
+
952
+ - **CSS.** Each definition's CSS goes on the page once, however many
953
+ instances render. In the browser, the grid puts its style tag in `<head>`
954
+ as it's created, reusing one the server rendered, so hydration adds no
955
+ second copy. On the server, the grid registers its style tag with Solid's
956
+ `useAssets`, once per definition per render, and `renderToString`,
957
+ `renderToStringAsync` and `renderToStream` put it before `</head>` when the
958
+ app renders the whole document (as SolidStart does). If your app renders
959
+ only part of the page, put `getAssets()` from `solid-js/web` in the
960
+ `<head>` you render around it. Nothing else is needed: no `@solidjs/meta`.
961
+ - **Development warnings** are React's: in development
962
+ (`process.env.NODE_ENV === "development"`), after mount and after every
963
+ change to its slots, a grid warns about a missing required slot or a
964
+ direct child that isn't a slot, once per distinct set of problems. Never on
965
+ the server, never in production.
966
+ - **Builds.** The package's `solid` export is Solid JSX for your bundler's
967
+ Solid plugin (`vite-plugin-solid` and the like) to compile, for the browser
968
+ or the server; its `import` export is compiled for the browser.
969
+ - **Server rendering needs a Solid-aware bundler.** Only the `solid` export
970
+ renders on the server, so the server build must resolve the `solid`
971
+ export condition, as `vite-plugin-solid` (and SolidStart) does. Without
972
+ that condition, plain Node loads the browser build, and importing it
973
+ throws Solid's "Client-only API called on the server side".
974
+
975
+ ## Rendering with Svelte: `@typed-grid-areas/svelte`
976
+
977
+ ```sh
978
+ npm i typed-grid-areas @typed-grid-areas/svelte
979
+ ```
980
+
981
+ Needs Svelte 5.57.0 or later, in runes mode. The package ships `.svelte`
982
+ files under the `svelte` export condition, so build with a Svelte-aware
983
+ bundler (Vite with `@sveltejs/vite-plugin-svelte`, or SvelteKit).
984
+
985
+ `createGridComponent(definition, { nest })` turns a definition into a
986
+ component with one member per area, like the React adapter. A `.svelte`
987
+ file can't be a generic factory, so create grid components in a module: a
988
+ `.ts` file, or a component's `<script module>`:
989
+
990
+ ```svelte
991
+ <script module lang="ts">
992
+ import { defineLayout } from "typed-grid-areas";
993
+ import { createGridComponent } from "@typed-grid-areas/svelte";
994
+
995
+ const Content = createGridComponent(
996
+ defineLayout({
997
+ areas: ["icon?", "information", "cardTag?"],
998
+ layouts: [
999
+ {
1000
+ template: "icon information cardTag",
1001
+ columns: "min-content minmax(0, 1fr) auto",
1002
+ },
1003
+ ],
1004
+ }),
1005
+ );
1006
+
1007
+ const Card = createGridComponent(
1008
+ defineLayout({
1009
+ areas: ["input?", "content"],
1010
+ layouts: [{ template: "input content", columns: "auto minmax(0, 1fr)" }],
1011
+ }),
1012
+ { nest: { content: Content } },
1013
+ );
1014
+ </script>
1015
+
1016
+ <script lang="ts">
1017
+ let { selectable = false, tag }: { selectable?: boolean; tag?: string } = $props();
1018
+ </script>
1019
+
1020
+ <Card class="gap-2" aria-label="Card">
1021
+ {#if selectable}
1022
+ <Card.input>
1023
+ {#snippet child({ props })}
1024
+ <label {...props}><input type="checkbox" /></label>
1025
+ {/snippet}
1026
+ </Card.input>
1027
+ {/if}
1028
+ <Card.content class="p-4">
1029
+ <Card.content.icon>★</Card.content.icon>
1030
+ <Card.content.information>Weekly digest</Card.content.information>
1031
+ {#if tag}
1032
+ <Card.content.cardTag>{tag}</Card.content.cardTag>
1033
+ {/if}
1034
+ </Card.content>
1035
+ </Card>
1036
+ ```
1037
+
1038
+ - **`<Card>`** renders the grid, and **`<Card.icon>`** the slot for the
1039
+ `icon` area, exactly as in React: the same DOM, the same size container
1040
+ for a definition with breakpoints (your attributes still go on the grid),
1041
+ and `<Card.iconn>` is an error in `svelte-check`. Both take any attribute
1042
+ a `div` takes (`class`, `style`, `aria-*`, event handlers) and children.
1043
+ - **Optional areas:** leave a slot out with an ordinary `{#if}`; the
1044
+ derived layout for its absence applies. Slots must be direct children of
1045
+ their grid (`{#if}`, `{#each}` and snippets rendered in place are fine).
1046
+ - **Your own element as a slot (or the grid):** pass a `child` snippet
1047
+ instead of children, and spread its `props` onto your element, Bits UI's
1048
+ convention: `{#snippet child({ props })}<label {...props}>…</label>{/snippet}`.
1049
+ `props` carries the slot's `data-area` (or the grid's attributes) and
1050
+ every attribute you gave the component.
1051
+ - **Nesting:** `nest: { content: Content }` makes `<Card.content>` both the
1052
+ `content` slot and the `Content` grid, reaching its slots as
1053
+ `<Card.content.icon>`.
1054
+
1055
+ **Where the CSS goes.** Each definition's CSS is a
1056
+ `<style data-typed-grid-areas="<grid id>">` in `<svelte:head>`, rendered by
1057
+ exactly one instance of the definition, however many render:
1058
+
1059
+ - **With server rendering**, `render()` from `svelte/server` puts it in
1060
+ `head` once per render; SvelteKit puts `head` into the page for you, and
1061
+ with plain `svelte/server` you put it in your HTML's `<head>`. Hydration
1062
+ reuses the server's tag.
1063
+ - **Without server rendering**, the first mounted instance adds it to
1064
+ `document.head`; when that instance unmounts another one takes it over,
1065
+ and it goes away with the last instance.
1066
+
1067
+ **Development warnings.** Under the `development` export condition (Vite's
1068
+ dev server, Vitest), a grid warns on the console when a required area's
1069
+ slot isn't rendered or it has a direct child that isn't one of its slots,
1070
+ once per distinct set of problems, after mount and after each update.
1071
+ Production builds and server rendering log nothing.
1072
+
1073
+ ## Rendering with Preact: `@typed-grid-areas/preact`
1074
+
1075
+ ```sh
1076
+ npm i typed-grid-areas @typed-grid-areas/preact
1077
+ ```
1078
+
1079
+ `@typed-grid-areas/preact` is a native Preact adapter (no `preact/compat`)
1080
+ for Preact 11 (`preact` `^11.0.0`; checked with 11.1). Its API is the React
1081
+ adapter's: `createGridComponent(definition, { nest })` returns `<Card>`,
1082
+ with a slot component per area (`<Card.icon>`), each taking anything a
1083
+ `div` takes (`class` or `className`, `style`, `ref`, …):
1084
+
1085
+ ```tsx preact
1086
+ import { defineLayout } from "typed-grid-areas";
1087
+ import { createGridComponent } from "@typed-grid-areas/preact";
1088
+
1089
+ const Card = createGridComponent(
1090
+ defineLayout({
1091
+ areas: ["icon?", "information", "cardTag?"],
1092
+ layouts: [
1093
+ {
1094
+ template: "icon information cardTag",
1095
+ columns: "min-content minmax(0, 1fr) auto",
1096
+ },
1097
+ ],
1098
+ }),
1099
+ );
1100
+
1101
+ function Example({ tag }: { tag?: string }) {
1102
+ return (
1103
+ <Card class="gap-2">
1104
+ <Card.icon>★</Card.icon>
1105
+ <Card.information>Weekly digest</Card.information>
1106
+ {tag && <Card.cardTag>{tag}</Card.cardTag>}
1107
+ </Card>
1108
+ );
1109
+ }
1110
+ ```
1111
+
1112
+ The rendered DOM, `nest`, and the development warnings are the React
1113
+ adapter's ([Rendering with React](#rendering-with-react-grid-components)).
1114
+
1115
+ **Your own element as a slot: `asChild`.** On a slot or on the grid,
1116
+ `asChild` renders your single child element instead of a `div`. Classes
1117
+ (`class` and `className`) from both are joined, `style` objects merge (a
1118
+ string style is appended after the slot's), a handler on both runs the
1119
+ child's then the slot's, and both refs are set. The slot's `data-area` (or
1120
+ the grid's `data-grid-id`) always wins; any other prop of the child wins.
1121
+
1122
+ ```tsx preact
1123
+ import { defineLayout } from "typed-grid-areas";
1124
+ import { createGridComponent } from "@typed-grid-areas/preact";
1125
+
1126
+ const Row = createGridComponent(
1127
+ defineLayout({ areas: ["input", "content"], layouts: [{ template: "input content" }] }),
1128
+ );
1129
+
1130
+ function Example() {
1131
+ return (
1132
+ <Row>
1133
+ <Row.input asChild class="p-4">
1134
+ <label for="notify">
1135
+ <input id="notify" type="checkbox" />
1136
+ </label>
1137
+ </Row.input>
1138
+ <Row.content>Notify me</Row.content>
1139
+ </Row>
1140
+ );
1141
+ }
1142
+ ```
1143
+
1144
+ **Where the CSS goes.** In the browser, each definition's CSS goes into one
1145
+ `<style data-typed-grid-areas>` in `<head>`, inserted while the first
1146
+ instance renders and kept for the page's lifetime; nothing to set up.
1147
+ Preact has no way to reach `<head>` from the server, so a server render
1148
+ collects it with `createGridStyleSheet()`, a new one per request, and puts
1149
+ it in `<head>` itself:
1150
+
1151
+ ```tsx preact
1152
+ import { renderToString } from "preact-render-to-string";
1153
+ import { createGridStyleSheet } from "@typed-grid-areas/preact";
1154
+
1155
+ function App() {
1156
+ return <main>…</main>;
1157
+ }
1158
+
1159
+ const sheet = createGridStyleSheet();
1160
+ const body = renderToString(sheet.collect(<App />));
1161
+ const html = `<!doctype html><html><head>${sheet}</head><body>${body}</body></html>`;
1162
+ ```
1163
+
1164
+ When the page hydrates, the grids reuse the server's style tags. In
1165
+ development, a grid rendered on the server outside a sheet warns that its
1166
+ CSS is missing.
1167
+
1168
+ ## Rendering with Lit: grid template functions
1169
+
1170
+ ```sh
1171
+ npm i typed-grid-areas @typed-grid-areas/lit
1172
+ ```
1173
+
1174
+ `@typed-grid-areas/lit` needs `lit` 3. `createGrid(definition)` turns a
1175
+ definition into a template function; each area is a member of it, typed as
1176
+ the area's name. Create grids at module level, once per definition:
1177
+
1178
+ ```ts lit
1179
+ import { css, html, LitElement, nothing } from "lit";
1180
+ import { defineLayout } from "typed-grid-areas";
1181
+ import { createGrid, gridStyles } from "@typed-grid-areas/lit";
1182
+
1183
+ const Content = createGrid(
1184
+ defineLayout({
1185
+ areas: ["icon?", "title"],
1186
+ layouts: [{ template: "icon title", columns: "min-content minmax(0, 1fr)" }],
1187
+ }),
1188
+ );
1189
+
1190
+ const Card = createGrid(
1191
+ defineLayout({
1192
+ areas: ["input?", "content"],
1193
+ layouts: [{ template: "input content", columns: "auto minmax(0, 1fr)" }],
1194
+ }),
1195
+ { nest: { content: Content } },
1196
+ );
1197
+
1198
+ class PreferenceCard extends LitElement {
1199
+ static styles = [
1200
+ gridStyles(Card),
1201
+ css`
1202
+ .gap {
1203
+ gap: 1rem;
1204
+ }
1205
+ `,
1206
+ ];
1207
+ static properties = { selectable: { type: Boolean } };
1208
+ declare selectable: boolean;
1209
+
1210
+ constructor() {
1211
+ super();
1212
+ this.selectable = false;
1213
+ }
1214
+
1215
+ render() {
1216
+ return Card(
1217
+ html`
1218
+ ${
1219
+ this.selectable
1220
+ ? html`<label data-area=${Card.input}><input type="checkbox" /></label>`
1221
+ : nothing
1222
+ }
1223
+ ${Card.content(
1224
+ html`
1225
+ <span data-area=${Card.content.icon}>★</span>
1226
+ <div data-area=${Card.content.title}>Weekly digest</div>
1227
+ `,
1228
+ { class: "p-4" },
1229
+ )}
1230
+ `,
1231
+ { class: "gap" },
1232
+ );
1233
+ }
1234
+ }
1235
+
1236
+ customElements.define("preference-card", PreferenceCard);
1237
+ ```
1238
+
1239
+ - **`Card(content, { class, style, ref })`** renders the grid: a `div` with
1240
+ the definition's `data-grid-id`, with `content` as its slots. When the
1241
+ definition has breakpoints the grid sits inside its own size container;
1242
+ the options still go on the grid. Lit can't spread arbitrary attributes,
1243
+ so the grid takes only `class`, `style` (text, or an object as `styleMap`
1244
+ takes it) and `ref` (as Lit's `ref` directive takes it): for other
1245
+ attributes or event listeners on the grid, use `ref`.
1246
+ - **`Card.input`** is the area's name, `"input"`, typed as that literal.
1247
+ A slot is any element with `data-area=${Card.input}`: your own `<label>`,
1248
+ `<img>` or `<button>` is the slot itself, with nothing to opt into and no
1249
+ wrapper. `Card.inptu` is a type error. A slot here is an element with
1250
+ `data-area`, never a `<slot>`.
1251
+ - **`nest`** makes the area's member the nested grid's template function:
1252
+ `Card.content(…)` renders `Content` as the `content` slot of `Card`, and
1253
+ `Card.content.icon` reaches its areas.
1254
+
1255
+ Slots must be **direct children** of their grid, in the grid's own DOM:
1256
+ grids render in light DOM, wherever your template is (usually your
1257
+ component's shadow root), since the generated CSS's child selectors can't see
1258
+ through a shadow boundary into `<slot>`ted children. Leave an optional
1259
+ area's slot out with an ordinary conditional (`nothing`) to make it absent.
1260
+
1261
+ ### CSS, server rendering and development warnings
1262
+
1263
+ Each grid puts its definition's CSS in the root it renders in, after each
1264
+ update:
1265
+
1266
+ - **In a shadow root**, one shared constructable style sheet per definition
1267
+ is adopted into it, once per shadow root rather than once per page. Your
1268
+ component's own `static styles` still beat the grid's layered CSS, and an
1269
+ area its layout leaves out stays hidden whatever `display` its slot sets.
1270
+ - **In the document**, a `<style data-typed-grid-areas>` goes into `<head>`,
1271
+ once per definition.
1272
+
1273
+ `gridStyles(Card)` returns the CSS of `Card` and the grids nested in it, as a
1274
+ `CSSResult` for `static styles`. In the browser it's optional (a grid already
1275
+ there isn't adopted again). **Server rendering needs it**: with
1276
+ `@lit-labs/ssr`, Lit's server renderer, the CSS reaches each component's
1277
+ declarative shadow root only through `static styles`, and hydration with
1278
+ `@lit-labs/ssr-client` takes over from there. Grids rendered on the server
1279
+ outside any shadow root need their style tags in `<head>`: see
1280
+ `gridStyleTags` [below](#without-react-typed-grid-areasadapter).
1281
+
1282
+ In development (`process.env.NODE_ENV === "development"`), a grid warns on
1283
+ the console after an update when a required area's slot isn't rendered, or
1284
+ when it has a direct child that isn't one of its slots, once per distinct
1285
+ set of problems.
1286
+
1287
+ Supported: Lit 3, and `@lit-labs/ssr` 4 (still labelled pre-release by the
1288
+ Lit team) for server rendering.
1289
+
1290
+ ## Rendering with Octane: `@typed-grid-areas/octane` (experimental)
1291
+
1292
+ ```sh
1293
+ npm i typed-grid-areas @typed-grid-areas/octane
1294
+ ```
1295
+
1296
+ `@typed-grid-areas/octane` renders a definition as typed slot components in
1297
+ [Octane](https://octanejs.dev), natively (not through Octane's React
1298
+ compatibility layer). It is **experimental until Octane 1.0**: it supports
1299
+ the current Octane minor only, **Octane 0.16** (`octane@^0.16.0`), and each
1300
+ new Octane minor needs a release of the adapter.
1301
+
1302
+ The package ships its source (`.tsx`), not a build: your app's Octane
1303
+ bundler plugin (`@octanejs/vite-plugin`, Rspack, Rsbuild) compiles it like
1304
+ your own components, and plain `tsc` type-checks it.
1305
+
1306
+ ```tsrx
1307
+ import { defineLayout } from "typed-grid-areas";
1308
+ import { createGridComponent } from "@typed-grid-areas/octane";
1309
+
1310
+ const Content = createGridComponent(
1311
+ defineLayout({ areas: ["icon?", "title"], layouts: [{ template: "icon title" }] }),
1312
+ );
1313
+
1314
+ const Card = createGridComponent(
1315
+ defineLayout({ areas: ["input?", "content"], layouts: [{ template: "input content" }] }),
1316
+ { nest: { content: Content } },
1317
+ );
1318
+
1319
+ export function Example(props: { selectable: boolean }) @{
1320
+ <Card class="gap-4" render={<section />}>
1321
+ @if (props.selectable) {
1322
+ <Card.input render={<label for="notify" />}><input id="notify" type="checkbox" /></Card.input>
1323
+ }
1324
+ <Card.content>
1325
+ <Card.content.icon>{'★'}</Card.content.icon>
1326
+ <Card.content.title>{'Notify me'}</Card.content.title>
1327
+ </Card.content>
1328
+ </Card>
1329
+ }
1330
+ ```
1331
+
1332
+ - **The API is React's** (see [Rendering with React](#rendering-with-react-grid-components)):
1333
+ `createGridComponent(definition, { nest })`, `<Card>` for the grid, a
1334
+ static slot component per area (`<Card.input>`, and `<Card.content.icon>`
1335
+ through `nest`), each taking `class`, `style`, `ref`, `children` and any
1336
+ other `div` props. Member tags work in `.tsx` and `.tsrx`, including
1337
+ inside `@if`; a misspelled area is a type error (`tsrx-tsc` checks
1338
+ `.tsrx`).
1339
+ - **Your own element as a slot: `render={<el />}`**, on slots and on the
1340
+ grid, instead of React's `asChild` (Octane's `.tsrx` compiles children to
1341
+ functions, which can't be cloned). The element is rendered with the
1342
+ slot's props merged in: the adapter's `data-area` / `data-grid-id` always
1343
+ win; otherwise the element's own props win; classes compose, styles merge,
1344
+ event handlers chain (the element's first), both refs attach; the slot's
1345
+ children become the element's children.
1346
+ - **Optional areas:** leave a slot out with Octane's ordinary conditional
1347
+ (`@if` in `.tsrx`, `{cond && …}` in `.tsx`); the derived layout applies.
1348
+ - **CSS:** each definition's CSS goes on the page once, through Octane's
1349
+ `injectStyle`: one `<style data-octane>` tag per definition in `<head>`,
1350
+ however many instances render. Without server rendering there is nothing
1351
+ to do. With it, `renderToString` (and `prerender`) return the CSS in
1352
+ `css`, separate from `html`: put `result.css` before your markup (in
1353
+ `<head>`), as Octane's scoped styles require. A stream
1354
+ (`renderToReadableStream`, `renderToPipeableStream`) leads its shell with
1355
+ it. Hydration adopts the server's tags instead of adding second copies.
1356
+ - **Development warnings** are React's: a missing required slot or a stray
1357
+ direct child warns once (after mount, and after an update that introduces
1358
+ it); production and server rendering log nothing.
1359
+
1360
+ ```ts octane
1361
+ // entry-server.ts
1362
+ import { renderToString } from "octane/server";
1363
+ import { App } from "./App.tsrx";
1364
+
1365
+ const { html, css } = renderToString(App);
1366
+ const page = `<!doctype html><html><head>${css}</head><body><div id="root">${html}</div></body></html>`;
1367
+ ```
1368
+
1369
+ ## Without React: `typed-grid-areas/adapter`
1370
+
1371
+ The core has no React dependency. To render grids in another framework, build
1372
+ on `typed-grid-areas/adapter`: it says exactly what to render for a
1373
+ definition, so your adapter renders the same DOM the React one does.
1374
+
1375
+ ```ts
1376
+ import { defineLayout } from "typed-grid-areas";
1377
+ import {
1378
+ createSlotCheck,
1379
+ gridMarkup,
1380
+ gridStyleTags,
1381
+ insertGridStyle,
1382
+ } from "typed-grid-areas/adapter";
1383
+
1384
+ const cardGrid = defineLayout({
1385
+ areas: ["icon?", "info"],
1386
+ layouts: [{ template: "icon info", breakpoints: { "@sm": { template: "info icon" } } }],
1387
+ });
1388
+
1389
+ // Once per definition.
1390
+ const markup = gridMarkup(cardGrid);
1391
+
1392
+ // Per instance. Pass the outer grid's area when this grid fills one.
1393
+ const { sizeContainer, grid } = markup.elements("content");
1394
+ // sizeContainer: undefined without breakpoints; otherwise the element that
1395
+ // wraps the grid: { attributes: { "data-area": "content" }, style, styleText }
1396
+ // grid.attributes: { "data-grid-id": markup.id }, plus the outer "data-area"
1397
+ // when there's no size container
1398
+
1399
+ markup.slot("info"); // { "data-area": "info" }, for each direct child of the grid
1400
+
1401
+ // The CSS, once per page: in the browser...
1402
+ insertGridStyle(document, cardGrid);
1403
+ // ...or in server-rendered <head>.
1404
+ const head = gridStyleTags([cardGrid]);
1405
+
1406
+ // In development, after each render: what to warn about the grid's slots.
1407
+ try {
1408
+ if (process.env.NODE_ENV === "development") {
1409
+ const checkSlots = createSlotCheck(cardGrid, {
1410
+ strayChildRemedy: "make it a slot with asChild",
1411
+ });
1412
+ const gridElement = document.querySelector(`[data-grid-id="${markup.id}"]`);
1413
+ if (gridElement !== null) {
1414
+ checkSlots(gridElement).forEach(warning => console.warn(warning));
1415
+ }
1416
+ }
1417
+ } catch (error) {
1418
+ // Without a bundler, `process` may not exist: then this isn't development.
1419
+ if (!(error instanceof ReferenceError)) throw error;
1420
+ }
1421
+ ```
1422
+
1423
+ - **Elements.** Render the size container (when there is one) with its
1424
+ attributes and style, the grid inside it with its attributes, and each slot
1425
+ as a direct child of the grid with its attributes. The CSS makes the grid a
1426
+ grid and places the slots (see [Breakpoints](#breakpoints) for why a grid
1427
+ with breakpoints has its own size container).
1428
+ - **CSS.** `markup.css` belongs on the page once per definition, before its
1429
+ grids lay out. `insertGridStyle` puts a `<style data-typed-grid-areas="<grid
1430
+ id>">` in `<head>` (ahead of the page's other styles, reusing a tag the
1431
+ server rendered), and `gridStyleTags` renders those tags as an HTML string.
1432
+ A framework with its own way to emit a style once can key it by
1433
+ `markup.cssKey` instead.
1434
+ - **Slot check.** One check per grid instance; it reports a set of problems
1435
+ once. `strayChildRemedy` says how your framework makes an element a slot.
1436
+ Gate it on your framework's development flag, or read
1437
+ `process.env.NODE_ENV` as above: bundlers replace it, so production builds
1438
+ drop the check. Behind a call, such as `isDevelopment()`, they keep it.
1439
+
1440
+ The main entry's `createSlots`, `generateCss` and `gridId` remain for
1441
+ rendering by hand.
1442
+
1443
+ ## Development
1444
+
1445
+ An npm-workspaces monorepo: one folder per package under `packages/`
1446
+ (`core` is `typed-grid-areas`, `react` is `@typed-grid-areas/react`, and the
1447
+ private `acceptance` holds the browser acceptance tests every adapter runs).
1448
+ `npm install` at the root sets them all up.
1449
+
1450
+ ```sh
1451
+ just test # unit tests (happy-dom), the release scripts and the packed packages
1452
+ just test-browser # in-browser layout tests (Chromium via Playwright)
1453
+ just typecheck # tsc --noEmit, including the type tests
1454
+ just build # compile each package's src/ into its dist/, as npm pack does
1455
+ ```
1456
+
1457
+ Each runs every package's own script of that name (or via npm directly:
1458
+ `npm test`, `npm run typecheck`, `npm run build`). Each package owns its
1459
+ toolchain, down to its TypeScript version; see
1460
+ [docs/agents/workspaces.md](https://github.com/MichaelBuss/typed-grid-areas/blob/main/docs/agents/workspaces.md) for adding an adapter
1461
+ and pinning its own TypeScript.
1462
+
1463
+ A change to a package carries a changeset (`npm run changeset`); see
1464
+ [docs/agents/release.md](https://github.com/MichaelBuss/typed-grid-areas/blob/main/docs/agents/release.md) for how releases ship.