Skip to content
Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9f6b6de
feat: initial make variants as array
atanasster Oct 27, 2020
9643e96
use deepmerge.all and add test for function
atanasster Nov 6, 2020
047e909
docs: update changelog
atanasster Nov 7, 2020
ac3151c
fix: missing variant merge, add docs by Lauchlan
atanasster Nov 18, 2020
2612c3b
test: add test for multiple derived variants
hasparus Nov 23, 2020
8159640
Merge remote-tracking branch 'origin/master' into variants-as-array
hasparus Nov 23, 2020
9c87c52
chore: merge with master
hasparus Nov 23, 2020
da9a535
Merge branch 'master' into variants-as-array
atanasster Dec 1, 2020
4d64610
feat: added getVariantValue to extract variants
atanasster Dec 1, 2020
3b850c6
Update packages/components/test/index.js
atanasster Dec 2, 2020
5063ddd
test: update snapshots
atanasster Dec 2, 2020
cc0c301
Merge branch 'master' into variants-as-array
hasparus Dec 2, 2020
2f1ddb6
feat: add variant tuple to types
hasparus Dec 2, 2020
771b845
ref(components): prefix unused parameter with _ to make TS happier
hasparus Dec 2, 2020
3eb5de5
test: add temporary test
hasparus Dec 2, 2020
b4d9578
Merge branch 'develop' into variants-as-array
atanasster Dec 15, 2020
fccaefc
merge incoming changes
atanasster Dec 15, 2020
8af8bad
docs: fix wording as suggested by lachlanjs
atanasster Dec 15, 2020
94cc661
Merge branch 'develop' into variants-as-array
atanasster Dec 16, 2020
3984a58
support variant array prop in sx
atanasster Dec 16, 2020
1bd7c60
simplified test code
atanasster Dec 16, 2020
3e5f716
test and docs for variant as a function
atanasster Dec 17, 2020
e1a10b1
Merge branch 'develop' into variants-as-array
lachlanjc Oct 4, 2021
a1f2a9a
Merge branch 'develop' into variants-as-array
lachlanjc Oct 27, 2021
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@

### `@theme-ui/core`

- Box - ability to merge array variant prop. Issues #1209 #1208
- Make ThemeProvider `theme` prop required

### `@theme-ui/editor`
Expand Down
4 changes: 2 additions & 2 deletions packages/components/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react'
import { StyledComponent } from '@emotion/styled'
import { Interpolation } from '@emotion/react'
import { SpaceProps, ColorProps, MarginProps } from 'styled-system'
import { ResponsiveStyleValue, ThemeUIStyleObject } from '@theme-ui/css'
import { ResponsiveStyleValue, ThemeUIStyleObject, VariantProperty } from '@theme-ui/css'

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>

Expand All @@ -20,7 +20,7 @@ type ForwardRef<T, P> = React.ForwardRefExoticComponent<

export interface BoxOwnProps extends SpaceProps, ColorProps {
as?: React.ElementType
variant?: string
variant?: VariantProperty.Variant
css?: Interpolation<any>
sx?: ThemeUIStyleObject
}
Expand Down
22 changes: 16 additions & 6 deletions packages/components/src/Box.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import styled from '@emotion/styled'
import { css, get } from '@theme-ui/css'
import { css, getVariantValue } from '@theme-ui/css'
import deepmerge from 'deepmerge'
import { createShouldForwardProp } from '@styled-system/should-forward-prop'
import space from '@styled-system/space'
import color from '@styled-system/color'
Expand All @@ -9,10 +10,19 @@ const shouldForwardProp = createShouldForwardProp([
...color.propNames,
])

const sx = props => css(props.sx)(props.theme)
const base = props => css(props.__css)(props.theme)
const variant = ({ theme, variant, __themeKey = 'variants' }) =>
css(get(theme, __themeKey + '.' + variant, get(theme, variant)))
const sx = (props) => css(props.sx)(props.theme)
const base = (props) => css(props.__css)(props.theme)
const variant = ({ theme, variant, __themeKey = 'variants' }) => {
if (Array.isArray(variant)) {
return css(
deepmerge.all(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we also support

sx={{
  variant: ['a', 'b']
}}

?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could move this logic up to css package.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we also support

sx={{
  variant: ['a', 'b']
}}

?

This is the responsive variants syntax, right?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the responsive variants syntax, right?

Well, now it is.

from V1 roadmap #832

sx={{
  variant: ['a', 'b'] // new combined variant
  variant: [['a', 'b']] // new responsive tuple variant
}}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should create a new issue with that feature.

variant.map((v) => getVariantValue(theme, __themeKey, v) || {}),
{ arrayMerge: (_dest, src) => src }
)
)
}
return css(getVariantValue(theme, __themeKey, variant))
}

