Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
/**
* Generates src/__generated__/property-var-test-fixtures.ts
*
* The fixture is sourced directly from MDN property grammar so both longhands
* and shorthands share one generated matrix. For each property we synthesize
* canonical value patterns, replace every known slot position with `var()`,
* and also emit an all-slots case where every slot becomes its own variable.
*
* Run with: pnpm build:property-var-fixtures
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import properties from "mdn-data/css/properties.json";
import syntaxes from "mdn-data/css/syntaxes.json";
import { definitionSyntax, generate, parse } from "css-tree";
type DSNode =
| { type: "Keyword"; name: string }
| { type: "String" }
| { type: "AtKeyword"; name: string }
| { type: "Token"; value: string }
| { type: "Comma" }
| { type: "Function"; name: string }
| { type: "Type"; name: string }
| { type: "Property"; name: string }
| {
type: "Multiplier";
term: DSNode;
max: number;
min: number;
comma: boolean;
}
| { type: "Group"; combinator: string; terms: DSNode[] };
const __dir = dirname(fileURLToPath(import.meta.url));
const targetDir = join(__dir, "../src/__generated__");
const autogeneratedHint =
"// This file was generated by pnpm build:property-var-fixtures\n";
const unsupportedProperties = ["--*", "all"];
const typeSamples: Record<string, string> = {
angle: "1deg",
attachment: "scroll",
"basic-shape": "circle()",
color: "red",
"color-stop-list": "red, blue",
"custom-ident": "custom-ident",
"dashed-ident": "--custom-ident",
"declaration-value": "1px",
decibel: "1db",
"family-name": "serif",
flex: "1fr",
frequency: "1hz",
"generic-family": "serif",
gradient: "linear-gradient(red, blue)",
ident: "custom-ident",
image: "url(hero.png)",
integer: "1",
length: "1px",
"length-percentage": "1px",
"line-style": "solid",
"line-width": "1px",
number: "1",
percentage: "10%",
position: "center",
"ratio-token": "1/1",
"repeat-style": "no-repeat",
resolution: "1dpi",
semitones: "1st",
shadow: "0 0 1px red",
string: '"x"',
time: "1s",
transform: "translateX(1px)",
"transform-function": "translateX(1px)",
"transform-list": "translateX(1px)",
url: "url(hero.png)",
x: "1",
y: "1",
};
const propertyOverrides: Record<string, string[]> = {};
const propertyPatternOverrides: Record<string, GrammarPattern[]> = {
font: [
{
complexity: 1,
parts: [
{ kind: "slot", label: "font-style", text: "italic" },
{ kind: "text", text: " " },
{ kind: "slot", label: "font-weight", text: "700" },
{ kind: "text", text: " " },
{ kind: "slot", label: "font-size", text: "16px" },
{ kind: "text", text: "/" },
{ kind: "slot", label: "line-height", text: "1.5" },
{ kind: "text", text: " " },
{ kind: "slot", label: "font-family", text: "serif" },
],
},
],
"grid-template": [
{
complexity: 1,
parts: [
{ kind: "slot", label: "grid-template-rows", text: "1px" },
{ kind: "text", text: " / " },
{ kind: "slot", label: "grid-template-columns", text: "1fr" },
],
},
{
complexity: 2,
parts: [
{ kind: "slot", label: "grid-template-areas", text: '"a"' },
{ kind: "text", text: " " },
{ kind: "slot", label: "grid-template-row-size", text: "1px" },
{ kind: "text", text: " / " },
{ kind: "slot", label: "grid-template-explicit-columns", text: "1fr" },
],
},
],
"scroll-timeline": [
{
complexity: 1,
parts: [
{ kind: "slot", label: "scroll-timeline-name", text: "--timeline" },
{ kind: "text", text: " " },
{ kind: "slot", label: "scroll-timeline-axis", text: "block" },
],
},
],
"timeline-trigger": [
{
complexity: 1,
parts: [
{ kind: "slot", label: "timeline-trigger-name", text: "--trigger" },
{ kind: "text", text: " " },
{ kind: "slot", label: "timeline-trigger-source", text: "auto" },
{ kind: "text", text: " " },
{
kind: "slot",
label: "timeline-trigger-activation-range",
text: "normal",
},
{ kind: "text", text: " / " },
{
kind: "slot",
label: "timeline-trigger-active-range",
text: "auto",
},
],
},
],
"view-timeline": [
{
complexity: 1,
parts: [
{ kind: "slot", label: "view-timeline-name", text: "--timeline" },
{ kind: "text", text: " " },
{ kind: "slot", label: "view-timeline-axis", text: "block" },
{ kind: "text", text: " " },
{ kind: "slot", label: "view-timeline-inset", text: "auto" },
],
},
],
"list-style": [
{
complexity: 1,
parts: [
{ kind: "slot", label: "list-style-type", text: "disc" },
{ kind: "text", text: " " },
{ kind: "slot", label: "list-style-position", text: "inside" },
{ kind: "text", text: " " },
{ kind: "slot", label: "list-style-image", text: "url(hero.png)" },
],
},
],
};
interface PropertyConfig {
inherited: boolean;
initial: string | string[];
mdn_url?: string;
status?: string;
syntax: string;
}
interface SyntaxConfig {
syntax: string;
}
interface GrammarPart {
kind: "slot" | "text";
label?: string;
text: string;
}
interface GrammarPattern {
complexity: number;
parts: GrammarPart[];
}
interface PropertyVarCase {
id: string;
positions: string[];
value: string;
variables: Record<string, string>;
}
interface PropertyVarFixture {
cases: PropertyVarCase[];
kind: "longhand" | "shorthand";
property: string;
syntax: string;
unsupportedReason?: string;
}
const propertyData = properties as Record<string, PropertyConfig>;
const syntaxData = syntaxes as Record<string, SyntaxConfig>;
const getFilteredProperties = () => {
const filtered: Array<{
kind: "longhand" | "shorthand";
property: string;
syntax: string;
}> = [];
for (const [property, config] of Object.entries(propertyData)) {
if (unsupportedProperties.includes(property)) {
continue;
}
filtered.push({
kind: Array.isArray(config.initial) ? "shorthand" : "longhand",
property,
syntax: config.syntax,
});
}
return filtered.sort((left, right) =>
left.property.localeCompare(right.property)
);
};
const normalizeCssValue = (value: string) => {
try {
return generate(parse(value, { context: "value" }));
} catch {
return;
}
};
const mergeTextParts = (parts: GrammarPart[]) => {
const merged: GrammarPart[] = [];
for (const part of parts) {
const previous = merged.at(-1);
if (part.kind === "text" && previous?.kind === "text") {
previous.text += part.text;
continue;
}
merged.push({ ...part });
}
return merged;
};
const serializeParts = (parts: GrammarPart[]) => {
return parts.map((part) => part.text).join("");
};
const trimPattern = (pattern: GrammarPattern): GrammarPattern => {
const parts = mergeTextParts(pattern.parts);
const first = parts[0];
const last = parts.at(-1);
if (first?.kind === "text") {
first.text = first.text.trimStart();
}
if (last?.kind === "text") {
last.text = last.text.trimEnd();
}
return {
complexity: pattern.complexity,
parts,
};
};
const leadingText = (pattern: GrammarPattern) => {
return pattern.parts[0]?.text ?? "";
};
const trailingText = (pattern: GrammarPattern) => {
return pattern.parts.at(-1)?.text ?? "";
};
const shouldInsertSpace = ({
left,
right,
}: {
left: GrammarPattern;
right: GrammarPattern;
}) => {
if (left.parts.length === 0 || right.parts.length === 0) {
return false;
}
const leftText = trailingText(left);
const rightText = leadingText(right);
if (leftText.endsWith("(") || leftText.endsWith("/")) {
return false;
}
if (rightText.startsWith(")") || rightText.startsWith(",")) {
return false;
}
if (rightText.startsWith("/")) {
return true;
}
return true;
};
const combinePatterns = ({
left,
right,
}: {
left: GrammarPattern;
right: GrammarPattern;
}): GrammarPattern => {
const parts = [...left.parts];
if (shouldInsertSpace({ left, right })) {
parts.push({ kind: "text", text: " " });
}
parts.push(...right.parts);
return trimPattern({
complexity: left.complexity + right.complexity + 1,
parts,
});
};
const takeBestPatterns = ({
limit,
patterns,
}: {
limit: number;
patterns: GrammarPattern[];
}) => {
const deduped = new Map<string, GrammarPattern>();
for (const pattern of patterns) {
const normalized = normalizeCssValue(serializeParts(pattern.parts));
if (normalized === undefined) {
continue;
}
const existing = deduped.get(normalized);
if (existing !== undefined && existing.complexity <= pattern.complexity) {
continue;
}
deduped.set(normalized, trimPattern(pattern));
}
return [...deduped.values()]
.sort((left, right) => left.complexity - right.complexity)
.slice(0, limit);
};
const literalPattern = ({
label,
text,
}: {
label?: string;
text: string;
}): GrammarPattern => {
return {
complexity: 1,
parts: [
label === undefined
? { kind: "text", text }
: { kind: "slot", label, text },
],
};
};
const repeatCount = ({ max, min }: { max: number; min: number }) => {
if (max === 0) {
if (min > 1) {
return min;
}
return 2;
}
if (min === max) {
return max;
}
return Math.max(min, max);
};
const sampleForType = (name: string) => {
const direct = typeSamples[name];
if (direct !== undefined) {
return direct;
}
if (name.endsWith("()")) {
const functionName = name.slice(0, -2);
const functionSamples: Record<string, string> = {
"anchor-size": "anchor-size(width, 1px)",
circle: "circle()",
"cross-fade": "cross-fade(url(hero.png), url(hero.png))",
element: "element(#hero)",
image: "image(url(hero.png))",
"image-set": "image-set(url(hero.png) 1x)",
"linear-gradient": "linear-gradient(red, blue)",
matrix: "matrix(1, 0, 0, 1, 0, 0)",
matrix3d: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)",
paint: "paint(worklet)",
path: 'path("M0 0")',
perspective: "perspective(1px)",
rotate: "rotate(1deg)",
rotate3d: "rotate3d(1, 0, 0, 1deg)",
rotateX: "rotateX(1deg)",
rotateY: "rotateY(1deg)",
rotateZ: "rotateZ(1deg)",
scale: "scale(1)",
scale3d: "scale3d(1, 1, 1)",
scaleX: "scaleX(1)",
scaleY: "scaleY(1)",
scaleZ: "scaleZ(1)",
skew: "skew(1deg)",
skewX: "skewX(1deg)",
skewY: "skewY(1deg)",
translate: "translate(1px)",
translate3d: "translate3d(1px, 1px, 1px)",
translateX: "translateX(1px)",
translateY: "translateY(1px)",
translateZ: "translateZ(1px)",
url: "url(hero.png)",
};
const sample = functionSamples[functionName];
if (sample !== undefined) {
return sample;
}
}
if (name.includes("color")) {
return "red";
}
if (name.includes("length")) {
return "1px";
}
if (name.includes("percentage")) {
return "10%";
}
if (name.includes("time")) {
return "1s";
}
if (name.includes("angle")) {
return "1deg";
}
if (name.includes("number") || name.includes("integer")) {
return "1";
}
if (name.includes("family")) {
return "serif";
}
if (name.includes("position")) {
return "center";
}
if (name.includes("image") || name.includes("url")) {
return "url(hero.png)";
}
if (name.includes("style")) {
return "solid";
}
if (name.includes("width")) {
return "1px";
}
if (name.includes("ident")) {
return "custom-ident";
}
return;
};
const buildPatterns = ({
depth,
key,
node,
seen,
}: {
depth: number;
key: string;
node: DSNode;
seen: Set<string>;
}): GrammarPattern[] => {
if (node.type === "Keyword") {
return [
literalPattern({ label: `${key}:keyword:${node.name}`, text: node.name }),
];
}
if (node.type === "String") {
return [literalPattern({ label: `${key}:string`, text: '"x"' })];
}
if (node.type === "AtKeyword") {
return [
literalPattern({ label: `${key}:at-keyword`, text: `@${node.name}` }),
];
}
if (node.type === "Token") {
return [literalPattern({ text: node.value })];
}
if (node.type === "Comma") {
return [literalPattern({ text: "," })];
}
if (node.type === "Function") {
return [literalPattern({ text: `${node.name}(` })];
}
if (node.type === "Type") {
const typeKey = `type:${node.name}`;
if (seen.has(typeKey)) {
const sample = sampleForType(node.name);
if (sample === undefined) {
return [];
}
return [
literalPattern({ label: `${key}:type:${node.name}`, text: sample }),
];
}
const nestedSyntax = syntaxData[node.name]?.syntax;
if (nestedSyntax !== undefined) {
const nextSeen = new Set(seen);
nextSeen.add(typeKey);
return buildPatterns({
depth: depth + 1,
key: `${key}:type:${node.name}`,
node: definitionSyntax.parse(nestedSyntax) as DSNode,
seen: nextSeen,
});
}
const sample = sampleForType(node.name);
if (sample === undefined) {
return [];
}
return [
literalPattern({ label: `${key}:type:${node.name}`, text: sample }),
];
}
if (node.type === "Property") {
const propertySyntax = propertyData[node.name]?.syntax;
if (propertySyntax === undefined) {
return [];
}
const propertyKey = `property:${node.name}`;
if (seen.has(propertyKey)) {
const override = propertyOverrides[node.name]?.[0];
if (override === undefined) {
return [];
}
return [
literalPattern({
label: `${key}:property:${node.name}`,
text: override,
}),
];
}
const nextSeen = new Set(seen);
nextSeen.add(propertyKey);
return buildPatterns({
depth: depth + 1,
key: `${key}:property:${node.name}`,
node: definitionSyntax.parse(propertySyntax) as DSNode,
seen: nextSeen,
});
}
if (node.type === "Multiplier") {
const basePatterns = buildPatterns({
depth: depth + 1,
key: `${key}:repeat`,
node: node.term,
seen,
});
if (basePatterns.length === 0) {
return [];
}
const patterns: GrammarPattern[] = [];
const count = repeatCount({ max: node.max, min: node.min });
for (const pattern of basePatterns) {
let combined = pattern;
for (let index = 1; index < count; index += 1) {
const separator = node.comma
? literalPattern({ text: "," })
: literalPattern({ text: "" });
combined = combinePatterns({ left: combined, right: separator });
combined = combinePatterns({ left: combined, right: pattern });
}
patterns.push(combined);
}
return takeBestPatterns({ limit: 4, patterns });
}
if (node.type !== "Group") {
return [];
}
if (node.combinator === "|") {
const branchPatterns = node.terms.flatMap((term: DSNode, index: number) => {
return buildPatterns({
depth: depth + 1,
key: `${key}:branch:${index}`,
node: term,
seen,
});
});
return takeBestPatterns({
limit: depth < 2 ? 4 : 1,
patterns: branchPatterns,
});
}
let current: GrammarPattern[] = [{ complexity: 0, parts: [] }];
for (const [index, term] of node.terms.entries()) {
const termPatterns = buildPatterns({
depth: depth + 1,
key: `${key}:term:${index}`,
node: term,
seen,
});
if (termPatterns.length === 0) {
return [];
}
const combined: GrammarPattern[] = [];
for (const left of current) {
for (const right of termPatterns) {
if (left.parts.length === 0) {
combined.push(trimPattern(right));
continue;
}
combined.push(combinePatterns({ left, right }));
}
}
current = takeBestPatterns({ limit: 6, patterns: combined });
}
return current;
};
/**
* Derive a semantic CSS variable name from a slot's grammar position label.
* The label looks like "border:term:2:type:color:branch:0:type:hex-color".
* We extract the first `type:XXX` segment to build `--slot-XXX`.
* When multiple slots in the same pattern share the same type we append
* a counter suffix: `--slot-color`, `--slot-color-2`, etc.
* Falling back to `--slot-N` when no type can be extracted.
*/
const slotVarName = (
label: string | undefined,
fallbackIndex: number,
used: Map<string, number>
): string => {
const typeMatch = label?.match(/(?:^|:)type:([^:]+)/);
const base = typeMatch
? `--slot-${typeMatch[1]}`
: `--slot-${fallbackIndex + 1}`;
const count = (used.get(base) ?? 0) + 1;
used.set(base, count);
return count === 1 ? base : `${base}-${count}`;
};
const buildCases = ({
patterns,
property,
}: {
patterns: GrammarPattern[];
property: string;
}) => {
const cases = new Map<string, PropertyVarCase>();
for (const [patternIndex, pattern] of patterns.entries()) {
const slots = pattern.parts
.map((part, index) => ({ index, part }))
.filter(({ part }) => part.kind === "slot");
if (slots.length === 0) {
continue;
}
for (const [slotOrder, slot] of slots.entries()) {
const used = new Map<string, number>();
// pre-register names for earlier slots so this slot gets the right suffix
for (let i = 0; i < slotOrder; i++) {
slotVarName(slots[i].part.label, i, used);
}
const variableName = slotVarName(slot.part.label, slotOrder, used);
const parts = pattern.parts.map((part, index) => {
if (index !== slot.index || part.kind !== "slot") {
return part;
}
return {
kind: "text" as const,
text: `var(${variableName})`,
};
});
const value = normalizeCssValue(serializeParts(parts));
if (value === undefined) {
continue;
}
cases.set(`${property}:${value}`, {
id: `pattern-${patternIndex + 1}-slot-${slotOrder + 1}`,
positions: [slot.part.label ?? `slot-${slotOrder + 1}`],
value,
variables: { [variableName]: slot.part.text },
});
}
if (slots.length === 1) {
continue;
}
const variables: Record<string, string> = {};
const allUsed = new Map<string, number>();
const parts = pattern.parts.map((part, index) => {
const slotOrder = slots.findIndex((slot) => slot.index === index);
if (slotOrder === -1 || part.kind !== "slot") {
return part;
}
const variableName = slotVarName(part.label, slotOrder, allUsed);
variables[variableName] = part.text;
return {
kind: "text" as const,
text: `var(${variableName})`,
};
});
const value = normalizeCssValue(serializeParts(parts));
if (value === undefined) {
continue;
}
cases.set(`${property}:${value}`, {
id: `pattern-${patternIndex + 1}-all-slots`,
positions: slots.map(
({ part }, index) => part.label ?? `slot-${index + 1}`
),
value,
variables,
});
}
return [...cases.values()].sort((left, right) =>
left.id.localeCompare(right.id)
);
};
const buildFixtures = () => {
return getFilteredProperties().map(({ kind, property, syntax }) => {
const overridePatterns = propertyOverrides[property]?.flatMap(
(value, index) => {
const normalized = normalizeCssValue(value);
if (normalized === undefined) {
return [];
}
return [
{
complexity: index + 1,
parts: [{ kind: "text", text: normalized }],
} satisfies GrammarPattern,
];
}
);
const patterns =
propertyPatternOverrides[property] ??
(overridePatterns !== undefined && overridePatterns.length > 0
? overridePatterns
: buildPatterns({
depth: 0,
key: property,
node: definitionSyntax.parse(syntax) as DSNode,
seen: new Set([`property:${property}`]),
}));
const cases = buildCases({ patterns, property });
if (cases.length > 0) {
return {
cases,
kind,
property,
syntax,
} satisfies PropertyVarFixture;
}
return {
cases: [],
kind,
property,
syntax,
unsupportedReason:
"No valid grammar-driven var() positions could be synthesized",
} satisfies PropertyVarFixture;
});
};
const fixtures = buildFixtures();
const content =
autogeneratedHint +
`
export interface PropertyVarCase {
id: string;
positions: string[];
value: string;
variables: Record<string, string>;
}
export interface PropertyVarFixture {
cases: PropertyVarCase[];
kind: "longhand" | "shorthand";
property: string;
syntax: string;
unsupportedReason?: string;
}
export const propertyVarTestFixtures: PropertyVarFixture[] = ${JSON.stringify(fixtures, null, 2)} as const;
`;
mkdirSync(targetDir, { recursive: true });
writeFileSync(
join(targetDir, "property-var-test-fixtures.ts"),
content,
"utf8"
);
const caseCount = fixtures.reduce(
(total, fixture) => total + fixture.cases.length,
0
);
const unsupportedCount = fixtures.filter(
(fixture) => fixture.cases.length === 0
).length;
console.info(
`Written ${fixtures.length} fixtures with ${caseCount} cases to property-var-test-fixtures.ts (${unsupportedCount} unsupported)`
);