Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions .changeset/top-level-starting-style-css-map.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@compiled/babel-plugin': minor
'@compiled/react': minor
---

Support the `@starting-style` at-rule when it is declared directly inside a `cssMap` variant (not nested within another at-rule or selector). Previously it was treated like `@media`, which expects a second half, and produced invalid CSS such as `@starting-style color: blue{}`. The `cssMap` types now accept styles directly under `'@starting-style'`.
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,88 @@ describe('css map advanced functionality (at rules, selectors object)', () => {
}
});

// TODO: add a unit test for the `@starting-style` at-rule when it is NOT nested. This is currently not working as
// Compiled only supports processing at-rules that have two "halves", e.g. `@media screen`
// When nested, the at-rule is not processed like an at-rule - it is processed like a CSS selector.
it('should parse the @starting-style at-rule when not nested', () => {
const actual = transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({
success: {
color: 'red',
'@starting-style': {
color: 'blue',
'&:hover': {
color: 'pink',
},
},
},
});

${EXAMPLE_USAGE}
`);

expect(actual).toIncludeMultiple([
'._1UtDYzGowl{color:red}',
'@starting-style{._1F7xNhynoA{color:blue}._0hmGsty8mA:hover{color:pink}}',
'const styles={success:"_1UtDYzGowl _1F7xNhynoA _0hmGsty8mA"}',
]);
expect(actual).not.toContain('@starting-style color');
});

it('should parse @starting-style defined in the selectors object', () => {
const actual = transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({
success: {
selectors: {
'@starting-style': {
color: 'blue',
},
},
},
});

${EXAMPLE_USAGE}
`);

expect(actual).toContain('@starting-style{._1F7xNhynoA{color:blue}}');
});

