|
1 | 1 | import {Component} from 'react'; |
| 2 | +import {Provider, Consumer} from '../context'; |
| 3 | +import {h} from '../util'; |
| 4 | +import renderProp from '../util/renderProp'; |
2 | 5 |
|
3 | | -const vars = { |
4 | | - color: 'red' |
5 | | -}; |
| 6 | +let idCnt = 0; |
6 | 7 |
|
7 | | -// export class CssVarsProvider extends Component<any, any> { |
8 | | - // render () { |
9 | | - // return this.props.children; |
10 | | - // } |
11 | | -// } |
| 8 | +const supportsCssVariables = typeof window === 'object' && (window as any).CSS && CSS.supports && CSS.supports('--a', '0'); |
| 9 | + |
| 10 | +export type TVars = {[name: string]: string}; |
| 11 | + |
| 12 | +export interface ICssVarsProviderProps { |
| 13 | + ns?: string; |
| 14 | + prefix?: string; |
| 15 | + vars: TVars; |
| 16 | +} |
| 17 | + |
| 18 | +export interface ICssVarsProviderState { |
| 19 | +} |
| 20 | + |
| 21 | +export class CssVarsProvider extends Component<ICssVarsProviderProps, ICssVarsProviderState> { |
| 22 | + vars: TVars = {}; |
| 23 | + |
| 24 | + constructor (props, context) { |
| 25 | + super(props, context); |
| 26 | + |
| 27 | + this.updateVars(props.vars); |
| 28 | + } |
| 29 | + |
| 30 | + updateVars (vars: TVars) { |
| 31 | + if (supportsCssVariables) { |
| 32 | + const {prefix = ''} = this.props; |
| 33 | + const {style} = document.documentElement; |
| 34 | + |
| 35 | + for (const name in vars) { |
| 36 | + const id = (idCnt++).toString(36); |
| 37 | + const varName = `---${prefix}${id}`; |
| 38 | + |
| 39 | + this.vars[name] = `var(${varName})`; |
| 40 | + style.setProperty(varName, String(vars[name])); |
| 41 | + } |
| 42 | + } else { |
| 43 | + this.vars = vars; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + render () { |
| 48 | + return h(Provider, { |
| 49 | + name: 'css/' + this.props.ns, |
| 50 | + value: this.vars |
| 51 | + }, |
| 52 | + this.props.children |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +export interface ICssVarsProps { |
| 58 | + children?: any; |
| 59 | + render?: any; |
| 60 | + component?: any; |
| 61 | + comp?: any; |
| 62 | + ns?: string; |
| 63 | +} |
| 64 | + |
| 65 | +export interface ICssVarsState { |
| 66 | +} |
| 67 | + |
| 68 | +export class CssVars extends Component<ICssVarsProps, ICssVarsState> { |
| 69 | + render () { |
| 70 | + return h(Consumer, {name: 'css/' + this.props.ns}, (vars) => { |
| 71 | + return renderProp(this.props, vars); |
| 72 | + }); |
| 73 | + } |
| 74 | +} |
0 commit comments