export const Box = styled('div', {
shouldForwardProp,
Expand All @@ -27,7 +37,7 @@ export const Box = styled('div', {
space,
color,
sx,
props => props.css
(props) => props.css
)

export default Box
37 changes: 37 additions & 0 deletions packages/components/test/__snapshots__/index.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,43 @@ exports[`Box renders 1`] = `
</div>
`;

exports[`Box renders with variant array derived variant from theme merge 1`] = `
.emotion-0 {
box-sizing: border-box;
margin: 0;
min-width: 0;
-webkit-appearance: none;
-moz-appearance: none;
-ms-appearance: none;
appearance: none;
display: inline-block;
text-align: center;
line-height: inherit;
-webkit-text-decoration: none;
text-decoration: none;
font-size: inherit;
padding-left: 16px;
padding-right: 16px;
padding-top: 8px;
padding-bottom: 8px;
color: white;
background-color: var(--theme-ui-colors-primary, #0cf);
border: 0;
border-radius: 4px;
color: var(--theme-ui-colors-background, #fefefe);
border: 2px solid undefined;
background-color: transparent;
border-bottom-left-radius: 5px 85px;
border-bottom-right-radius: 75px 5px;
border-top-left-radius: 85px 5px;
border-top-right-radius: 5px 75px;
}

<button
className="emotion-0"
/>
`;

exports[`Button hidden 1`] = `
.emotion-0 {
box-sizing: border-box;
Expand Down
120 changes: 120 additions & 0 deletions packages/components/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ const theme = {
p: 4,
bg: 'highlight',
},
bop: {
m: 1,
bg: 'muted',
},
},
cards: {
primary: {
Expand Down Expand Up @@ -139,6 +143,122 @@ describe('Box', () => {
expect(json).toHaveStyleRule('background-color', 'highlight')
expect(json).toHaveStyleRule('padding', '32px')
})
test('renders with variant array', () => {
const json = renderJSON(
<ThemeProvider theme={theme}>
<Box variant={['boxes.beep', 'boxes.bop']} />
</ThemeProvider>
)
expect(json).toHaveStyleRule('background-color', 'muted')
expect(json).toHaveStyleRule('padding', '32px')
expect(json).toHaveStyleRule('margin', '4px')
})

test('renders with variant array function merge', () => {
const json = renderJSON(
<ThemeProvider
theme={{
colors: {
shadow: '#333333',
},
boxes: {
beep: {
border: (t) => `1px solid ${t.colors.shadow}`,
},
bop: {
border: (t) => `2px solid ${t.colors.shadow}`,
},
},
}}>
<Box variant={['boxes.beep', 'boxes.bop']} />
</ThemeProvider>
)
expect(json).toHaveStyleRule(
'border',
'2px solid var(--theme-ui-colors-shadow, #333333)'
)
})

test('renders with variant array derived variant from theme merge', () => {
jest.spyOn(global.Math, 'random').mockReturnValue(0.4)

const lighten = (color, amount) => {
if (color === '#0cf' && amount === 0.25) {
return '#80e5ff'
}
}

const sketchyBorders = [
{
borderBottomLeftRadius: '5px 85px',
borderBottomRightRadius: '75px 5px',
borderTopLeftRadius: '85px 5px',
borderTopRightRadius: '5px 75px',
},
{
borderBottomLeftRadius: '61px 8px',
borderBottomRightRadius: '6px 68px',
borderTopLeftRadius: '41px 8px',
borderTopRightRadius: '3px 68px',
},
{
borderBottomLeftRadius: '75px 5px',
borderBottomRightRadius: '5px 85px',
borderTopLeftRadius: '5px 75px',
borderTopRightRadius: '85px 5px',
},
]
const randomNumber = () => 0.321;
const borderIndex = Math.floor(randomNumber() * sketchyBorders.length)
const json = renderJSON(
<ThemeProvider
theme={{
colors: {
primary: '#0cf',
text: '#000',
background: '#fefefe',
},
buttons: {
primary: (t) => {
const backgroundColor = lighten(t?.colors?.primary, 0.25)

return {
color: 'background',
border: `2px solid ${backgroundColor}`,
backgroundColor,
}
},
ghost: {
backgroundColor: 'transparent',
},
sketchy: (t) => {
return sketchyBorders[borderIndex]
},
},
}}>
<Button variant={['primary', 'ghost', 'sketchy']} />
</ThemeProvider>
)

expect(json).toMatchSnapshot()

expect(json).toHaveStyleRule(
'border-bottom-left-radius',
sketchyBorders[borderIndex].borderBottomLeftRadius
)
expect(json).toHaveStyleRule(
'border-bottom-right-radius',
sketchyBorders[borderIndex].borderBottomRightRadius
)

expect(json).toHaveStyleRule(
'color',
'var(--theme-ui-colors-background, #fefefe)'
)
expect(json).toHaveStyleRule('background-color', 'transparent')

jest.spyOn(global.Math, 'random').mockRestore()
})

test('renders with base styles', () => {
const json = renderJSON(
Expand Down
40 changes: 31 additions & 9 deletions packages/css/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ThemeDerivedStyles,
Theme,
ThemeUICSSObject,
VariantProperty,
} from './types'

export * from './types'
Expand All @@ -22,6 +23,20 @@ export function get(
return obj === undef ? def : obj
}

export const getVariantValue = (
theme: Theme,
_themeKey: string,
variant: string
): ThemeUICSSObject => {
const defValue = get(theme, variant)
const value = get(
theme,
`${_themeKey}.${variant}`,
typeof defValue === 'function' ? defValue(theme) : defValue
)
return typeof value === 'function' ? value(theme) : value
}

export const defaultBreakpoints = [40, 52, 64].map((n) => n + 'em')

const defaultTheme = {
Expand Down Expand Up @@ -262,8 +277,8 @@ const responsive = (
continue
}
next[media] = next[media] || {}
if (value[i] == null) continue;
(next[media] as Record<string, any>)[key] = value[i]
if (value[i] == null) continue
;(next[media] as Record<string, any>)[key] = value[i]
}
}
return next
Expand All @@ -283,23 +298,30 @@ export const css = (args: ThemeUIStyleObject = {}) => (

// insert variant props before responsive styles, so they can be merged
// we need to maintain order of the style props, so if a variant is place in the middle
// of other props, it will extends its props at that same location order.
// of other props, it will extend its props at that same location order.
if (obj && obj['variant']) {
for (const key in obj) {
const x = obj[key as keyof typeof styles]
if (key === 'variant') {
const val = typeof x === 'function' ? x(theme) : x;
const variant = get(theme, val as string);
result = { ...result, ...variant };
// We could start using the types here to ensure we cover all public API.
const variantName = x as VariantProperty.Variant

// TODO: Is this even documented?
const val = typeof x === 'function' ? x(theme) : x
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hasparus was saying something about removing/changing this? I don't recall exactly

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No idea what was going on there :)

@hasparus - can you pls check, I think there were some suggestions that were really not part of this PR but for v1?


const variant = get(theme, val as string)
result = { ...result, ...variant }
} else {
result[key] = x as CSSObject;
}
result[key] = x as CSSObject
}
}
} else {
result = obj as CSSObject ;
result = obj as CSSObject
}

const styles = responsive(result as ThemeUICSSObject)(theme)
result = {}

for (const key in styles) {
const x = styles[key as keyof typeof styles]
const val = typeof x === 'function' ? x(theme) : x
Expand Down
6 changes: 5 additions & 1 deletion packages/css/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,10 @@ export type ThemeUICSSProperties = {
>
}

export declare namespace VariantProperty {
export type Variant = string | string[]
}

export interface VariantProperty {
/**
* **`Variants`** can be useful for applying complex styles to a component based on a single prop.
Expand All @@ -474,7 +478,7 @@ export interface VariantProperty {
*
* @see https://styled-system.com/variants
*/
variant?: string
variant?: VariantProperty.Variant
}

export interface ThemeDerivedStyles {
Expand Down
38 changes: 38 additions & 0 deletions packages/css/test/temporary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { css, Theme } from '../src'

const theme: Theme = {
buttons: {
'call-to-action': {
fontWeight: 900,
bg: 'hotpink',
color: 'white',
},
},
}

// What's the usecase? Is this documented?
describe('temporary test', () => {
it('is this even documented?', () => {
expect(
JSON.stringify(
css({
variant: ((theme: Theme) => {
const bestButtonVariant = Object.keys(
theme.buttons!
)[0 /* Math.random()? */]

return `buttons.${bestButtonVariant}`
}) as any,
})(theme),
null,
2
)
).toMatchInlineSnapshot(`
"{
\\"fontWeight\\": 900,
\\"backgroundColor\\": \\"hotpink\\",
\\"color\\": \\"white\\"
}"
`)
})
})
11 changes: 11 additions & 0 deletions packages/docs/src/pages/components/variants.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ For example, a secondary button style can be added to `theme.buttons.secondary`
</Button>
```

## Combining Multiple Variants
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## Combining Multiple Variants
## Combining multiple variants


If you want to combine multiple variants on the same element, pass an array of variants with the `variant` prop.
Variant styles are merged from left to right, so if some of the styles conflict, those of the variant passed later will render.

```jsx live=true
<Text variant={['caps', 'heading']}>
Title text
</Text>
```

## Example Theme
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## Example Theme
## Example theme


```js
Expand Down