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

feat: Add merging array of variants #1226

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -969,6 +969,7 @@ Theme UI is now written in TypeScript, and the emitted types differ from

### `@theme-ui/core`

- Add ability to use arrays to merge variants. Issues #1209 #1208, PR #1226
- 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
5 changes: 3 additions & 2 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 @@ -17,7 +18,7 @@ const shouldForwardProp = createShouldForwardProp(boxSystemProps)
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)))
css(getVariantValue(theme, variant, __themeKey))

export const Box = styled('div', {
shouldForwardProp,
Expand Down
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
129 changes: 129 additions & 0 deletions packages/components/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ const theme = {
p: 4,
bg: 'highlight',
},
bop: {
m: 1,
bg: 'muted',
},
},
cards: {
primary: {
Expand Down Expand Up @@ -146,6 +150,131 @@ describe('Box', () => {
expect(json).toHaveStyleRule('background-color', 'highlight')
expect(json).toHaveStyleRule('padding', '32px')
})
it('renders with variant prop as a function', () => {
const json = renderJSON(
<ThemeProvider theme={theme}>
<Box variant={(theme) => `boxes.${Object.keys(theme.boxes)[0]}`} />
</ThemeProvider>
)
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(
atanasster marked this conversation as resolved.
Show resolved Hide resolved
'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
3 changes: 2 additions & 1 deletion packages/css/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
},
"dependencies": {
"@emotion/react": "^11.4.1",
"csstype": "^3.0.9"
"csstype": "^3.0.9",
"deepmerge": "^4.2.2"
},
"preconstruct": {
"entrypoints": [
Expand Down
33 changes: 31 additions & 2 deletions packages/css/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import deepmerge from 'deepmerge'
import type {
CSSObject,
ThemeUIStyleObject,
ThemeDerivedStyles,
Theme,
ThemeUICSSObject,
VariantProperty,
} from './types'

export * from './types'
Expand Down Expand Up @@ -53,14 +55,41 @@ export function get(
return hasDefault(obj) ? obj[THEME_UI_DEFAULT_KEY] : obj
}

export const getValue = (
theme: Theme,
key: string,
_themeKey?: string
): ThemeUICSSObject => {
const defValue = _themeKey ? get(theme, key) : undefined
const value = get(
theme,
_themeKey ? `${_themeKey}.${key}` : key,
typeof defValue === 'function' ? defValue(theme) : defValue
)
return typeof value === 'function' ? value(theme) : value
}
export const getVariantValue = (
theme: Theme,
variant: VariantProperty.Variant,
_themeKey?: string
): ThemeUICSSObject => {
const key = typeof variant === 'function' ? variant(theme) : variant
if (Array.isArray(key)) {
return deepmerge.all(
key.map((v) => getValue(theme, v, _themeKey) || {}),
{ arrayMerge: (_dest, src) => src }
) as ThemeUICSSObject
}
return getValue(theme, key, _themeKey)
}

export const getObjectWithVariants = (obj: any, theme: Theme): CSSObject => {
if (obj && obj['variant']) {
let result: CSSObject = {}
for (const key in obj) {
const x = obj[key]
if (key === 'variant') {
const val = typeof x === 'function' ? x(theme) : x
const variant = getObjectWithVariants(get(theme, val as string), theme)
const variant = getObjectWithVariants(getVariantValue(theme, x), theme)
result = { ...result, ...variant }
} else {
result[key] = x as CSSObject
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 @@ -446,6 +446,10 @@ export type ThemeUICSSProperties = {
>
}

export declare namespace VariantProperty {
export type Variant = string | string[] | ((theme: Theme) => string)
}

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

export interface ThemeDerivedStyles {
Expand Down
27 changes: 27 additions & 0 deletions packages/css/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,34 @@ test('handles responsive variants', () => {
},
})
})
test('merge array of variant', () => {
const result = css({
variant: ['buttons.primary', 'buttons.round'],
})(theme)
expect(result).toEqual({
padding: 16,
fontWeight: 600,
color: 'white',
width: '100%',
height: '100%',
overflow: 'hidden',
borderRadius: '50%',
backgroundColor: 'tomato',
})
})

it('invoke variants as a function', () => {
const result = css({
variant: (theme: Theme) => `buttons.${Object.keys(theme.buttons!)[3]}`,
})(theme)
expect(result).toEqual({
width: '100%',
height: '100%',
overflow: 'hidden',
borderRadius: '50%',
backgroundColor: 'tomato',
})
})
test('handles negative margins from scale', () => {
const result = css({
mt: -3,
Expand Down
25 changes: 24 additions & 1 deletion packages/docs/src/pages/components/variants.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,30 @@ For example, a secondary button style can be added to `theme.buttons.secondary`
<Button variant="secondary">Secondary</Button>
```

## 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

## 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>
```

## Variant as a function

If you need to determine variants at run-time, pass a function to the `variant` prop.

```jsx live=true
<Box
variant={(theme) => {
const buttonVariant = Object.keys(theme.buttons)[0]
return `buttons.${buttonVariant}`
}}>
some text
</Box>
```

## Example theme

```js
// example theme
Expand Down
Loading