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

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
27 changes: 25 additions & 2 deletions examples/next/components/HelloWorld.css.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,34 @@
import { style } from '@vanilla-extract/css';
import { style, createVar, keyframes, fallbackVar } from '@vanilla-extract/css';

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

const angleKeyframes = keyframes({
'100%': {
vars: {
[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'),
}
});
5 changes: 4 additions & 1 deletion fixtures/themed/src/styles.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ globalStyle(`body ${iDunno}:after`, {
content: "'I am content'",
});

const blankVar1 = createVar();
const blankVar1 = createVar({
syntax: '<number>',
inherits: false,
});
const blankVar2 = createVar();

export const opacity = styleVariants(
Expand Down
6 changes: 5 additions & 1 deletion packages/babel-plugin-debug-ids/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ const debuggableFunctionConfig = {
maxParams: 2,
},
createVar: {
maxParams: 1,
maxParams: 2,
hasDebugId: ({ arguments: args }) => {
const previousArg = args[args.length - 1];
return t.isStringLiteral(previousArg) || t.isTemplateLiteral(previousArg);
},
z4o4z marked this conversation as resolved.
Show resolved Hide resolved
},
recipe: {
maxParams: 2,
Expand Down
67 changes: 63 additions & 4 deletions packages/css/src/transformCss.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { style } from './style';
setFileScope('test');

const testVar = createVar();
const testPropertyVar = createVar({
syntax: '<angle>',
inherits: false,
initialValue: '0deg',
}, 'test-property');
const style1 = style({});
const style2 = style({});

Expand Down Expand Up @@ -2022,7 +2027,7 @@ describe('transformCss', () => {
`);
});

it('should handle css vars', () => {
it('should handle simple css properties', () => {
expect(
transformCss({
composedClassLists: [],
Expand Down Expand Up @@ -2075,6 +2080,60 @@ describe('transformCss', () => {
}
`);
});

it('should handle complicated css properties', () => {
expect(
transformCss({
composedClassLists: [],
localClassNames: ['testClass'],
cssObjs: [
{
type: 'local',
selector: 'testClass',
rule: {
display: 'block',
vars: {
'--my-var': 'red',
[testPropertyVar]: '10deg',
},
selectors: {
'&:nth-child(3)': {
vars: {
'--my-var': 'orange',
[testPropertyVar]: '20deg',
},
},
},
'@media': {
'screen and (min-width: 700px)': {
vars: {
'--my-var': 'yellow',
[testPropertyVar]: '50deg',
},
},
},
},
},
],
}).join('\n'),
).toMatchInlineSnapshot(`
.testClass {
--my-var: red;
--test-property__skkcyc1: 10deg;
display: block;
}
.testClass:nth-child(3) {
--my-var: orange;
--test-property__skkcyc1: 20deg;
}
@media screen and (min-width: 700px) {
.testClass {
--my-var: yellow;
--test-property__skkcyc1: 50deg;
}
}
`);
});

it('should cast property values to pixels when relevant', () => {
expect(
Expand Down Expand Up @@ -2288,13 +2347,13 @@ describe('transformCss', () => {
],
}).join('\n'),
).toMatchInlineSnapshot(`
.skkcyc2 .skkcyc1:before, .skkcyc2 .skkcyc1:after {
.skkcyc3 .skkcyc2:before, .skkcyc3 .skkcyc2:after {
background: black;
}
._1g1ptzo1._1g1ptzo10 .skkcyc1 {
._1g1ptzo1._1g1ptzo10 .skkcyc2 {
background: blue;
}
._1g1ptzo10._1g1ptzo1 .skkcyc1 {
._1g1ptzo10._1g1ptzo1 .skkcyc2 {
background: blue;
}
`);
Expand Down
17 changes: 16 additions & 1 deletion 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,10 +153,17 @@ 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]) => {
return [keyframe, this.transformProperties(rule)];
return [keyframe, this.transformVars(this.transformProperties(rule))];
z4o4z marked this conversation as resolved.
Show resolved Hide resolved
}),
);
this.keyframesRules.push(root);
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
30 changes: 28 additions & 2 deletions packages/css/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export type CSSProperties = {
};

export interface CSSKeyframes {
[time: string]: CSSProperties;
[time: string]: CSSPropertiesWithVars;
}

export type CSSPropertiesWithVars = CSSProperties & {
Expand Down 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>);
50 changes: 44 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,58 @@ 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 != null && { initialValue }),
z4o4z marked this conversation as resolved.
Show resolved Hide resolved
z4o4z marked this conversation as resolved.
Show resolved Hide resolved
})

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
askoufis marked this conversation as resolved.
Show resolved Hide resolved
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 +72,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
Loading