atlassian-labs / compiled

A familiar and performant compile time CSS-in-JS library for React.
https://compiledcssinjs.com
Apache License 2.0
1.98k stars 68 forks source link

Fails silently when Compiled APIs are used as values in style attribute #1614

Open dddlr opened 8 months ago

dddlr commented 8 months ago

Keyframes API in style attribute

Take this example:

import { css, keyframes } from '@compiled/react';
import React from 'react';

const slideInTop = keyframes({
    from: {
        transform: 'translateY(15px)',
    },
    to: {
        transform: 'translateY(0)',
    },
});

const slideInBottom = keyframes({
    from: {
        transform: 'translateY(-15px)',
    },
    to: {
        transform: 'translateY(0)',
    },
});

const dragHandleDotStyles = css({
    width: '9px',
    height: '9px',
    borderRadius: '50%',
    cursor: 'pointer',
});

const type = 'top';

export const App = () => (
  <>
    <div
        css={dragHandleDotStyles}
        style={{
            animation: `${type === 'top' ? slideInTop : slideInBottom} 1s`,
        }}
    >
      hello
    </div>
  </>
);

This fails silently because we do not support keyframes API (which uses Compiled) inside of style attribute (which currently bypasses Compiled entirely?).

We also get some bizarre output for the animation property:

Screenshot 2024-01-08 at 17 09 54

We should throw an error here instead.

Workaround for keyframes API in style attribute

Note that there is a workaround - move everything into the css attribute:

const slideInTopStyles = css({
  animation: `${slideInTop} 1s`,
});

const slideInBottomStyles = css({
  animation: `${slideInBottom} 1s`,
})

const type = 'top';

export const App = () => (
  <>
    <div
        data-dot
        css={[dragHandleDotStyles, type === 'top' && slideInTopStyles, type === 'bottom' && slideInBottomStyles]}
    >
      bap
    </div>
  </>
);

We can see that the output CSS is now correct:

Screenshot 2024-01-08 at 17 08 45

Note two: we do not support ternary operators, so we can't do type === 'top' ? slideInTopStyles : slideInBottomStyles in the css attribute just yet. One day!

Use of other Compiled APIs in style attribute

Additionally, using Compiled's css API (and potentially other Compiled APIs, like the cssMap API) also fails silently:

const dragHandleDotStyles = css({
    width: '9px',
    height: '9px',
    borderRadius: '50%',
    cursor: 'pointer',
});

export const App = () => (
  <>
    <div
        style={{
            animation: `${dragHandleDotStyles} 1s`,
        }}
    >
      hello??
    </div>
  </>
);

Regardless of what Compiled API is being used in the style attribute, we should throw an error.