UNPKG

21.5 kBJavaScriptView Raw
1'use strict';
2
3function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
5var React = _interopDefault(require('react'));
6var glamor = require('glamor');
7
8var CHANNEL = '__glamorous__'; /* istanbul ignore next */
9
10var isPreact = false;
11
12var _PropTypes = void 0;
13
14/* istanbul ignore next */
15if (isPreact) {
16 if (!React.PropTypes) {
17 _PropTypes = function PropTypes() {
18 return _PropTypes;
19 };
20
21 ['array', 'bool', 'func', 'number', 'object', 'string', 'symbol', 'any', 'arrayOf', 'element', 'instanceOf', 'node', 'objectOf', 'oneOf', 'oneOfType', 'shape', 'exact'].forEach(function (type) {
22 _PropTypes[type] = _PropTypes;
23 });
24 }
25 // copied from preact-compat
26 /* eslint-disable no-eq-null, eqeqeq, consistent-return */
27 if (!React.Children) {
28 var Children = {
29 map: function map(children, fn, ctx) {
30 if (children == null) {
31 return null;
32 }
33 children = Children.toArray(children);
34 if (ctx && ctx !== children) {
35 fn = fn.bind(ctx);
36 }
37 return children.map(fn);
38 },
39 forEach: function forEach(children, fn, ctx) {
40 if (children == null) {
41 return null;
42 }
43 children = Children.toArray(children);
44 if (ctx && ctx !== children) {
45 fn = fn.bind(ctx);
46 }
47 children.forEach(fn);
48 },
49 count: function count(children) {
50 return children && children.length || 0;
51 },
52 only: function only(children) {
53 children = Children.toArray(children);
54 if (children.length !== 1) {
55 throw new Error('Children.only() expects only one child.');
56 }
57 return children[0];
58 },
59 toArray: function toArray(children) {
60 if (children == null) {
61 return [];
62 }
63 return [].concat(children);
64 }
65 };
66 React.Children = Children;
67 }
68 /* eslint-enable no-eq-null, eqeqeq, consistent-return */
69} else if (parseFloat(React.version.slice(0, 4)) >= 15.5) {
70 /* istanbul ignore next */
71 try {
72 _PropTypes = require('prop-types');
73 /* istanbul ignore next */
74 } catch (error) {
75 // ignore
76 }
77}
78/* istanbul ignore next */
79_PropTypes = _PropTypes || React.PropTypes;
80
81/*
82eslint
83 import/no-mutable-exports:0,
84 import/prefer-default-export:0,
85 react/no-deprecated:0
86 */
87
88var classCallCheck = function (instance, Constructor) {
89 if (!(instance instanceof Constructor)) {
90 throw new TypeError("Cannot call a class as a function");
91 }
92};
93
94var _extends = Object.assign || function (target) {
95 for (var i = 1; i < arguments.length; i++) {
96 var source = arguments[i];
97
98 for (var key in source) {
99 if (Object.prototype.hasOwnProperty.call(source, key)) {
100 target[key] = source[key];
101 }
102 }
103 }
104
105 return target;
106};
107
108var inherits = function (subClass, superClass) {
109 if (typeof superClass !== "function" && superClass !== null) {
110 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
111 }
112
113 subClass.prototype = Object.create(superClass && superClass.prototype, {
114 constructor: {
115 value: subClass,
116 enumerable: false,
117 writable: true,
118 configurable: true
119 }
120 });
121 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
122};
123
124var objectWithoutProperties = function (obj, keys) {
125 var target = {};
126
127 for (var i in obj) {
128 if (keys.indexOf(i) >= 0) continue;
129 if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
130 target[i] = obj[i];
131 }
132
133 return target;
134};
135
136var possibleConstructorReturn = function (self, call) {
137 if (!self) {
138 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
139 }
140
141 return call && (typeof call === "object" || typeof call === "function") ? call : self;
142};
143
144function generateWarningMessage(Comp) {
145 var componentName = Comp.displayName || Comp.name || 'FunctionComponent';
146 // eslint-disable-next-line max-len
147 return 'glamorous warning: Expected component called "' + componentName + '" which uses withTheme to be within a ThemeProvider but none was found.';
148}
149
150function withTheme(ComponentToTheme) {
151 var _defaultContextTypes;
152
153 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
154 _ref$noWarn = _ref.noWarn,
155 noWarn = _ref$noWarn === undefined ? false : _ref$noWarn,
156 _ref$createElement = _ref.createElement,
157 createElement = _ref$createElement === undefined ? true : _ref$createElement;
158
159 var ThemedComponent = function (_React$Component) {
160 inherits(ThemedComponent, _React$Component);
161
162 function ThemedComponent() {
163 var _temp, _this, _ret;
164
165 classCallCheck(this, ThemedComponent);
166
167 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
168 args[_key] = arguments[_key];
169 }
170
171 return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.warned = noWarn, _this.state = { theme: {} }, _this.setTheme = function (theme) {
172 return _this.setState({ theme: theme });
173 }, _temp), possibleConstructorReturn(_this, _ret);
174 }
175
176 // eslint-disable-next-line complexity
177 ThemedComponent.prototype.componentWillMount = function componentWillMount() {
178 if (!this.context[CHANNEL]) {
179 if (process.env.NODE_ENV !== 'production' && !this.warned) {
180 this.warned = true;
181 // eslint-disable-next-line no-console
182 console.warn(generateWarningMessage(ComponentToTheme));
183 }
184 }
185 var theme = this.props.theme;
186
187 if (this.context[CHANNEL]) {
188 // if a theme is provided via props,
189 // it takes precedence over context
190 this.setTheme(theme ? theme : this.context[CHANNEL].getState());
191 } else {
192 this.setTheme(theme || {});
193 }
194 };
195
196 ThemedComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
197 if (this.props.theme !== nextProps.theme) {
198 this.setTheme(nextProps.theme);
199 }
200 };
201
202 ThemedComponent.prototype.componentDidMount = function componentDidMount() {
203 if (this.context[CHANNEL] && !this.props.theme) {
204 // subscribe to future theme changes
205 this.subscriptionId = this.context[CHANNEL].subscribe(this.setTheme);
206 }
207 };
208
209 ThemedComponent.prototype.componentWillUnmount = function componentWillUnmount() {
210 // cleanup subscription
211 this.subscriptionId && this.context[CHANNEL].unsubscribe(this.subscriptionId);
212 };
213
214 ThemedComponent.prototype.render = function render() {
215 if (createElement) {
216 return React.createElement(ComponentToTheme, _extends({}, this.props, this.state));
217 } else {
218 // this allows us to effectively use the GlamorousComponent
219 // as our `render` method without going through lifecycle hooks.
220 // Also allows us to forward the context in the scenario where
221 // a user wants to add more context.
222 // eslint-disable-next-line babel/new-cap
223 return ComponentToTheme.call(this, _extends({}, this.props, this.state), this.context);
224 }
225 };
226
227 return ThemedComponent;
228 }(React.Component);
229
230 process.env.NODE_ENV !== "production" ? ThemedComponent.propTypes = {
231 theme: _PropTypes.object
232 } : void 0;
233
234
235 var defaultContextTypes = (_defaultContextTypes = {}, _defaultContextTypes[CHANNEL] = _PropTypes.object, _defaultContextTypes);
236
237 var userDefinedContextTypes = null;
238
239 // configure the contextTypes to be settable by the user,
240 // however also retaining the glamorous channel.
241 Object.defineProperty(ThemedComponent, 'contextTypes', {
242 enumerable: true,
243 configurable: true,
244 set: function set$$1(value) {
245 userDefinedContextTypes = value;
246 },
247 get: function get$$1() {
248 // if the user has provided a contextTypes definition,
249 // merge the default context types with the provided ones.
250 if (userDefinedContextTypes) {
251 return _extends({}, defaultContextTypes, userDefinedContextTypes);
252 }
253 return defaultContextTypes;
254 }
255 });
256
257 return ThemedComponent;
258}
259
260/**
261 * This function takes a className string and gets all the
262 * associated glamor styles. It's used to merge glamor styles
263 * from a className to make sure that specificity is not
264 * a problem when passing a className to a component.
265 * @param {String} [className=''] the className string
266 * @return {Object} { glamorStyles, glamorlessClassName }
267 * - glamorStyles is an array of all the glamor styles objects
268 * - glamorlessClassName is the rest of the className string
269 * without the glamor classNames
270 */
271function extractGlamorStyles(className) {
272 var glamorlessClassName = [];
273 var glamorStyles = [];
274 className.toString().split(' ').forEach(function (name) {
275 if (glamor.styleSheet.registered[name.substring(4)] === undefined) {
276 glamorlessClassName.push(name);
277 } else {
278 var style = buildGlamorSrcFromClassName(name);
279 glamorStyles.push(style);
280 }
281 });
282
283 return { glamorlessClassName: glamorlessClassName, glamorStyles: glamorStyles };
284}
285
286/** Glamor's css function returns an object with the shape
287 *
288 * {
289 * [`data-css-${hash}`]: '',
290 * toString() { return `css-${hash}` }
291 * }
292 *
293 * Whenever glamor's build function encounters an object with
294 * this shape it just pulls the resulting styles from the cache.
295 *
296 * note: the toString method is not needed to qualify the shape
297 **/
298function buildGlamorSrcFromClassName(className) {
299 var _ref;
300
301 return _ref = {}, _ref['data-' + className] = '', _ref;
302}
303
304function getGlamorClassName(_ref2) {
305 var styles = _ref2.styles,
306 props = _ref2.props,
307 cssOverrides = _ref2.cssOverrides,
308 cssProp = _ref2.cssProp,
309 context = _ref2.context,
310 displayName = _ref2.displayName;
311
312 var _handleStyles = handleStyles([].concat(styles, [props.className, cssOverrides, cssProp]), props, context),
313 mappedArgs = _handleStyles.mappedArgs,
314 nonGlamorClassNames = _handleStyles.nonGlamorClassNames;
315 // eslint-disable-next-line max-len
316
317
318 var isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
319 var devRules = isDev ? { label: displayName } : null;
320 var glamorClassName = glamor.css.apply(undefined, [devRules].concat(mappedArgs)).toString();
321 var extras = nonGlamorClassNames.join(' ').trim();
322 return (glamorClassName + ' ' + extras).trim();
323}
324
325// this next function is on a "hot" code-path
326// so it's pretty complex to make sure it's fast.
327// eslint-disable-next-line complexity
328function handleStyles(styles, props, context) {
329 var current = void 0;
330 var mappedArgs = [];
331 var nonGlamorClassNames = [];
332 for (var i = 0; i < styles.length; i++) {
333 current = styles[i];
334 while (typeof current === 'function') {
335 current = current(props, context);
336 }
337 if (typeof current === 'string') {
338 var _extractGlamorStyles = extractGlamorStyles(current),
339 glamorStyles = _extractGlamorStyles.glamorStyles,
340 glamorlessClassName = _extractGlamorStyles.glamorlessClassName;
341
342 mappedArgs.push.apply(mappedArgs, glamorStyles);
343 nonGlamorClassNames.push.apply(nonGlamorClassNames, glamorlessClassName);
344 } else if (Array.isArray(current)) {
345 var recursed = handleStyles(current, props, context);
346 mappedArgs.push.apply(mappedArgs, recursed.mappedArgs);
347 nonGlamorClassNames.push.apply(nonGlamorClassNames, recursed.nonGlamorClassNames);
348 } else {
349 mappedArgs.push(current);
350 }
351 }
352 return { mappedArgs: mappedArgs, nonGlamorClassNames: nonGlamorClassNames };
353}
354
355/*
356 * This is a relatively small abstraction that's ripe for open sourcing.
357 * Documentation is in the README.md
358 */
359
360function createGlamorous(splitProps) {
361 return glamorous;
362
363 /**
364 * This is the main export and the function that people
365 * interact with most directly.
366 *
367 * It accepts a component which can be a string or
368 * a React Component and returns
369 * a "glamorousComponentFactory"
370 * @param {String|ReactComponent} comp the component to render
371 * @param {Object} options helpful info for the GlamorousComponents
372 * @return {Function} the glamorousComponentFactory
373 */
374 function glamorous(comp) {
375 var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
376 var rootEl = config.rootEl,
377 displayName = config.displayName,
378 shouldClassNameUpdate = config.shouldClassNameUpdate,
379 _config$filterProps = config.filterProps,
380 filterProps = _config$filterProps === undefined ? [] : _config$filterProps,
381 _config$forwardProps = config.forwardProps,
382 forwardProps = _config$forwardProps === undefined ? [] : _config$forwardProps,
383 _config$propsAreCssOv = config.propsAreCssOverrides,
384 propsAreCssOverrides = _config$propsAreCssOv === undefined ? comp.propsAreCssOverrides : _config$propsAreCssOv,
385 basePropsToApply = config.withProps;
386
387 Object.assign(glamorousComponentFactory, { withConfig: withConfig });
388 return glamorousComponentFactory;
389
390 function withConfig(newConfig) {
391 return glamorous(comp, _extends({}, config, newConfig));
392 }
393
394 /**
395 * This returns a React Component that renders the comp (closure)
396 * with a className based on the given glamor styles object(s)
397 * @param {...Object|Function} styles the styles to create with glamor.
398 * If any of these are functions, they are invoked with the component
399 * props and the return value is used.
400 * @return {ReactComponent} the ReactComponent function
401 */
402 function glamorousComponentFactory() {
403 for (var _len = arguments.length, styles = Array(_len), _key = 0; _key < _len; _key++) {
404 styles[_key] = arguments[_key];
405 }
406
407 /**
408 * This is a component which will render the comp (closure)
409 * with the glamorous styles (closure). Forwards any valid
410 * props to the underlying component.
411 */
412 var GlamorousComponent = withTheme(function (props, context) {
413 props = getPropsToApply(GlamorousComponent.propsToApply, {}, props, context);
414 var updateClassName = shouldUpdate(props, context, this.previous);
415
416 if (shouldClassNameUpdate) {
417 this.previous = { props: props, context: context };
418 }
419
420 var _splitProps = splitProps(props, GlamorousComponent),
421 toForward = _splitProps.toForward,
422 cssOverrides = _splitProps.cssOverrides,
423 cssProp = _splitProps.cssProp;
424
425 // create className to apply
426
427
428 this.className = updateClassName ? getGlamorClassName({
429 styles: GlamorousComponent.styles,
430 props: props,
431 cssOverrides: cssOverrides,
432 cssProp: cssProp,
433 context: context,
434 displayName: GlamorousComponent.displayName
435 }) : this.className;
436
437 return React.createElement(GlamorousComponent.comp, _extends({
438 // if innerRef is forwarded we don't want to apply it here
439 ref: 'innerRef' in toForward ? undefined : props.innerRef
440 }, toForward, {
441 className: this.className
442 }));
443 }, { noWarn: true, createElement: false });
444
445 process.env.NODE_ENV !== "production" ? GlamorousComponent.propTypes = {
446 // className accepts an object due to glamor's css function
447 // returning an object with a toString method that gives the className
448 className: _PropTypes.oneOfType([_PropTypes.string, _PropTypes.object]),
449 cssOverrides: _PropTypes.object,
450 innerRef: _PropTypes.oneOfType([_PropTypes.func, _PropTypes.object]),
451 glam: _PropTypes.object
452 } : void 0;
453
454 function shouldUpdate(props, context, previous) {
455 // exiting early so components which do not use this
456 // optimization are not penalized by hanging onto
457 // references to previous props and context
458 if (!shouldClassNameUpdate) {
459 return true;
460 }
461 var update = true;
462 if (previous) {
463 if (!shouldClassNameUpdate(previous.props, props, previous.context, context)) {
464 update = false;
465 }
466 }
467
468 return update;
469 }
470
471 Object.assign(GlamorousComponent, getGlamorousComponentMetadata({
472 comp: comp,
473 styles: styles,
474 rootEl: rootEl,
475 filterProps: filterProps,
476 forwardProps: forwardProps,
477 displayName: displayName,
478 propsToApply: basePropsToApply
479 }), {
480 isGlamorousComponent: true,
481 propsAreCssOverrides: propsAreCssOverrides,
482 withComponent: function (newComp) {
483 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
484 var fwp = GlamorousComponent.forwardProps,
485 flp = GlamorousComponent.filterProps,
486 componentProperties = objectWithoutProperties(GlamorousComponent, ['forwardProps', 'filterProps']);
487
488 return glamorous(_extends({}, componentProperties, {
489 comp: newComp,
490 rootEl: getRootEl(newComp)
491 }), _extends({
492 // allows the forwardProps and filterProps to be overridden
493 forwardProps: fwp,
494 filterProps: flp
495 }, options))();
496 },
497 withProps: function () {
498 for (var _len2 = arguments.length, propsToApply = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
499 propsToApply[_key2] = arguments[_key2];
500 }
501
502 return glamorous(GlamorousComponent, { withProps: propsToApply })();
503 },
504 withConfig: withConfig
505 });
506 return GlamorousComponent;
507 }
508 }
509
510 function getGlamorousComponentMetadata(_ref) {
511 var comp = _ref.comp,
512 styles = _ref.styles,
513 rootEl = _ref.rootEl,
514 filterProps = _ref.filterProps,
515 forwardProps = _ref.forwardProps,
516 displayName = _ref.displayName,
517 basePropsToApply = _ref.propsToApply;
518
519 var componentsComp = comp.comp ? comp.comp : comp;
520 var propsToApply = comp.propsToApply ? [].concat(comp.propsToApply, arrayify(basePropsToApply)) : arrayify(basePropsToApply);
521 return {
522 // join styles together (for anyone doing: glamorous(glamorous.a({}), {}))
523 styles: when(comp.styles, styles),
524 // keep track of the ultimate rootEl to render (we never
525 // actually render anything but
526 // the base component, even when people wrap a glamorous
527 // component in glamorous
528 comp: componentsComp,
529 rootEl: rootEl || getRootEl(comp),
530 // join forwardProps and filterProps
531 // (for anyone doing: glamorous(glamorous.a({}), {}))
532 forwardProps: when(comp.forwardProps, forwardProps),
533 filterProps: when(comp.filterProps, filterProps),
534 // set the displayName to something that's slightly more
535 // helpful than `GlamorousComponent` :)
536 displayName: displayName || 'glamorous(' + getDisplayName(comp) + ')',
537 // these are props that should be applied to the component at render time
538 propsToApply: propsToApply
539 };
540 }
541}
542
543/**
544 * reduces the propsToApply given to a single props object
545 * @param {Array} propsToApply an array of propsToApply objects:
546 * - object
547 * - array of propsToApply items
548 * - function that accepts the accumulated props and the context
549 * @param {Object} accumulator an object to apply props onto
550 * @param {Object} props the props that should ultimately take precedence
551 * @param {*} context the context object
552 * @return {Object} the reduced props
553 */
554function getPropsToApply(propsToApply, accumulator, props, context) {
555 // using forEach rather than reduce here because the reduce solution
556 // effectively did the same thing because we manipulate the `accumulator`
557 propsToApply.forEach(function (propsToApplyItem) {
558 if (typeof propsToApplyItem === 'function') {
559 return Object.assign(accumulator, propsToApplyItem(Object.assign({}, accumulator, props), context));
560 } else if (Array.isArray(propsToApplyItem)) {
561 return Object.assign(accumulator, getPropsToApply(propsToApplyItem, accumulator, props, context));
562 }
563 return Object.assign(accumulator, propsToApplyItem);
564 });
565 // props wins
566 return Object.assign(accumulator, props);
567}
568
569function arrayify() {
570 var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
571
572 return Array.isArray(x) ? x : [x];
573}
574
575function when(comp, prop) {
576 return comp ? comp.concat(prop) : prop;
577}
578
579function getRootEl(comp) {
580 return comp.rootEl ? comp.rootEl : comp.comp || comp;
581}
582
583function getDisplayName(comp) {
584 return typeof comp === 'string' ? comp : comp.displayName || comp.name || 'unknown';
585}
586
587/* eslint no-unused-vars:0 */
588
589function splitProps(_ref, _ref2) {
590 var forwardProps = _ref2.forwardProps;
591 var cssProp = _ref.css,
592 innerRef = _ref.innerRef,
593 theme = _ref.theme,
594 className = _ref.className,
595 glam = _ref.glam,
596 rest = objectWithoutProperties(_ref, ['css', 'innerRef', 'theme', 'className', 'glam']);
597
598 // forward innerRef if user wishes to do so
599 if (innerRef !== undefined && forwardProps.indexOf('innerRef') !== -1) {
600 rest.innerRef = innerRef;
601 }
602 return { toForward: rest, cssProp: cssProp };
603}
604
605var glamorous = createGlamorous(splitProps);
606
607module.exports = glamorous;