@schema-engine/layout 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +57 -2
- package/dist/index.d.ts +37 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +7 -0
- package/dist/lib/appearance.d.ts +204 -0
- package/dist/lib/appearance.js +2 -0
- package/dist/lib/appearance.js.map +7 -0
- package/dist/lib/deep-readonly.d.ts +10 -0
- package/dist/lib/deep-readonly.js +0 -0
- package/dist/lib/deep-readonly.js.map +7 -0
- package/dist/lib/grid-placement.d.ts +107 -0
- package/dist/lib/grid-placement.js +1 -0
- package/dist/lib/grid-placement.js.map +7 -0
- package/dist/lib/grid-styles.d.ts +178 -0
- package/dist/lib/grid-styles.js +2 -0
- package/dist/lib/grid-styles.js.map +7 -0
- package/dist/lib/layout-issue.d.ts +12 -0
- package/dist/lib/layout-issue.js +0 -0
- package/dist/lib/layout-issue.js.map +7 -0
- package/dist/lib/layout-theme.d.ts +94 -0
- package/dist/lib/layout-theme.js +4 -0
- package/dist/lib/layout-theme.js.map +7 -0
- package/dist/recipes/bind-recipe.d.ts +12 -0
- package/dist/recipes/bind-recipe.js +1 -0
- package/dist/recipes/bind-recipe.js.map +7 -0
- package/dist/recipes/define-recipe-spec.d.ts +49 -0
- package/dist/recipes/define-recipe-spec.js +1 -0
- package/dist/recipes/define-recipe-spec.js.map +7 -0
- package/dist/recipes/merge-slot-defaults.d.ts +8 -0
- package/dist/recipes/merge-slot-defaults.js +1 -0
- package/dist/recipes/merge-slot-defaults.js.map +7 -0
- package/dist/recipes/protocol.d.ts +69 -0
- package/dist/recipes/protocol.js +1 -0
- package/dist/recipes/protocol.js.map +7 -0
- package/dist/recipes/resolve-recipe-view.d.ts +52 -0
- package/dist/recipes/resolve-recipe-view.js +1 -0
- package/dist/recipes/resolve-recipe-view.js.map +7 -0
- package/dist/recipes/types.d.ts +53 -0
- package/dist/recipes/types.js +0 -0
- package/dist/recipes/types.js.map +7 -0
- package/dist/recipes/view-model.d.ts +20 -0
- package/dist/recipes/view-model.js +1 -0
- package/dist/recipes/view-model.js.map +7 -0
- package/dist/schemas/appearance.d.ts +57 -0
- package/dist/schemas/appearance.js +1 -0
- package/dist/schemas/appearance.js.map +7 -0
- package/dist/schemas/grid.d.ts +666 -0
- package/dist/schemas/grid.js +1 -0
- package/dist/schemas/grid.js.map +7 -0
- package/package.json +75 -3
- package/skill/SKILL.md +79 -0
- package/skill/reference/layout.md +48 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { type BaseRegistration, type ReadOnlyRegistry, type RegistrationMetadata } from '@schema-engine/registry';
|
|
2
|
+
import type { LayoutIssue } from './layout-issue';
|
|
3
|
+
import type { LayoutTheme, LayoutThemeCompilerOptions } from './layout-theme';
|
|
4
|
+
/**
|
|
5
|
+
* Appearance axes a document picks values on and renderers emit as data attributes.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* An axis is one independent dimension of appearance, with two to five named values. Each value
|
|
9
|
+
* stands for a set of semantic CSS tokens, which components read; components never read an axis
|
|
10
|
+
* value. The theme declares the axes ({@link defineAxis}, stored in a registry), a registration
|
|
11
|
+
* declares which axes it responds to, and a document picks values that pass down.
|
|
12
|
+
*
|
|
13
|
+
* A domain checks the pick against the vocabulary and the owner's declared axes
|
|
14
|
+
* ({@link checkAppearance}), merges it with the pick it inherits ({@link mergeAppearance}), and a
|
|
15
|
+
* renderer emits the result as `data-se-<axis>="<value>"` ({@link getAppearanceAttributes}).
|
|
16
|
+
* Walking the document tree to inherit picks belongs to the domain, because only it knows the
|
|
17
|
+
* tree's shape.
|
|
18
|
+
*
|
|
19
|
+
* Compile once, where the theme is built ({@link createLayoutTheme} does, with the grid). Token rules are
|
|
20
|
+
* emitted inside `:where()`, so they add no specificity and an author's `className` always wins; they
|
|
21
|
+
* are scoped to the theme by `data-se-theme` and the nearest theme above an element wins, so two themes
|
|
22
|
+
* with different tokens cannot overwrite each other ({@link getAppearanceCss} has the details).
|
|
23
|
+
*/
|
|
24
|
+
/** Custom properties a value stands for, keyed `--name`. */
|
|
25
|
+
export type AppearanceTokens = Readonly<Record<`--${string}`, string | number>>;
|
|
26
|
+
/** A pick of one value per axis. */
|
|
27
|
+
export type AppearanceSelection = Readonly<Record<string, string>>;
|
|
28
|
+
/**
|
|
29
|
+
* An appearance axis, stored in a registry like every other registration.
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* `schema` is a Standard Schema that accepts exactly the value names, which satisfies the
|
|
33
|
+
* registry's build check and is what a catalog or JSON Schema export lists. {@link defineAxis}
|
|
34
|
+
* produces it.
|
|
35
|
+
*/
|
|
36
|
+
export interface AxisRegistration<TName extends string = string, TValue extends string = string> extends BaseRegistration<unknown, RegistrationMetadata> {
|
|
37
|
+
readonly $type: TName;
|
|
38
|
+
/** Each value name and the semantic tokens it stands for. */
|
|
39
|
+
readonly values: Readonly<Record<TValue, AppearanceTokens>>;
|
|
40
|
+
/**
|
|
41
|
+
* The value that stands for no pick.
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* A component's own CSS fallbacks are the look of this value, so a document that picks it looks
|
|
45
|
+
* like one that picks nothing. To make that true under an inherited pick, a default value that
|
|
46
|
+
* leaves the tokens to the component sets them to `initial`: a custom property set to `initial`
|
|
47
|
+
* makes `var(--token, fallback)` use its fallback, so a step that picks `default` inside a
|
|
48
|
+
* `compact` form undoes the compact tokens.
|
|
49
|
+
*/
|
|
50
|
+
readonly default: TValue;
|
|
51
|
+
}
|
|
52
|
+
/** Any axis registration, whatever its name and values. */
|
|
53
|
+
export type AnyAxisRegistration = AxisRegistration;
|
|
54
|
+
/** A registry of axes, as {@link createLayoutTheme} builds it. */
|
|
55
|
+
export type AxisRegistry = ReadOnlyRegistry<AnyAxisRegistration>;
|
|
56
|
+
/** Input to {@link defineAxis}. */
|
|
57
|
+
export interface AxisDefinition<TName extends string, TValues extends Readonly<Record<string, AppearanceTokens>>> {
|
|
58
|
+
/** The axis name, which becomes the `data-se-<axis>` attribute and the key of a pick. */
|
|
59
|
+
readonly $type: TName;
|
|
60
|
+
/** Each value name and the semantic tokens it stands for. Two to five values. */
|
|
61
|
+
readonly values: TValues;
|
|
62
|
+
/** One of the value names. */
|
|
63
|
+
readonly default: keyof TValues & string;
|
|
64
|
+
readonly metadata: RegistrationMetadata;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Throws when an axis name is one a domain reserves.
|
|
68
|
+
*
|
|
69
|
+
* @remarks The one place the message lives, shared by the compiler and by {@link assertAxesNotReserved}.
|
|
70
|
+
*/
|
|
71
|
+
export declare function assertAxisNotReserved(axisName: string, reserved: ReadonlySet<string>): void;
|
|
72
|
+
/**
|
|
73
|
+
* Defines an appearance axis: one independent dimension of appearance with a small closed set of
|
|
74
|
+
* named values.
|
|
75
|
+
*
|
|
76
|
+
* @remarks
|
|
77
|
+
* Each value stands for a set of semantic CSS custom properties (`--se-space`, `--se-shadow`) that
|
|
78
|
+
* components read; components never read the axis value. A token names a role, not a component, so
|
|
79
|
+
* it means the same on every component that reads it. A value that sets a token to `initial`
|
|
80
|
+
* hands it back to the component's own fallback. Appearance only: structure is slot config or the grid.
|
|
81
|
+
*
|
|
82
|
+
* The axis carries a Standard Schema that accepts exactly its value names. Throws on an axis with
|
|
83
|
+
* a name that is not a lowercase identifier, fewer than 2 or more than 5 values, a value name that
|
|
84
|
+
* would break a selector, a token that is not a custom property or has an unsafe value, or a
|
|
85
|
+
* `default` that is not one of the values.
|
|
86
|
+
*/
|
|
87
|
+
export declare function defineAxis<const TName extends string, const TValues extends Readonly<Record<string, AppearanceTokens>>>(definition: AxisDefinition<TName, TValues>): AxisRegistration<TName, keyof TValues & string>;
|
|
88
|
+
/**
|
|
89
|
+
* The axes every layout theme starts from: `size` (compact, default, comfortable) and `surface`
|
|
90
|
+
* (flat, outlined, elevated).
|
|
91
|
+
*
|
|
92
|
+
* @remarks
|
|
93
|
+
* The tokens are renderer-neutral and name no host theme; `size` reads hooks an author sets (`--se-space-compact`,
|
|
94
|
+
* `--se-control-height-compact` and their `comfortable` twins), then the `--se-renderer-*` twin of each, which a renderer sets from its theme, then a neutral value. `size.default` and the background of
|
|
95
|
+
* `surface.elevated` are `initial`, which hands the token back to the component's own fallback, so
|
|
96
|
+
* a renderer's fallbacks, which it maps to its host theme, stay in force and `size: default`
|
|
97
|
+
* looks like no pick, also inside a `compact` form. Override an axis by listing another
|
|
98
|
+
* with the same `$type` after these: `createLayoutTheme({ appearance: [...builtInAxes, mine] })`.
|
|
99
|
+
*/
|
|
100
|
+
export declare const builtInAxes: readonly [AxisRegistration<"size", "default" | "compact" | "comfortable">, AxisRegistration<"surface", "flat" | "elevated" | "outlined">];
|
|
101
|
+
/** The value names of an axis registration. */
|
|
102
|
+
type AxisValueNames<TAxis> = TAxis extends AxisRegistration<string, infer V> ? V : never;
|
|
103
|
+
type Flatten<T> = {
|
|
104
|
+
[K in keyof T]: T[K] & string;
|
|
105
|
+
};
|
|
106
|
+
type AxesOfTuple<TAxes extends readonly AnyAxisRegistration[]> = TAxes extends readonly [
|
|
107
|
+
...infer Rest extends readonly AnyAxisRegistration[],
|
|
108
|
+
infer Last extends AnyAxisRegistration
|
|
109
|
+
] ? Omit<AxesOfTuple<Rest>, Last['$type']> & {
|
|
110
|
+
[K in Last['$type']]: AxisValueNames<Last>;
|
|
111
|
+
} : unknown;
|
|
112
|
+
/**
|
|
113
|
+
* Axis-to-value-union map of a theme: the axes a host lists in `appearance`, the last of a name winning.
|
|
114
|
+
*
|
|
115
|
+
* @remarks Typed authoring narrows a pick to these literals. `TAxes` should be a const-inferred list;
|
|
116
|
+
* a list that is not a tuple, or a member typed as a plain `AnyAxisRegistration` (name `string`),
|
|
117
|
+
* widens to any axis name and any value.
|
|
118
|
+
*/
|
|
119
|
+
export type ResolvedAppearanceAxes<TAxes extends readonly AnyAxisRegistration[] = typeof builtInAxes> = number extends TAxes['length'] ? Record<string, string> : Flatten<AxesOfTuple<TAxes>>;
|
|
120
|
+
/** Built-in axes and their values, as literal types, for typed authoring. */
|
|
121
|
+
export type BuiltInAppearanceAxes = ResolvedAppearanceAxes;
|
|
122
|
+
/** The axes an element or a recipe slot declares it supports. */
|
|
123
|
+
export type AppearanceAxisList = readonly string[];
|
|
124
|
+
/** The axes each slot of a recipe supports, keyed by slot name. */
|
|
125
|
+
export type SlotAppearanceAxes<TSlot extends PropertyKey = string> = {
|
|
126
|
+
[K in TSlot]?: AppearanceAxisList;
|
|
127
|
+
};
|
|
128
|
+
/** Authoring shape of a pick: any declared axis, restricted to its values. */
|
|
129
|
+
export type AppearanceInput<TAxes extends Record<string, string>> = {
|
|
130
|
+
readonly [A in keyof TAxes]?: TAxes[A];
|
|
131
|
+
};
|
|
132
|
+
/** A theme's compiled appearance vocabulary. */
|
|
133
|
+
export interface CompiledAppearance {
|
|
134
|
+
/** The axes, last registration of a `$type` winning, in first-registration order. */
|
|
135
|
+
readonly registry: AxisRegistry;
|
|
136
|
+
/** Axis name to its closed value list. */
|
|
137
|
+
readonly axes: Readonly<Record<string, readonly string[]>>;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The token rules of a compiled appearance, scoped to the layout theme with the given id.
|
|
141
|
+
*
|
|
142
|
+
* @remarks
|
|
143
|
+
* Every rule sits inside `:where()`, so it adds no specificity and an author's class always wins.
|
|
144
|
+
* Every grid and item carries `data-se-theme`, so a form of theme B inside a grid item of theme A
|
|
145
|
+
* has both themes above it; the nearest theme's rule must be the one that matches, whatever the
|
|
146
|
+
* order of the stylesheets. Empty when no value declares tokens. Two sets of rules say so:
|
|
147
|
+
*
|
|
148
|
+
* 1. Plain rules, which match an element that carries the theme and the pick together, or a
|
|
149
|
+
* descendant of the theme's root with no element of another theme between. They need only
|
|
150
|
+
* `:where()` and complex selectors in `:not()`, so they hold in server-rendered output in every
|
|
151
|
+
* browser the renderers support. They cannot say "no other theme between" for a theme re-entered
|
|
152
|
+
* below another theme (A in B in A): its descendants match no plain rule, so they inherit the
|
|
153
|
+
* custom properties of the nearest element that did.
|
|
154
|
+
* 2. `@scope` rules, emitted after the plain ones in one block: the theme's roots down to the nearest
|
|
155
|
+
* element of another theme. A browser without `@scope` drops the block and keeps the plain rules;
|
|
156
|
+
* one with it is exact, A in B in A included. About 1.1 KB per theme with the built-in axes.
|
|
157
|
+
*
|
|
158
|
+
* The `@scope` rules change one cascade detail: scope proximity outranks source order, and an
|
|
159
|
+
* unscoped rule is the farthest from any root. A zero-specificity author rule such as `:where(.x)`
|
|
160
|
+
* therefore loses to a token rule in a browser with `@scope`, where it won on order alone before;
|
|
161
|
+
* a class with any specificity still wins.
|
|
162
|
+
*/
|
|
163
|
+
export declare function getAppearanceCss(appearance: CompiledAppearance, themeId: string): string;
|
|
164
|
+
/**
|
|
165
|
+
* Compiles a list of axes into the theme's appearance vocabulary.
|
|
166
|
+
*
|
|
167
|
+
* @param axes - The axes of the theme; defaults to {@link builtInAxes}. A later axis with the same
|
|
168
|
+
* `$type` replaces the earlier one, so `[...builtInAxes, mine]` overrides.
|
|
169
|
+
*
|
|
170
|
+
* @remarks
|
|
171
|
+
* Stores the axes with `createRegistry`, so each needs a Standard Schema, and holds every winner to
|
|
172
|
+
* the rules {@link defineAxis} states. Throws on an invalid axis and on one named in `reservedNames`.
|
|
173
|
+
*/
|
|
174
|
+
export declare function compileAppearance(axes?: readonly AnyAxisRegistration[], compiler?: LayoutThemeCompilerOptions): CompiledAppearance;
|
|
175
|
+
/**
|
|
176
|
+
* The `data-se-<axis>` attributes for a resolved selection.
|
|
177
|
+
*
|
|
178
|
+
* @remarks A renderer spreads this on every element that carries a pick.
|
|
179
|
+
*/
|
|
180
|
+
export declare function getAppearanceAttributes(appearance: AppearanceSelection | undefined): Record<string, string>;
|
|
181
|
+
/**
|
|
182
|
+
* A child's picks laid over the picks it inherits: the child's value wins per axis.
|
|
183
|
+
*
|
|
184
|
+
* @remarks Pure merge; checking that the child's axes are valid is {@link checkAppearance}'s job.
|
|
185
|
+
*/
|
|
186
|
+
export declare function mergeAppearance(inherited: AppearanceSelection | undefined, own: AppearanceSelection | undefined): Record<string, string>;
|
|
187
|
+
/**
|
|
188
|
+
* Checks an authored pick against the vocabulary and, when given, the axes its owner supports.
|
|
189
|
+
*
|
|
190
|
+
* @param subject Names the owner in a message, for example `Element 'fieldSet'`.
|
|
191
|
+
* @param supported The axes the owner declares; an owner that declares none passes `[]`. Omit it for an owner that accepts every axis.
|
|
192
|
+
* @returns One issue per problem, with a path relative to the authored pick (`['appearance', axis]`), and the valid picks.
|
|
193
|
+
*/
|
|
194
|
+
export declare function checkAppearance(authored: unknown, options: {
|
|
195
|
+
axes: LayoutTheme['axes'];
|
|
196
|
+
subject: string;
|
|
197
|
+
supported?: readonly string[];
|
|
198
|
+
}): {
|
|
199
|
+
issues: LayoutIssue[];
|
|
200
|
+
appearance: Record<string, string>;
|
|
201
|
+
};
|
|
202
|
+
/** Keeps the axes an owner supports. An owner that declares none keeps none. */
|
|
203
|
+
export declare function pickSupportedAppearance(selection: AppearanceSelection, supported: readonly string[] | undefined): Record<string, string>;
|
|
204
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRegistry as $}from"@schema-engine/registry";import*as p from"zod/mini";var R=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,v=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,T=/[{};<]|\/\*/,g=2,f=5;function b(e,t){if(t.has(e))throw new Error(`Invalid appearance axis name '${e}': data-se-${e} is reserved by the renderer.`)}function x(e){let t=e.$type;if(!R.test(t))throw new Error(`Invalid appearance axis name '${t}': use lowercase letters, digits and hyphens, starting with a letter.`);let n=Object.entries(e.values);if(n.length<g||n.length>f)throw new Error(`Invalid appearance axis '${t}': an axis has ${g} to ${f} values, found ${n.length}. A raw value is a token override, not an axis value.`);if(!Object.hasOwn(e.values,e.default))throw new Error(`Invalid appearance axis '${t}': default '${e.default}' is not one of its values (${n.map(([s])=>s).join(", ")}).`);for(let[s,r]of n){if(!v.test(s))throw new Error(`Invalid appearance value '${s}' on axis '${t}': use letters, digits, hyphens and underscores.`);for(let[a,o]of Object.entries(r)){if(!a.startsWith("--")||a.length<3)throw new Error(`Invalid appearance token '${a}' on '${t}.${s}': tokens are CSS custom properties and start with '--'.`);if(T.test(String(o)))throw new Error(`Invalid appearance token value for '${a}' on '${t}.${s}'.`)}}}function y(e){let t={$type:e.$type,values:e.values,default:e.default,metadata:e.metadata,schema:p.enum(Object.keys(e.values)).check(p.describe(e.metadata.description??e.metadata.name))};return x(t),Object.freeze(t)}var w=y({$type:"size",metadata:{name:"Size",description:"How much room components take: spacing, type size, control height and readable width."},default:"default",values:{compact:{"--se-space":"var(--se-space-compact, var(--se-renderer-space-compact, 1rem))","--se-font-size":"0.875rem","--se-measure":"24rem","--se-control-height":"var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))"},default:{"--se-space":"initial","--se-font-size":"initial","--se-measure":"initial","--se-control-height":"initial"},comfortable:{"--se-space":"var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))","--se-font-size":"1.0625rem","--se-measure":"32rem","--se-control-height":"var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))"}}}),k=y({$type:"surface",metadata:{name:"Surface",description:"How a container sets itself apart: border, shadow and background."},default:"elevated",values:{flat:{"--se-border-width":"0","--se-shadow":"none","--se-surface-background":"initial"},outlined:{"--se-border-width":"1px","--se-shadow":"none","--se-surface-background":"initial"},elevated:{"--se-border-width":"initial","--se-shadow":"initial","--se-surface-background":"initial"}}}),j=[w,k];function V(e,t){let n=[],s=[],r=`[data-se-theme="${t}"]`,a=`[data-se-theme]:not(${r})`;for(let o of e.registry.all())for(let[i,d]of Object.entries(o.values)){let l=Object.entries(d).map(([m,h])=>`${m}:${h};`);if(l.length===0)continue;let u=`{${l.join("")}}`,c=`[data-se-${o.$type}="${i}"]`,A=`${r} ${c}:not(${a},${r} ${a} *)`;n.push(`:where(${r}${c},${A})${u}`),s.push(`:where(:scope${c},${c})${u}`)}return s.length===0?"":[...n,`@scope (${r}) to (${a}){${s.join("")}}`].join(`
|
|
2
|
+
`)}function z(e=j,t={}){let n=$("Axis",e),s=new Set(t.reservedNames);for(let r of n.all())x(r),b(r.$type,s);return Object.freeze({registry:n,axes:Object.freeze(Object.fromEntries(n.all().map(r=>[r.$type,Object.freeze(Object.keys(r.values))])))})}function E(e){let t={};for(let[n,s]of Object.entries(e??{}))t[`data-se-${n}`]=s;return t}function I(e,t){return{...e,...t}}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,t){let n=[],s={};if(e===void 0)return{issues:n,appearance:s};if(!O(e))return{issues:[{path:["appearance"],message:"Expected an object of axis names to values."}],appearance:s};let r=Object.keys(t.axes).join(", ");for(let[a,o]of Object.entries(e)){let i=Object.hasOwn(t.axes,a)?t.axes[a]:void 0;if(!i){n.push({path:["appearance",a],message:`Unknown axis '${a}'. Declared axes: ${r}.`});continue}if(t.supported!==void 0&&!t.supported.includes(a)){let d=t.supported.length>0?t.supported.join(", "):"(none)";n.push({path:["appearance",a],message:`${t.subject} does not support the axis '${a}'. Supported axes: ${d}.`});continue}if(typeof o!="string"){n.push({path:["appearance",a],message:`Expected one of ${i.join(", ")}.`});continue}if(!i.includes(o)){n.push({path:["appearance",a],message:`'${o}' is not a value of '${a}'. Allowed: ${i.join(", ")}.`});continue}s[a]=o}return{issues:n,appearance:s}}function N(e,t){let n={};for(let s of t??[]){let r=e[s];r!==void 0&&(n[s]=r)}return n}export{b as assertAxisNotReserved,j as builtInAxes,L as checkAppearance,z as compileAppearance,y as defineAxis,E as getAppearanceAttributes,V as getAppearanceCss,I as mergeAppearance,N as pickSupportedAppearance};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/appearance.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n\ttype RegistrationMetadata,\n} from '@schema-engine/registry';\nimport * as z from 'zod/mini';\nimport type { LayoutIssue } from './layout-issue';\nimport type { LayoutTheme, LayoutThemeCompilerOptions } from './layout-theme';\n\n/**\n * Appearance axes a document picks values on and renderers emit as data attributes.\n *\n * @remarks\n * An axis is one independent dimension of appearance, with two to five named values. Each value\n * stands for a set of semantic CSS tokens, which components read; components never read an axis\n * value. The theme declares the axes ({@link defineAxis}, stored in a registry), a registration\n * declares which axes it responds to, and a document picks values that pass down.\n *\n * A domain checks the pick against the vocabulary and the owner's declared axes\n * ({@link checkAppearance}), merges it with the pick it inherits ({@link mergeAppearance}), and a\n * renderer emits the result as `data-se-<axis>=\"<value>\"` ({@link getAppearanceAttributes}).\n * Walking the document tree to inherit picks belongs to the domain, because only it knows the\n * tree's shape.\n *\n * Compile once, where the theme is built ({@link createLayoutTheme} does, with the grid). Token rules are\n * emitted inside `:where()`, so they add no specificity and an author's `className` always wins; they\n * are scoped to the theme by `data-se-theme` and the nearest theme above an element wins, so two themes\n * with different tokens cannot overwrite each other ({@link getAppearanceCss} has the details).\n */\n\n/** Custom properties a value stands for, keyed `--name`. */\nexport type AppearanceTokens = Readonly<Record<`--${string}`, string | number>>;\n\n/** A pick of one value per axis. */\nexport type AppearanceSelection = Readonly<Record<string, string>>;\n\n/**\n * An appearance axis, stored in a registry like every other registration.\n *\n * @remarks\n * `schema` is a Standard Schema that accepts exactly the value names, which satisfies the\n * registry's build check and is what a catalog or JSON Schema export lists. {@link defineAxis}\n * produces it.\n */\nexport interface AxisRegistration<\n\tTName extends string = string,\n\tTValue extends string = string,\n> extends BaseRegistration<unknown, RegistrationMetadata> {\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. */\n\treadonly values: Readonly<Record<TValue, AppearanceTokens>>;\n\t/**\n\t * The value that stands for no pick.\n\t *\n\t * @remarks\n\t * A component's own CSS fallbacks are the look of this value, so a document that picks it looks\n\t * like one that picks nothing. To make that true under an inherited pick, a default value that\n\t * leaves the tokens to the component sets them to `initial`: a custom property set to `initial`\n\t * makes `var(--token, fallback)` use its fallback, so a step that picks `default` inside a\n\t * `compact` form undoes the compact tokens.\n\t */\n\treadonly default: TValue;\n}\n\n/** Any axis registration, whatever its name and values. */\nexport type AnyAxisRegistration = AxisRegistration;\n\n/** A registry of axes, as {@link createLayoutTheme} builds it. */\nexport type AxisRegistry = ReadOnlyRegistry<AnyAxisRegistration>;\n\n/** Input to {@link defineAxis}. */\nexport interface AxisDefinition<TName extends string, TValues extends Readonly<Record<string, AppearanceTokens>>> {\n\t/** The axis name, which becomes the `data-se-<axis>` attribute and the key of a pick. */\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. Two to five values. */\n\treadonly values: TValues;\n\t/** One of the value names. */\n\treadonly default: keyof TValues & string;\n\treadonly metadata: RegistrationMetadata;\n}\n\nconst AXIS_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst VALUE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\nconst UNSAFE_TOKEN_VALUE = /[{};<]|\\/\\*/;\nconst MIN_AXIS_VALUES = 2;\nconst MAX_AXIS_VALUES = 5;\n\n/**\n * Throws when an axis name is one a domain reserves.\n *\n * @remarks The one place the message lives, shared by the compiler and by {@link assertAxesNotReserved}.\n */\nexport function assertAxisNotReserved(axisName: string, reserved: ReadonlySet<string>): void {\n\tif (reserved.has(axisName)) {\n\t\tthrow new Error(`Invalid appearance axis name '${axisName}': data-se-${axisName} is reserved by the renderer.`);\n\t}\n}\n\n/**\n * Throws when an axis is not a usable one: a bad name, fewer than two or more than five values, a\n * value that would break a selector, a token that is not a custom property, or a `default` that is\n * not a value.\n *\n * @remarks\n * Axis names become `data-se-<axis>` attribute names and values go into attribute selectors, so\n * both are restricted to plain identifiers. {@link defineAxis} and the compiler both run this, so an\n * object that did not come from `defineAxis` is held to the same rules.\n */\nfunction assertValidAxis(axis: AnyAxisRegistration): void {\n\tconst name = axis.$type;\n\tif (!AXIS_NAME.test(name)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis name '${name}': use lowercase letters, digits and hyphens, starting with a letter.`,\n\t\t);\n\t}\n\tconst entries = Object.entries(axis.values);\n\tif (entries.length < MIN_AXIS_VALUES || entries.length > MAX_AXIS_VALUES) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': an axis has ${MIN_AXIS_VALUES} to ${MAX_AXIS_VALUES} values, found ${entries.length}. A raw value is a token override, not an axis value.`,\n\t\t);\n\t}\n\tif (!Object.hasOwn(axis.values, axis.default)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': default '${axis.default}' is not one of its values (${entries.map(([value]) => value).join(', ')}).`,\n\t\t);\n\t}\n\tfor (const [value, tokens] of entries) {\n\t\tif (!VALUE_NAME.test(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid appearance value '${value}' on axis '${name}': use letters, digits, hyphens and underscores.`,\n\t\t\t);\n\t\t}\n\t\tfor (const [token, tokenValue] of Object.entries(tokens)) {\n\t\t\tif (!token.startsWith('--') || token.length < 3) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid appearance token '${token}' on '${name}.${value}': tokens are CSS custom properties and start with '--'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (UNSAFE_TOKEN_VALUE.test(String(tokenValue))) {\n\t\t\t\tthrow new Error(`Invalid appearance token value for '${token}' on '${name}.${value}'.`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Defines an appearance axis: one independent dimension of appearance with a small closed set of\n * named values.\n *\n * @remarks\n * Each value stands for a set of semantic CSS custom properties (`--se-space`, `--se-shadow`) that\n * components read; components never read the axis value. A token names a role, not a component, so\n * it means the same on every component that reads it. A value that sets a token to `initial`\n * hands it back to the component's own fallback. Appearance only: structure is slot config or the grid.\n *\n * The axis carries a Standard Schema that accepts exactly its value names. Throws on an axis with\n * a name that is not a lowercase identifier, fewer than 2 or more than 5 values, a value name that\n * would break a selector, a token that is not a custom property or has an unsafe value, or a\n * `default` that is not one of the values.\n */\nexport function defineAxis<\n\tconst TName extends string,\n\tconst TValues extends Readonly<Record<string, AppearanceTokens>>,\n>(definition: AxisDefinition<TName, TValues>): AxisRegistration<TName, keyof TValues & string> {\n\tconst axis: AxisRegistration<TName, keyof TValues & string> = {\n\t\t$type: definition.$type,\n\t\tvalues: definition.values,\n\t\tdefault: definition.default,\n\t\tmetadata: definition.metadata,\n\t\tschema: z\n\t\t\t.enum(Object.keys(definition.values) as [string, ...string[]])\n\t\t\t.check(z.describe(definition.metadata.description ?? definition.metadata.name)),\n\t};\n\tassertValidAxis(axis);\n\treturn Object.freeze(axis);\n}\n\nconst sizeAxis = defineAxis({\n\t$type: 'size',\n\tmetadata: {\n\t\tname: 'Size',\n\t\tdescription: 'How much room components take: spacing, type size, control height and readable width.',\n\t},\n\tdefault: 'default',\n\tvalues: {\n\t\tcompact: {\n\t\t\t'--se-space': 'var(--se-space-compact, var(--se-renderer-space-compact, 1rem))',\n\t\t\t'--se-font-size': '0.875rem',\n\t\t\t'--se-measure': '24rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))',\n\t\t},\n\t\tdefault: {\n\t\t\t'--se-space': 'initial',\n\t\t\t'--se-font-size': 'initial',\n\t\t\t'--se-measure': 'initial',\n\t\t\t'--se-control-height': 'initial',\n\t\t},\n\t\tcomfortable: {\n\t\t\t'--se-space': 'var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))',\n\t\t\t'--se-font-size': '1.0625rem',\n\t\t\t'--se-measure': '32rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))',\n\t\t},\n\t},\n});\n\nconst surfaceAxis = defineAxis({\n\t$type: 'surface',\n\tmetadata: {\n\t\tname: 'Surface',\n\t\tdescription: 'How a container sets itself apart: border, shadow and background.',\n\t},\n\tdefault: 'elevated',\n\tvalues: {\n\t\tflat: {\n\t\t\t'--se-border-width': '0',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\toutlined: {\n\t\t\t'--se-border-width': '1px',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\televated: {\n\t\t\t'--se-border-width': 'initial',\n\t\t\t'--se-shadow': 'initial',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t},\n});\n\n/**\n * The axes every layout theme starts from: `size` (compact, default, comfortable) and `surface`\n * (flat, outlined, elevated).\n *\n * @remarks\n * The tokens are renderer-neutral and name no host theme; `size` reads hooks an author sets (`--se-space-compact`,\n * `--se-control-height-compact` and their `comfortable` twins), then the `--se-renderer-*` twin of each, which a renderer sets from its theme, then a neutral value. `size.default` and the background of\n * `surface.elevated` are `initial`, which hands the token back to the component's own fallback, so\n * a renderer's fallbacks, which it maps to its host theme, stay in force and `size: default`\n * looks like no pick, also inside a `compact` form. Override an axis by listing another\n * with the same `$type` after these: `createLayoutTheme({ appearance: [...builtInAxes, mine] })`.\n */\nexport const builtInAxes = [sizeAxis, surfaceAxis] as const;\n\n/** The value names of an axis registration. */\ntype AxisValueNames<TAxis> = TAxis extends AxisRegistration<string, infer V> ? V : never;\n\ntype Flatten<T> = { [K in keyof T]: T[K] & string };\n\ntype AxesOfTuple<TAxes extends readonly AnyAxisRegistration[]> = TAxes extends readonly [\n\t...infer Rest extends readonly AnyAxisRegistration[],\n\tinfer Last extends AnyAxisRegistration,\n]\n\t? Omit<AxesOfTuple<Rest>, Last['$type']> & { [K in Last['$type']]: AxisValueNames<Last> }\n\t: unknown;\n\n/**\n * Axis-to-value-union map of a theme: the axes a host lists in `appearance`, the last of a name winning.\n *\n * @remarks Typed authoring narrows a pick to these literals. `TAxes` should be a const-inferred list;\n * a list that is not a tuple, or a member typed as a plain `AnyAxisRegistration` (name `string`),\n * widens to any axis name and any value.\n */\nexport type ResolvedAppearanceAxes<TAxes extends readonly AnyAxisRegistration[] = typeof builtInAxes> =\n\tnumber extends TAxes['length'] ? Record<string, string> : Flatten<AxesOfTuple<TAxes>>;\n\n/** Built-in axes and their values, as literal types, for typed authoring. */\nexport type BuiltInAppearanceAxes = ResolvedAppearanceAxes;\n\n/** The axes an element or a recipe slot declares it supports. */\nexport type AppearanceAxisList = readonly string[];\n\n/** The axes each slot of a recipe supports, keyed by slot name. */\nexport type SlotAppearanceAxes<TSlot extends PropertyKey = string> = { [K in TSlot]?: AppearanceAxisList };\n\n/** Authoring shape of a pick: any declared axis, restricted to its values. */\nexport type AppearanceInput<TAxes extends Record<string, string>> = { readonly [A in keyof TAxes]?: TAxes[A] };\n\n/** A theme's compiled appearance vocabulary. */\nexport interface CompiledAppearance {\n\t/** The axes, last registration of a `$type` winning, in first-registration order. */\n\treadonly registry: AxisRegistry;\n\t/** Axis name to its closed value list. */\n\treadonly axes: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The token rules of a compiled appearance, scoped to the layout theme with the given id.\n *\n * @remarks\n * Every rule sits inside `:where()`, so it adds no specificity and an author's class always wins.\n * Every grid and item carries `data-se-theme`, so a form of theme B inside a grid item of theme A\n * has both themes above it; the nearest theme's rule must be the one that matches, whatever the\n * order of the stylesheets. Empty when no value declares tokens. Two sets of rules say so:\n *\n * 1. Plain rules, which match an element that carries the theme and the pick together, or a\n * descendant of the theme's root with no element of another theme between. They need only\n * `:where()` and complex selectors in `:not()`, so they hold in server-rendered output in every\n * browser the renderers support. They cannot say \"no other theme between\" for a theme re-entered\n * below another theme (A in B in A): its descendants match no plain rule, so they inherit the\n * custom properties of the nearest element that did.\n * 2. `@scope` rules, emitted after the plain ones in one block: the theme's roots down to the nearest\n * element of another theme. A browser without `@scope` drops the block and keeps the plain rules;\n * one with it is exact, A in B in A included. About 1.1 KB per theme with the built-in axes.\n *\n * The `@scope` rules change one cascade detail: scope proximity outranks source order, and an\n * unscoped rule is the farthest from any root. A zero-specificity author rule such as `:where(.x)`\n * therefore loses to a token rule in a browser with `@scope`, where it won on order alone before;\n * a class with any specificity still wins.\n */\nexport function getAppearanceCss(appearance: CompiledAppearance, themeId: string): string {\n\tconst plain: string[] = [];\n\tconst scoped: string[] = [];\n\tconst scope = `[data-se-theme=\"${themeId}\"]`;\n\tconst foreign = `[data-se-theme]:not(${scope})`;\n\tfor (const axis of appearance.registry.all()) {\n\t\tfor (const [value, tokens] of Object.entries(axis.values)) {\n\t\t\tconst declarations = Object.entries(tokens).map(([token, tokenValue]) => `${token}:${tokenValue};`);\n\t\t\tif (declarations.length === 0) continue;\n\t\t\tconst block = `{${declarations.join('')}}`;\n\t\t\tconst match = `[data-se-${axis.$type}=\"${value}\"]`;\n\t\t\tconst descendant = `${scope} ${match}:not(${foreign},${scope} ${foreign} *)`;\n\t\t\tplain.push(`:where(${scope}${match},${descendant})${block}`);\n\t\t\tscoped.push(`:where(:scope${match},${match})${block}`);\n\t\t}\n\t}\n\tif (scoped.length === 0) return '';\n\treturn [...plain, `@scope (${scope}) to (${foreign}){${scoped.join('')}}`].join('\\n');\n}\n\n/**\n * Compiles a list of axes into the theme's appearance vocabulary.\n *\n * @param axes - The axes of the theme; defaults to {@link builtInAxes}. A later axis with the same\n * `$type` replaces the earlier one, so `[...builtInAxes, mine]` overrides.\n *\n * @remarks\n * Stores the axes with `createRegistry`, so each needs a Standard Schema, and holds every winner to\n * the rules {@link defineAxis} states. Throws on an invalid axis and on one named in `reservedNames`.\n */\nexport function compileAppearance(\n\taxes: readonly AnyAxisRegistration[] = builtInAxes,\n\tcompiler: LayoutThemeCompilerOptions = {},\n): CompiledAppearance {\n\tconst registry = createRegistry<AnyAxisRegistration>('Axis', axes);\n\tconst reserved = new Set(compiler.reservedNames);\n\tfor (const axis of registry.all()) {\n\t\tassertValidAxis(axis);\n\t\tassertAxisNotReserved(axis.$type, reserved);\n\t}\n\treturn Object.freeze({\n\t\tregistry,\n\t\taxes: Object.freeze(\n\t\t\tObject.fromEntries(registry.all().map((axis) => [axis.$type, Object.freeze(Object.keys(axis.values))])),\n\t\t),\n\t});\n}\n\n/**\n * The `data-se-<axis>` attributes for a resolved selection.\n *\n * @remarks A renderer spreads this on every element that carries a pick.\n */\nexport function getAppearanceAttributes(appearance: AppearanceSelection | undefined): Record<string, string> {\n\tconst attributes: Record<string, string> = {};\n\tfor (const [axis, value] of Object.entries(appearance ?? {})) attributes[`data-se-${axis}`] = value;\n\treturn attributes;\n}\n\n/**\n * A child's picks laid over the picks it inherits: the child's value wins per axis.\n *\n * @remarks Pure merge; checking that the child's axes are valid is {@link checkAppearance}'s job.\n */\nexport function mergeAppearance(\n\tinherited: AppearanceSelection | undefined,\n\town: AppearanceSelection | undefined,\n): Record<string, string> {\n\treturn { ...inherited, ...own };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Checks an authored pick against the vocabulary and, when given, the axes its owner supports.\n *\n * @param subject Names the owner in a message, for example `Element 'fieldSet'`.\n * @param supported The axes the owner declares; an owner that declares none passes `[]`. Omit it for an owner that accepts every axis.\n * @returns One issue per problem, with a path relative to the authored pick (`['appearance', axis]`), and the valid picks.\n */\nexport function checkAppearance(\n\tauthored: unknown,\n\toptions: { axes: LayoutTheme['axes']; subject: string; supported?: readonly string[] },\n): { issues: LayoutIssue[]; appearance: Record<string, string> } {\n\tconst issues: LayoutIssue[] = [];\n\tconst appearance: Record<string, string> = {};\n\tif (authored === undefined) return { issues, appearance };\n\tif (!isRecord(authored)) {\n\t\treturn {\n\t\t\tissues: [{ path: ['appearance'], message: 'Expected an object of axis names to values.' }],\n\t\t\tappearance,\n\t\t};\n\t}\n\tconst declared = Object.keys(options.axes).join(', ');\n\tfor (const [axis, value] of Object.entries(authored)) {\n\t\tconst values = Object.hasOwn(options.axes, axis) ? options.axes[axis] : undefined;\n\t\tif (!values) {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Unknown axis '${axis}'. Declared axes: ${declared}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.supported !== undefined && !options.supported.includes(axis)) {\n\t\t\tconst supported = options.supported.length > 0 ? options.supported.join(', ') : '(none)';\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `${options.subject} does not support the axis '${axis}'. Supported axes: ${supported}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Expected one of ${values.join(', ')}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!values.includes(value)) {\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `'${value}' is not a value of '${axis}'. Allowed: ${values.join(', ')}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tappearance[axis] = value;\n\t}\n\treturn { issues, appearance };\n}\n\n/** Keeps the axes an owner supports. An owner that declares none keeps none. */\nexport function pickSupportedAppearance(\n\tselection: AppearanceSelection,\n\tsupported: readonly string[] | undefined,\n): Record<string, string> {\n\tconst picked: Record<string, string> = {};\n\tfor (const axis of supported ?? []) {\n\t\tconst value = selection[axis];\n\t\tif (value !== undefined) picked[axis] = value;\n\t}\n\treturn picked;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OACC,kBAAAA,MAIM,0BACP,UAAYC,MAAO,WA4EnB,IAAMC,EAAY,kCACZC,EAAa,8BACbC,EAAqB,cACrBC,EAAkB,EAClBC,EAAkB,EAOjB,SAASC,EAAsBC,EAAkBC,EAAqC,CAC5F,GAAIA,EAAS,IAAID,CAAQ,EACxB,MAAM,IAAI,MAAM,iCAAiCA,CAAQ,cAAcA,CAAQ,+BAA+B,CAEhH,CAYA,SAASE,EAAgBC,EAAiC,CACzD,IAAMC,EAAOD,EAAK,MAClB,GAAI,CAACT,EAAU,KAAKU,CAAI,EACv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,EACfC,EACAF,EACyB,CACzB,IAAMG,EAAiC,CAAC,EACxC,QAAW1C,KAAQuC,GAAa,CAAC,EAAG,CACnC,IAAMpC,EAAQsC,EAAUzC,CAAI,EACxBG,IAAU,SAAWuC,EAAO1C,CAAI,EAAIG,EACzC,CACA,OAAOuC,CACR",
|
|
6
|
+
"names": ["createRegistry", "z", "AXIS_NAME", "VALUE_NAME", "UNSAFE_TOKEN_VALUE", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "assertAxisNotReserved", "axisName", "reserved", "assertValidAxis", "axis", "name", "entries", "value", "tokens", "token", "tokenValue", "defineAxis", "definition", "sizeAxis", "surfaceAxis", "builtInAxes", "getAppearanceCss", "appearance", "themeId", "plain", "scoped", "scope", "foreign", "declarations", "block", "match", "descendant", "compileAppearance", "axes", "compiler", "registry", "getAppearanceAttributes", "attributes", "mergeAppearance", "inherited", "own", "isRecord", "checkAppearance", "authored", "options", "issues", "declared", "values", "supported", "pickSupportedAppearance", "selection", "picked"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `T` with every property, array and nested object read-only; functions are kept as they are.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Domain-free on purpose, so modules that must not depend on a domain's config (the
|
|
6
|
+
* grid helpers) can accept frozen input.
|
|
7
|
+
*/
|
|
8
|
+
export type DeepReadonly<T> = T extends (...args: never[]) => unknown ? T : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
|
|
9
|
+
readonly [K in keyof T]: DeepReadonly<T[K]>;
|
|
10
|
+
} : T;
|
|
File without changes
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { GridOffsetName, GridWidthName } from '../schemas/grid.js';
|
|
2
|
+
import type { LayoutIssue } from './layout-issue';
|
|
3
|
+
/**
|
|
4
|
+
* Reads of an element's grid placement shared by the stylesheet emitter and
|
|
5
|
+
* validation, so the cascade the author is checked against is the one emitted.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Elements arrive as `unknown` because they are read before, or without, a
|
|
9
|
+
* registered schema narrowing them: a registration may declare `grid` loosely.
|
|
10
|
+
*/
|
|
11
|
+
export declare const BREAKPOINT_ORDER: readonly ["sm", "md", "lg", "xl", "2xl"];
|
|
12
|
+
/** Named breakpoint tokens. Thresholds are configured on the layout theme's `grid` option. */
|
|
13
|
+
export type GridBreakpointToken = (typeof BREAKPOINT_ORDER)[number];
|
|
14
|
+
export type CascadeSlot = 'default' | GridBreakpointToken;
|
|
15
|
+
/** Every slot of the cascade, narrowest first. */
|
|
16
|
+
export declare const CASCADE_SLOTS: readonly CascadeSlot[];
|
|
17
|
+
/** Tracks a grid has once its items use named widths. */
|
|
18
|
+
export declare const WIDTH_TRACKS = 12;
|
|
19
|
+
export declare const WIDTH_SPANS: Readonly<Record<GridWidthName, number>>;
|
|
20
|
+
/**
|
|
21
|
+
* Grid keys that define the template, and so cannot meet named widths.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* Typed against the breakpoint schema so a renamed key fails to compile here.
|
|
25
|
+
*/
|
|
26
|
+
export declare const GRID_TEMPLATE_KEYS: readonly ["columns", "minColumnWidth"];
|
|
27
|
+
/** The width and offset an item has authored so far, carried through the cascade. */
|
|
28
|
+
export interface NamedPlacement {
|
|
29
|
+
width?: GridWidthName;
|
|
30
|
+
offset?: GridOffsetName;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* An element's grid entries in cascade order: the top level, `responsive.default`,
|
|
34
|
+
* then each breakpoint that is set.
|
|
35
|
+
*/
|
|
36
|
+
export declare function elementGridSlots(element: unknown): Array<{
|
|
37
|
+
slot: CascadeSlot;
|
|
38
|
+
entry: Record<string, unknown>;
|
|
39
|
+
}>;
|
|
40
|
+
/** Keys an element's `grid` config sets to a value, at the top level or in any breakpoint. */
|
|
41
|
+
export declare function elementGridKeys(element: unknown): ReadonlySet<string>;
|
|
42
|
+
export declare function elementUsesGridWidths(element: unknown): boolean;
|
|
43
|
+
export declare function usesGridWidths(elements: readonly unknown[]): boolean;
|
|
44
|
+
/** Updates `carried` with the width and offset a slot authored; the other keeps its earlier value. */
|
|
45
|
+
export declare function carryNamedPlacement(carried: NamedPlacement, entry: NamedPlacement): void;
|
|
46
|
+
/**
|
|
47
|
+
* The first slot where an element's offset and width together pass the grid's
|
|
48
|
+
* tracks, with the tracks they span, or `undefined` when none does.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* Follows the same carry-over as emission: a slot that sets one of the pair is
|
|
52
|
+
* checked against the other as the narrower slots left it, so two slots that
|
|
53
|
+
* each look valid can still overflow together.
|
|
54
|
+
*/
|
|
55
|
+
export declare function namedPlacementOverflow(element: unknown): {
|
|
56
|
+
slot: CascadeSlot;
|
|
57
|
+
tracks: number;
|
|
58
|
+
} | undefined;
|
|
59
|
+
/** The cells of each row of a template; `.` marks an empty cell. */
|
|
60
|
+
export type GridAreaRows = readonly (readonly string[])[];
|
|
61
|
+
/** Templates by the slot that sets them. */
|
|
62
|
+
export type GridAreaTemplates = Partial<Record<CascadeSlot, GridAreaRows>>;
|
|
63
|
+
/**
|
|
64
|
+
* The templates a grid's `areas` sets, by slot. An array is the `default` template.
|
|
65
|
+
*
|
|
66
|
+
* @remarks
|
|
67
|
+
* A run of dots is one empty cell, normalised to a single `.`, so a template
|
|
68
|
+
* compares and emits the same however the author spaced it.
|
|
69
|
+
*/
|
|
70
|
+
export declare function gridAreaTemplates(grid: unknown): GridAreaTemplates;
|
|
71
|
+
/** Whether a grid draws its layout with `areas`. */
|
|
72
|
+
export declare function gridUsesAreas(grid: unknown): boolean;
|
|
73
|
+
/** Area names a template uses, in order of first appearance. */
|
|
74
|
+
export declare function areaNames(rows: GridAreaRows): string[];
|
|
75
|
+
/** The `grid-template-areas` value for a template: one quoted string per row. */
|
|
76
|
+
export declare function areasTemplateValue(rows: GridAreaRows): string;
|
|
77
|
+
/**
|
|
78
|
+
* The area an element authored at each slot it sets one. Within a slot,
|
|
79
|
+
* `responsive.default` beats the top level, as in emission.
|
|
80
|
+
*/
|
|
81
|
+
export declare function elementAreaSlots(element: unknown): Partial<Record<CascadeSlot, string>>;
|
|
82
|
+
/** Whether an element hides itself at each slot it sets `hidden`, in cascade order within a slot. */
|
|
83
|
+
export declare function elementHiddenSlots(element: unknown): Partial<Record<CascadeSlot, boolean>>;
|
|
84
|
+
/**
|
|
85
|
+
* What each slot resolves to: the value set at that slot, else the last one a
|
|
86
|
+
* narrower slot set.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* Emission falls back through narrower slots in the stylesheet, so validation
|
|
90
|
+
* reads templates and areas the same way to check what a viewport gets.
|
|
91
|
+
*/
|
|
92
|
+
export declare function cascadeValues<T>(authored: Partial<Record<CascadeSlot, T>>): Array<{
|
|
93
|
+
slot: CascadeSlot;
|
|
94
|
+
value: T | undefined;
|
|
95
|
+
}>;
|
|
96
|
+
/**
|
|
97
|
+
* Why CSS would drop a template: rows of unequal length, or an area whose cells
|
|
98
|
+
* do not fill a rectangle.
|
|
99
|
+
*
|
|
100
|
+
* @param grid A grid config; one that sets no `areas` has no issue.
|
|
101
|
+
*
|
|
102
|
+
* @remarks
|
|
103
|
+
* Each issue's `path` is relative to the grid: `['areas']` for the array form of the default
|
|
104
|
+
* template, else `['areas', slot]`. Rows of unequal length stop the check for that template, as no
|
|
105
|
+
* area can be located in a ragged one.
|
|
106
|
+
*/
|
|
107
|
+
export declare function areaTemplateIssues(grid: unknown): LayoutIssue[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=["sm","md","lg","xl","2xl"],f=["default",...g],R=12,m={full:12,"three-quarters":9,"two-thirds":8,half:6,third:4,quarter:3},P=["columns","minColumnWidth"];function i(e){return typeof e=="object"&&e!==null}function l(e){if(!i(e)||!i(e.grid))return[];let t=e.grid,n=[{slot:"default",entry:t}],o=t.responsive;if(!i(o))return n;for(let r of f){let s=o[r];i(s)&&n.push({slot:r,entry:s})}return n}function k(e){let t=new Set;for(let{entry:n}of l(e))for(let[o,r]of Object.entries(n))o!=="responsive"&&r!==void 0&&t.add(o);return t}function x(e){let t=k(e);return t.has("width")||t.has("offset")}function b(e){return e.some(x)}function A(e,t){e.width=t.width??e.width,e.offset=t.offset??e.offset}function N(e){let t={};for(let{slot:n,entry:o}of l(e)){if(o.width===void 0&&o.offset===void 0||(A(t,o),t.width===void 0||t.offset===void 0))continue;let r=(m[t.width]??0)+(m[t.offset]??0);if(r>R)return{slot:n,tracks:r}}}var h=".";function S(e){return typeof e!="string"?[]:e.trim().split(/\s+/).filter(Boolean).map(t=>/^\.+$/.test(t)?h:t)}function p(e){return Array.isArray(e)?e.map(S):void 0}function y(e){if(!i(e)||e.areas===void 0)return{};if(Array.isArray(e.areas)){let n=p(e.areas);return n?{default:n}:{}}if(!i(e.areas))return{};let t={};for(let n of f){let o=p(e.areas[n]);o&&(t[n]=o)}return t}function E(e){return Object.keys(y(e)).length>0}function G(e){let t=new Set;for(let n of e)for(let o of n)o!==h&&t.add(o);return[...t]}function I(e){return e.map(t=>`"${t.join(" ")}"`).join(" ")}function O(e){let t={};for(let{slot:n,entry:o}of l(e))typeof o.area=="string"&&(t[n]=o.area);return t}function v(e){let t={};for(let{slot:n,entry:o}of l(e))typeof o.hidden=="boolean"&&(t[n]=o.hidden);return t}function W(e){let t;return f.map(n=>(t=e[n]??t,{slot:n,value:t}))}function C(e){return`${e} ${e===1?"cell":"cells"}`}function T(e,t){let n=[];e.forEach((a,c)=>a.forEach((d,w)=>{d===t&&n.push([c,w])}));let o=n.map(([a])=>a),r=n.map(([,a])=>a),s=Math.max(...o)-Math.min(...o)+1,u=Math.max(...r)-Math.min(...r)+1;return s*u===n.length}function _(e){let t=y(e),n=i(e)&&Array.isArray(e.areas),o=[];for(let r of f){let s=t[r];if(!s)continue;let u=n?["areas"]:["areas",r],a=s[0]?.length??0,c=s.findIndex(d=>d.length!==a);if(c!==-1){o.push({path:u,message:`row ${c+1} has ${C(s[c]?.length??0)} but row 1 has ${a}.`});continue}for(let d of G(s))T(s,d)||o.push({path:u,message:`area '${d}' is not rectangular; CSS drops the whole template unless every area fills a rectangle.`})}return o}export{g as BREAKPOINT_ORDER,f as CASCADE_SLOTS,P as GRID_TEMPLATE_KEYS,m as WIDTH_SPANS,R as WIDTH_TRACKS,G as areaNames,_ as areaTemplateIssues,I as areasTemplateValue,A as carryNamedPlacement,W as cascadeValues,O as elementAreaSlots,k as elementGridKeys,l as elementGridSlots,v as elementHiddenSlots,x as elementUsesGridWidths,y as gridAreaTemplates,E as gridUsesAreas,N as namedPlacementOverflow,b as usesGridWidths};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/grid-placement.ts"],
|
|
4
|
+
"sourcesContent": ["import type { GridBreakpointConfig, GridOffsetName, GridWidthName } from '@/schemas/grid';\nimport type { LayoutIssue } from './layout-issue';\n\n/**\n * Reads of an element's grid placement shared by the stylesheet emitter and\n * validation, so the cascade the author is checked against is the one emitted.\n *\n * @remarks\n * Elements arrive as `unknown` because they are read before, or without, a\n * registered schema narrowing them: a registration may declare `grid` loosely.\n */\n\nexport const BREAKPOINT_ORDER = ['sm', 'md', 'lg', 'xl', '2xl'] as const;\n\n/** Named breakpoint tokens. Thresholds are configured on the layout theme's `grid` option. */\nexport type GridBreakpointToken = (typeof BREAKPOINT_ORDER)[number];\n\nexport type CascadeSlot = 'default' | GridBreakpointToken;\n\n/** Every slot of the cascade, narrowest first. */\nexport const CASCADE_SLOTS: readonly CascadeSlot[] = ['default', ...BREAKPOINT_ORDER];\n\n/** Tracks a grid has once its items use named widths. */\nexport const WIDTH_TRACKS = 12;\n\nexport const WIDTH_SPANS: Readonly<Record<GridWidthName, number>> = {\n\tfull: 12,\n\t'three-quarters': 9,\n\t'two-thirds': 8,\n\thalf: 6,\n\tthird: 4,\n\tquarter: 3,\n};\n\n/**\n * Grid keys that define the template, and so cannot meet named widths.\n *\n * @remarks\n * Typed against the breakpoint schema so a renamed key fails to compile here.\n */\nexport const GRID_TEMPLATE_KEYS = [\n\t'columns',\n\t'minColumnWidth',\n] as const satisfies readonly (keyof GridBreakpointConfig)[];\n\n/** The width and offset an item has authored so far, carried through the cascade. */\nexport interface NamedPlacement {\n\twidth?: GridWidthName;\n\toffset?: GridOffsetName;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\n/**\n * An element's grid entries in cascade order: the top level, `responsive.default`,\n * then each breakpoint that is set.\n */\nexport function elementGridSlots(element: unknown): Array<{ slot: CascadeSlot; entry: Record<string, unknown> }> {\n\tif (!isRecord(element) || !isRecord(element.grid)) return [];\n\tconst grid = element.grid;\n\tconst slots: Array<{ slot: CascadeSlot; entry: Record<string, unknown> }> = [{ slot: 'default', entry: grid }];\n\tconst responsive = grid.responsive;\n\tif (!isRecord(responsive)) return slots;\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst entry = responsive[slot];\n\t\tif (isRecord(entry)) slots.push({ slot, entry });\n\t}\n\treturn slots;\n}\n\n/** Keys an element's `grid` config sets to a value, at the top level or in any breakpoint. */\nexport function elementGridKeys(element: unknown): ReadonlySet<string> {\n\tconst keys = new Set<string>();\n\tfor (const { entry } of elementGridSlots(element)) {\n\t\tfor (const [key, value] of Object.entries(entry)) {\n\t\t\tif (key !== 'responsive' && value !== undefined) keys.add(key);\n\t\t}\n\t}\n\treturn keys;\n}\n\nexport function elementUsesGridWidths(element: unknown): boolean {\n\tconst keys = elementGridKeys(element);\n\treturn keys.has('width') || keys.has('offset');\n}\n\nexport function usesGridWidths(elements: readonly unknown[]): boolean {\n\treturn elements.some(elementUsesGridWidths);\n}\n\n/** Updates `carried` with the width and offset a slot authored; the other keeps its earlier value. */\nexport function carryNamedPlacement(carried: NamedPlacement, entry: NamedPlacement): void {\n\tcarried.width = entry.width ?? carried.width;\n\tcarried.offset = entry.offset ?? carried.offset;\n}\n\n/**\n * The first slot where an element's offset and width together pass the grid's\n * tracks, with the tracks they span, or `undefined` when none does.\n *\n * @remarks\n * Follows the same carry-over as emission: a slot that sets one of the pair is\n * checked against the other as the narrower slots left it, so two slots that\n * each look valid can still overflow together.\n */\nexport function namedPlacementOverflow(element: unknown): { slot: CascadeSlot; tracks: number } | undefined {\n\tconst carried: NamedPlacement = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (entry.width === undefined && entry.offset === undefined) continue;\n\t\tcarryNamedPlacement(carried, entry as NamedPlacement);\n\t\tif (carried.width === undefined || carried.offset === undefined) continue;\n\t\tconst tracks = (WIDTH_SPANS[carried.width] ?? 0) + (WIDTH_SPANS[carried.offset] ?? 0);\n\t\tif (tracks > WIDTH_TRACKS) return { slot, tracks };\n\t}\n\treturn undefined;\n}\n\n/** The cells of each row of a template; `.` marks an empty cell. */\nexport type GridAreaRows = readonly (readonly string[])[];\n\n/** Templates by the slot that sets them. */\nexport type GridAreaTemplates = Partial<Record<CascadeSlot, GridAreaRows>>;\n\nconst EMPTY_CELL = '.';\n\nfunction splitRow(row: unknown): string[] {\n\tif (typeof row !== 'string') return [];\n\treturn row\n\t\t.trim()\n\t\t.split(/\\s+/)\n\t\t.filter(Boolean)\n\t\t.map((cell) => (/^\\.+$/.test(cell) ? EMPTY_CELL : cell));\n}\n\nfunction toRows(rows: unknown): GridAreaRows | undefined {\n\treturn Array.isArray(rows) ? rows.map(splitRow) : undefined;\n}\n\n/**\n * The templates a grid's `areas` sets, by slot. An array is the `default` template.\n *\n * @remarks\n * A run of dots is one empty cell, normalised to a single `.`, so a template\n * compares and emits the same however the author spaced it.\n */\nexport function gridAreaTemplates(grid: unknown): GridAreaTemplates {\n\tif (!isRecord(grid) || grid.areas === undefined) return {};\n\tif (Array.isArray(grid.areas)) {\n\t\tconst rows = toRows(grid.areas);\n\t\treturn rows ? { default: rows } : {};\n\t}\n\tif (!isRecord(grid.areas)) return {};\n\tconst templates: GridAreaTemplates = {};\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst rows = toRows(grid.areas[slot]);\n\t\tif (rows) templates[slot] = rows;\n\t}\n\treturn templates;\n}\n\n/** Whether a grid draws its layout with `areas`. */\nexport function gridUsesAreas(grid: unknown): boolean {\n\treturn Object.keys(gridAreaTemplates(grid)).length > 0;\n}\n\n/** Area names a template uses, in order of first appearance. */\nexport function areaNames(rows: GridAreaRows): string[] {\n\tconst names = new Set<string>();\n\tfor (const row of rows) {\n\t\tfor (const cell of row) if (cell !== EMPTY_CELL) names.add(cell);\n\t}\n\treturn [...names];\n}\n\n/** The `grid-template-areas` value for a template: one quoted string per row. */\nexport function areasTemplateValue(rows: GridAreaRows): string {\n\treturn rows.map((row) => `\"${row.join(' ')}\"`).join(' ');\n}\n\n/**\n * The area an element authored at each slot it sets one. Within a slot,\n * `responsive.default` beats the top level, as in emission.\n */\nexport function elementAreaSlots(element: unknown): Partial<Record<CascadeSlot, string>> {\n\tconst areas: Partial<Record<CascadeSlot, string>> = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (typeof entry.area === 'string') areas[slot] = entry.area;\n\t}\n\treturn areas;\n}\n\n/** Whether an element hides itself at each slot it sets `hidden`, in cascade order within a slot. */\nexport function elementHiddenSlots(element: unknown): Partial<Record<CascadeSlot, boolean>> {\n\tconst hidden: Partial<Record<CascadeSlot, boolean>> = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (typeof entry.hidden === 'boolean') hidden[slot] = entry.hidden;\n\t}\n\treturn hidden;\n}\n\n/**\n * What each slot resolves to: the value set at that slot, else the last one a\n * narrower slot set.\n *\n * @remarks\n * Emission falls back through narrower slots in the stylesheet, so validation\n * reads templates and areas the same way to check what a viewport gets.\n */\nexport function cascadeValues<T>(\n\tauthored: Partial<Record<CascadeSlot, T>>,\n): Array<{ slot: CascadeSlot; value: T | undefined }> {\n\tlet carried: T | undefined;\n\treturn CASCADE_SLOTS.map((slot) => {\n\t\tcarried = authored[slot] ?? carried;\n\t\treturn { slot, value: carried };\n\t});\n}\n\nfunction cellCount(count: number): string {\n\treturn `${count} ${count === 1 ? 'cell' : 'cells'}`;\n}\n\nfunction isRectangle(rows: GridAreaRows, name: string): boolean {\n\tconst cells: Array<[row: number, column: number]> = [];\n\trows.forEach((row, rowIndex) =>\n\t\trow.forEach((cell, columnIndex) => {\n\t\t\tif (cell === name) cells.push([rowIndex, columnIndex]);\n\t\t}),\n\t);\n\tconst rowsUsed = cells.map(([row]) => row);\n\tconst columnsUsed = cells.map(([, column]) => column);\n\tconst height = Math.max(...rowsUsed) - Math.min(...rowsUsed) + 1;\n\tconst width = Math.max(...columnsUsed) - Math.min(...columnsUsed) + 1;\n\treturn height * width === cells.length;\n}\n\n/**\n * Why CSS would drop a template: rows of unequal length, or an area whose cells\n * do not fill a rectangle.\n *\n * @param grid A grid config; one that sets no `areas` has no issue.\n *\n * @remarks\n * Each issue's `path` is relative to the grid: `['areas']` for the array form of the default\n * template, else `['areas', slot]`. Rows of unequal length stop the check for that template, as no\n * area can be located in a ragged one.\n */\nexport function areaTemplateIssues(grid: unknown): LayoutIssue[] {\n\tconst templates = gridAreaTemplates(grid);\n\tconst arrayForm = isRecord(grid) && Array.isArray(grid.areas);\n\tconst issues: LayoutIssue[] = [];\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst rows = templates[slot];\n\t\tif (!rows) continue;\n\t\tconst path = arrayForm ? ['areas'] : ['areas', slot];\n\t\tconst width = rows[0]?.length ?? 0;\n\t\tconst ragged = rows.findIndex((row) => row.length !== width);\n\t\tif (ragged !== -1) {\n\t\t\tissues.push({\n\t\t\t\tpath,\n\t\t\t\tmessage: `row ${ragged + 1} has ${cellCount(rows[ragged]?.length ?? 0)} but row 1 has ${width}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const name of areaNames(rows)) {\n\t\t\tif (!isRectangle(rows, name)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tpath,\n\t\t\t\t\tmessage: `area '${name}' is not rectangular; CSS drops the whole template unless every area fills a rectangle.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn issues;\n}\n"],
|
|
5
|
+
"mappings": "AAYO,IAAMA,EAAmB,CAAC,KAAM,KAAM,KAAM,KAAM,KAAK,EAQjDC,EAAwC,CAAC,UAAW,GAAGD,CAAgB,EAGvEE,EAAe,GAEfC,EAAuD,CACnE,KAAM,GACN,iBAAkB,EAClB,aAAc,EACd,KAAM,EACN,MAAO,EACP,QAAS,CACV,EAQaC,EAAqB,CACjC,UACA,gBACD,EAQA,SAASC,EAASC,EAAkD,CACnE,OAAO,OAAOA,GAAU,UAAYA,IAAU,IAC/C,CAMO,SAASC,EAAiBC,EAAgF,CAChH,GAAI,CAACH,EAASG,CAAO,GAAK,CAACH,EAASG,EAAQ,IAAI,EAAG,MAAO,CAAC,EAC3D,IAAMC,EAAOD,EAAQ,KACfE,EAAsE,CAAC,CAAE,KAAM,UAAW,MAAOD,CAAK,CAAC,EACvGE,EAAaF,EAAK,WACxB,GAAI,CAACJ,EAASM,CAAU,EAAG,OAAOD,EAClC,QAAWE,KAAQX,EAAe,CACjC,IAAMY,EAAQF,EAAWC,CAAI,EACzBP,EAASQ,CAAK,GAAGH,EAAM,KAAK,CAAE,KAAAE,EAAM,MAAAC,CAAM,CAAC,CAChD,CACA,OAAOH,CACR,CAGO,SAASI,EAAgBN,EAAuC,CACtE,IAAMO,EAAO,IAAI,IACjB,OAAW,CAAE,MAAAF,CAAM,IAAKN,EAAiBC,CAAO,EAC/C,OAAW,CAACQ,EAAKV,CAAK,IAAK,OAAO,QAAQO,CAAK,EAC1CG,IAAQ,cAAgBV,IAAU,QAAWS,EAAK,IAAIC,CAAG,EAG/D,OAAOD,CACR,CAEO,SAASE,EAAsBT,EAA2B,CAChE,IAAMO,EAAOD,EAAgBN,CAAO,EACpC,OAAOO,EAAK,IAAI,OAAO,GAAKA,EAAK,IAAI,QAA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B,CAAC,CAGJ,CACA,OAAOW,CACR",
|
|
6
|
+
"names": ["BREAKPOINT_ORDER", "CASCADE_SLOTS", "WIDTH_TRACKS", "WIDTH_SPANS", "GRID_TEMPLATE_KEYS", "isRecord", "value", "elementGridSlots", "element", "grid", "slots", "responsive", "slot", "entry", "elementGridKeys", "keys", "key", "elementUsesGridWidths", "usesGridWidths", "elements", "carryNamedPlacement", "carried", "namedPlacementOverflow", "tracks", "EMPTY_CELL", "splitRow", "row", "cell", "toRows", "rows", "gridAreaTemplates", "templates", "gridUsesAreas", "areaNames", "names", "areasTemplateValue", "elementAreaSlots", "areas", "elementHiddenSlots", "hidden", "cascadeValues", "authored", "cellCount", "count", "isRectangle", "name", "cells", "rowIndex", "columnIndex", "rowsUsed", "columnsUsed", "column", "height", "width", "areaTemplateIssues", "arrayForm", "issues", "path", "ragged"]
|
|
7
|
+
}
|