Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for css @property #1092

Merged
merged 19 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions examples/next/components/HelloWorld.css.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
import { style } from '@vanilla-extract/css';
import {
style,
createVar,
keyframes,
getVarName,
fallbackVar,
} from '@vanilla-extract/css';

const color = createVar();
const angle = createVar({
syntax: '<angle>',
inherits: false,
initialValue: '0deg',
});

const angleKeyframes = keyframes({
'100%': {
[getVarName(angle)]: '360deg',
},
});

export const root = style({
background: 'pink',
color: 'blue',
padding: '16px',
transition: 'opacity .1s ease', // Testing autoprefixer
transition: `opacity .1s ease, color .1s ease`, // Testing autoprefixer
backgroundImage: `linear-gradient(${angle}, rgba(153, 70, 198, 0.35) 0%, rgba(28, 56, 240, 0.46) 100%)`,
animation: `${angleKeyframes} 7s infinite ease-in-out both`,

':hover': {
opacity: 0.8,
color: color,
},

vars: {
[color]: '#fef',
[angle]: fallbackVar(angle, '138deg'),
},
});
2 changes: 2 additions & 0 deletions packages/css/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export { getVarName } from '@vanilla-extract/private';

import './runtimeAdapter';

export type {
Expand Down
15 changes: 15 additions & 0 deletions packages/css/src/transformCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
CSSSelectorBlock,
Composition,
WithQueries,
CSSPropertyBlock,
} from './types';
import { markCompositionUsed } from './adapter';
import { forEach, omit, mapKeys } from './utils';
Expand Down Expand Up @@ -119,6 +120,7 @@ class Stylesheet {
localClassNamesSearch: AhoCorasick;
composedClassLists: Array<{ identifier: string; regex: RegExp }>;
layers: Map<string, Array<string>>;
propertyRules: Array<CSSPropertyBlock>;

constructor(
localClassNames: Array<string>,
Expand All @@ -128,6 +130,7 @@ class Stylesheet {
this.conditionalRulesets = [new ConditionalRuleset()];
this.fontFaceRules = [];
this.keyframesRules = [];
this.propertyRules = [];
this.localClassNamesMap = new Map(
localClassNames.map((localClassName) => [localClassName, localClassName]),
);
Expand All @@ -150,6 +153,13 @@ class Stylesheet {

return;
}

if (root.type === 'property') {
this.propertyRules.push(root);

return;
}

if (root.type === 'keyframes') {
root.rule = Object.fromEntries(
Object.entries(root.rule).map(([keyframe, rule]) => {
Expand Down Expand Up @@ -573,6 +583,11 @@ class Stylesheet {
css.push(renderCss({ '@font-face': fontFaceRule }));
}

// Render property rules
for (const property of this.propertyRules) {
css.push(renderCss({ [`@property ${property.name}`]: property.rule }));
}

// Render keyframes
for (const keyframe of this.keyframesRules) {
css.push(renderCss({ [`@keyframes ${keyframe.name}`]: keyframe.rule }));
Expand Down
28 changes: 27 additions & 1 deletion packages/css/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,19 @@ export type CSSLayerDeclaration = {
name: string;
};

export type CSSPropertyBlock = {
type: 'property';
name: string;
rule: AtRule.Property;
};

export type CSS =
| CSSStyleBlock
| CSSFontFaceBlock
| CSSKeyframesBlock
| CSSSelectorBlock
| CSSLayerDeclaration;
| CSSLayerDeclaration
| CSSPropertyBlock;

export type FileScope = {
packageName?: string;
Expand Down Expand Up @@ -155,3 +162,22 @@ export type ThemeVars<ThemeContract extends NullableTokens> = MapLeafNodes<
export type ClassNames = string | Array<ClassNames>;

export type ComplexStyleRule = StyleRule | Array<StyleRule | ClassNames>;

export type PropertySyntax =
| '<length>'
| '<number>'
| '<percentage>'
| '<length-percentage>'
| '<color>'
| '<image>'
| '<url>'
| '<integer>'
| '<angle>'
| '<time>'
| '<resolution>'
| '<transform-function>'
| '<custom-ident>'
| '<transform-list>'
| '*'
// needs this to make TS suggestions work
| (string & Record<never, never>);
askoufis marked this conversation as resolved.
Show resolved Hide resolved
84 changes: 78 additions & 6 deletions packages/css/src/vars.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { AtRule } from 'csstype';

import {
get,
walkObject,
Expand All @@ -9,20 +11,92 @@ import cssesc from 'cssesc';

import { Tokens, NullableTokens, ThemeVars } from './types';
import { validateContract } from './validateContract';
import { getFileScope } from './fileScope';
import { generateIdentifier } from './identifier';

export function createVar(debugId?: string): CSSVarFunction {
import { PropertySyntax } from './types';
import { appendCss } from './adapter';

type VarDeclaration = {
syntax: PropertySyntax | Array<PropertySyntax>;
inherits: boolean;
initialValue?: string;
};

const buildPropertyRule = ({
syntax,
inherits,
initialValue,
}: VarDeclaration): AtRule.Property => ({
syntax: `"${Array.isArray(syntax) ? syntax.join(' | ') : syntax}"`,
inherits: inherits ? 'true' : 'false',
initialValue,
});

export function createVar(
declaration: VarDeclaration,
debugId?: string,
): CSSVarFunction;
export function createVar(debugId?: string): CSSVarFunction;
export function createVar(
debugIdOrDeclaration?: string | VarDeclaration,
debugId?: string,
): CSSVarFunction {
const cssVarName = cssesc(
generateIdentifier({
debugId,
debugId:
typeof debugIdOrDeclaration === 'string'
? debugIdOrDeclaration
: debugId,
debugFileName: false,
}),
{ isIdentifier: true },
);

if (debugIdOrDeclaration && typeof debugIdOrDeclaration === 'object') {
appendCss(
{
type: 'property',
name: `--${cssVarName}`,
rule: buildPropertyRule(debugIdOrDeclaration),
},
getFileScope(),
);
}

return `var(--${cssVarName})` as const;
}

export function createGlobalVar(name: string): CSSVarFunction;
export function createGlobalVar(
name: string,
declaration: VarDeclaration,
): CSSVarFunction;
export function createGlobalVar(
name: string,
declaration?: VarDeclaration,
): string {
if (declaration && typeof declaration === 'object') {
appendCss(
{
type: 'property',
name: `--${name}`,
rule: buildPropertyRule(declaration),
},
getFileScope(),
);
}

return `var(--${name})`;
}

export function assertVarName(
value: unknown,
): asserts value is `var(--${string})` {
if (typeof value !== 'string' || !/^var\(--.*\)$/.test(value)) {
throw new Error(`Invalid variable name: ${value}`);
}
}

export function fallbackVar(
...values: [string, ...Array<string>]
): CSSVarFunction {
Expand All @@ -32,9 +106,7 @@ export function fallbackVar(
if (finalValue === '') {
finalValue = String(value);
} else {
if (typeof value !== 'string' || !/^var\(--.*\)$/.test(value)) {
throw new Error(`Invalid variable name: ${value}`);
}
assertVarName(value);

finalValue = value.replace(/\)$/, `, ${finalValue})`);
}
Expand Down
2 changes: 2 additions & 0 deletions packages/dynamic/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export { getVarName } from '@vanilla-extract/private';

export { assignInlineVars } from './assignInlineVars';
export { setElementVars } from './setElementVars';