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 ClassNames component #828

Merged
merged 9 commits into from
Sep 27, 2018
Merged
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
2 changes: 1 addition & 1 deletion flow-typed/npm/jest_v21.x.x.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ type JestExpectType = {
*/
toMatchSnapshot(name?: string): void,
toMatchInlineSnapshot(...args: any): void,

toThrowErrorMatchingInlineSnapshot(...args: any): void,
/**
* Use .toThrow to test that a function throws when it is called.
* If you want to test that a specific error gets thrown, you can provide an
Expand Down
32 changes: 32 additions & 0 deletions packages/core/__tests__/__snapshots__/class-names.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`css 1`] = `
.emotion-0 {
color: hotpink;
}

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

exports[`cx 1`] = `
.emotion-0 {
color: hotpink;
color: green;
}

<div
className="some-other-class emotion-0"
/>
`;

exports[`should get the theme 1`] = `
.emotion-0 {
color: green;
}

<div
className="emotion-0"
/>
`;
86 changes: 86 additions & 0 deletions packages/core/__tests__/class-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// @flow
import * as React from 'react'
import 'test-utils/next-env'
import { ClassNames } from '@emotion/core'
import { ThemeProvider } from 'emotion-theming'
import renderer from 'react-test-renderer'

test('css', () => {
const tree = renderer.create(
<ClassNames>
{({ css }) => (
<div
className={css`
color: hotpink;
`}
/>
)}
</ClassNames>
)

expect(tree.toJSON()).toMatchSnapshot()
})

it('should get the theme', () => {
const tree = renderer.create(
<ThemeProvider theme={{ color: 'green' }}>
<ClassNames>
{({ css, theme }) => (
<div
className={css`
color: ${theme.color};
`}
/>
)}
</ClassNames>
</ThemeProvider>
)

expect(tree.toJSON()).toMatchSnapshot()
})

test('cx', () => {
const tree = renderer.create(
<ClassNames>
{({ css, cx }) => {
let secondClassButItsInsertedFirst = css`
color: green;
`
let firstClassButItsInsertedSecond = css`
color: hotpink;
`

return (
<div
className={cx(
firstClassButItsInsertedSecond,
'some-other-class',
secondClassButItsInsertedFirst
)}
/>
)
}}
</ClassNames>
)

expect(tree.toJSON()).toMatchSnapshot()
})

test('css and cx throws when used after render', () => {
let cx, css
renderer.create(
<ClassNames>
{arg => {
;({ cx, css } = arg)
return null
}}
</ClassNames>
)

expect(cx).toThrowErrorMatchingInlineSnapshot(
`"cx can only be used during render"`
)
expect(css).toThrowErrorMatchingInlineSnapshot(
`"css can only be used during render"`
)
})
120 changes: 120 additions & 0 deletions packages/core/src/class-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// @flow
import * as React from 'react'
import { getRegisteredStyles, insertStyles, isBrowser } from '@emotion/utils'
import { serializeStyles } from '@emotion/serialize'
import { withEmotionCache, ThemeContext } from './context'

type ClassNameArg =
| string
| boolean
| { [key: string]: boolean }
| Array<ClassNameArg>

let classnames = (args: Array<ClassNameArg>): string => {
let len = args.length
let i = 0
let cls = ''
for (; i < len; i++) {
let arg = args[i]
if (arg == null) continue

let toAdd
switch (typeof arg) {
case 'boolean':
break
case 'object': {
if (Array.isArray(arg)) {
toAdd = classnames(arg)
} else {
toAdd = ''
for (const k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ')
toAdd += k
}
}
}
break
}
default: {
toAdd = arg
}
}
if (toAdd) {
cls && (cls += ' ')
cls += toAdd
}
}
return cls
}
function merge(registered: Object, css: (*) => string, className: string) {
const registeredStyles = []

const rawClassName = getRegisteredStyles(
registered,
registeredStyles,
className
)

if (registeredStyles.length < 2) {
return className
}
return rawClassName + css(registeredStyles)
}

export const ClassNames = withEmotionCache((props, context) => {
return (
<ThemeContext.Consumer>
{theme => {
let rules = ''
let serializedHashes = ''
let hasRendered = false

let css = (...args) => {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('css can only be used during render')
}
let serialized = serializeStyles(context.registered, args)
if (isBrowser) {
insertStyles(context, serialized, false)
} else {
let res = insertStyles(context, serialized, false)
if (res !== undefined) {
rules += res
}
}
if (!isBrowser) {
serializedHashes += ` ${serialized.name}`
}
return `${context.key}-${serialized.name}`
}
let cx = (...args: Array<ClassNameArg>) => {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('cx can only be used during render')
}
return merge(context.registered, css, classnames(args))
}
let content = { css, cx, theme }
let ele = props.children(content)
hasRendered = true
if (!isBrowser && rules !== undefined) {
return (
<React.Fragment>
<style
{...{
[`data-emotion-${context.key}`]: serializedHashes.substring(
1
),
dangerouslySetInnerHTML: { __html: rules },
nonce: context.sheet.nonce
}}
/>
{ele}
</React.Fragment>
)
}
return ele
}}
</ThemeContext.Consumer>
)
})
2 changes: 1 addition & 1 deletion packages/core/src/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import createCache from '@emotion/cache'

let EmotionCacheContext = React.createContext(isBrowser ? createCache() : null)

export let ThemeContext = React.createContext({})
export let ThemeContext = React.createContext<Object>({})
export let CacheProvider: React.ComponentType<{ value: EmotionCache }> =
// $FlowFixMe
EmotionCacheContext.Provider
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export { withEmotionCache, CacheProvider, ThemeContext } from './context'
export { jsx } from './jsx'
export { Global } from './global'
export { keyframes } from './keyframes'
export { ClassNames } from './class-names'
export { default as css } from '@emotion/css'
2 changes: 1 addition & 1 deletion packages/react-emotion/test/composition.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ test('composition', () => {
`

const H2 = styled(H1)`
font-size: ${fontSize * 2 / 3 + 'px'};
font-size: ${(fontSize * 2) / 3 + 'px'};
`

const tree = renderer
Expand Down