it('should error if @starting-style is defined both outside and inside the selectors object', () => {
expect(() => {
transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({
success: {
'@starting-style': { color: 'blue' },
selectors: {
'@starting-style': { color: 'red' },
},
},
});

${EXAMPLE_USAGE}
`);
}).toThrow(ErrorMessages.DUPLICATE_AT_RULE);
});

it('should error if @starting-style value is not an object', () => {
expect(() => {
transform(`
import { cssMap } from '@compiled/react';

const styles = cssMap({
success: {
'@starting-style': 'blue',
},
});

${EXAMPLE_USAGE}
`);
}).toThrow(ErrorMessages.AT_RULE_VALUE_TYPE);
});

it('should parse the @starting-style at-rule when nested', () => {
const actual = transform(`
import { cssMap } from '@compiled/react';
Expand Down Expand Up @@ -622,6 +701,27 @@ describe('cssMapScoped advanced functionality (at rules, nested selectors)', ()
}
});

it('should parse the @starting-style at-rule when not nested', () => {
const actual = transform(`
import { cssMapScoped } from '@compiled/react';

const styles = cssMapScoped({
success: {
color: 'red',
'@starting-style': {
color: 'blue'
},
},
});

${EXAMPLE_USAGE}
`);

expect(actual).toContain('const styles={success:"cc-');
expect(actual).toMatch(/@starting-style\{\.cc-[^{]*\{color:blue\}\}/);
expect(actual).not.toContain('@starting-style color');
});

it('should parse the @starting-style at-rule when nested', () => {
const actual = transform(`
import { cssMapScoped } from '@compiled/react';
Expand Down
27 changes: 25 additions & 2 deletions packages/babel-plugin/src/css-map/process-selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getKeyValue,
hasExtendedSelectorsKey as propertyHasExtendedSelectorsKey,
isAtRuleObject,
isAtRuleWithoutPrelude,
objectKeyIsLiteralValue,
isPlainSelector,
} from '../utils/css-map';
Expand Down Expand Up @@ -90,7 +91,8 @@ const getExtendedSelectors = (
*
* This function will merge the two halves of the `@media` query (for example, to get
* `@media screen and (min-width: 500px)`), and it will merge all of
* the keys located in the value of `selectors`:
* the keys located in the value of `selectors`. At-rules that have no second half,
* such as `@starting-style`, are left untouched:
*
* {
* color: 'blue',
Expand Down Expand Up @@ -142,7 +144,28 @@ export const mergeExtendedSelectorsIntoProperties = (
// variable, so we can skip it now
if (propertyHasExtendedSelectorsKey(property)) continue;

if (isAtRuleObject(propertyKey)) {
if (isAtRuleWithoutPrelude(propertyKey)) {
// e.g. `'@starting-style': { color: 'blue' }` - there is no second half to merge into the
// key, so the block is processed as is, the same way a selector would be.
const atRuleName = getKeyValue(propertyKey);
if (!t.isObjectExpression(property.value)) {
throw buildCodeFrameError(
createErrorMessage(ErrorMessages.AT_RULE_VALUE_TYPE),
property.value,
meta.parentPath
);
}
if (addedSelectors.has(atRuleName)) {
throw buildCodeFrameError(
createErrorMessage(ErrorMessages.DUPLICATE_AT_RULE),
property.key,
meta.parentPath
);
}

mergedProperties.push(property);
addedSelectors.add(atRuleName);
} else if (isAtRuleObject(propertyKey)) {
const atRuleType = getKeyValue(propertyKey);
const atRules = collapseAtRule(property, atRuleType, meta);

Expand Down
9 changes: 9 additions & 0 deletions packages/babel-plugin/src/utils/css-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ export const isAtRuleObject = (
return keyValue in atRules;
};

/**
* At-rules that have no prelude (the `screen` in `@media screen`), so their value is a block of styles
* rather than a record of preludes to styles. These must not be collapsed with a second half.
*/
const atRulesWithoutPrelude: Set<string> = new Set(['@starting-style']);

export const isAtRuleWithoutPrelude = (key: ObjectKeyWithLiteralValue): boolean =>
atRulesWithoutPrelude.has(getKeyValue(key));

export const isPlainSelector = (selector: string): boolean => selector.startsWith(':');

export const hasExtendedSelectorsKey = (property: t.ObjectProperty): boolean =>
Expand Down
16 changes: 15 additions & 1 deletion packages/react/src/css-map/__tests__/types.typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,24 @@
// eslint-disable-next-line import/no-extraneous-dependencies, import/named
import { cssMapScoped } from '@compiled/react';

import cssMap from '../index';

// Verify cssMapScoped is exported and accepts the same styles object as cssMap.
const scopedStyles = cssMapScoped({ danger: { color: 'red' } });

// Verify cssMapScoped does NOT accept a second argument.
const scopedStylesWithExtraArg = cssMapScoped({ danger: { color: 'red' } }, {});

export { scopedStyles, scopedStylesWithExtraArg };
// Verify `@starting-style` directly contains styles, as it has no second half like `@media`.
const startingStyleStyles = cssMap({
open: {
color: 'red',
'@starting-style': { opacity: 0, '&:hover': { color: 'blue' } },
'@media': { '(min-width: 100px)': { '@starting-style': { opacity: 0 } } },
},
});

// @ts-expect-error -- `@starting-style` must contain styles, not a record of preludes to styles.
const invalidStartingStyle = cssMap({ open: { '@starting-style': 'blue' } });

export { scopedStyles, scopedStylesWithExtraArg, startingStyleStyles, invalidStartingStyle };
6 changes: 5 additions & 1 deletion packages/react/src/css-map/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ type AllPseudos = { [key in CSSPseudos]?: CSSProperties & AllPseudos };
// Ideally we would do type checking to forbid this from containing the `@media` part,
// but TypeScript doesn't provide a good way to do this.
type AtRuleSecondHalf = string;
// At-rules without a second half, e.g. `@starting-style`, directly contain styles.
type AtRuleWithoutSecondHalf = '@starting-style';
type WhitelistedAtRule = {
[atRuleFirstHalf in CSS.AtRules]?: {
[atRuleFirstHalf in Exclude<CSS.AtRules, AtRuleWithoutSecondHalf>]?: {
[atRuleSecondHalf in AtRuleSecondHalf]: CSSProperties & AllPseudos & WhitelistedAtRule;
};
} & {
[atRule in AtRuleWithoutSecondHalf]?: CSSProperties & AllPseudos & WhitelistedAtRule;
};
type WhitelistedSelector = AllPseudos & WhitelistedAtRule;

Expand Down
14 changes: 14 additions & 0 deletions website/packages/docs/src/pages/api-cssmap.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ const myMap = cssMap({
});
```

At-rules that don't take a condition, such as `@starting-style`, contain styles directly:

```jsx
const myMap = cssMap({
open: {
opacity: 1,
transition: 'opacity 0.3s',
'@starting-style': {
opacity: 0,
},
},
});
```

Previously you would specify media queries by splitting the `@media` part and the rest of the media query into two, just like with the [`vanilla-extract`](https://vanilla-extract.style/documentation/styling/#media-queries) library. We no longer recommend this as it is inconsistent with other Compiled APIs, and our type checking now works without the need for splitting media queries into two.

### Nested selectors and advanced selectors
Expand Down