UNPKG

21.6 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('glamor')) :
3 typeof define === 'function' && define.amd ? define(['react', 'glamor'], factory) :
4 (global.glamorous = factory(global.React,global.Glamor));
5}(this, (function (React,glamor) { 'use strict';
6
7React = React && React.hasOwnProperty('default') ? React['default'] : React;
8
9var CHANNEL = '__glamorous__'; /* istanbul ignore next */
10
11var isPreact = false;
12
13var _PropTypes = void 0;
14
15/* istanbul ignore next */
16if (isPreact) {
17 if (!React.PropTypes) {
18 _PropTypes = function PropTypes() {
19 return _PropTypes;
20 };
21
22 ['array', 'bool', 'func', 'number', 'object', 'string', 'symbol', 'any', 'arrayOf', 'element', 'instanceOf', 'node', 'objectOf', 'oneOf', 'oneOfType', 'shape', 'exact'].forEach(function (type) {
23 _PropTypes[type] = _PropTypes;
24 });
25 }
26 // copied from preact-compat
27 /* eslint-disable no-eq-null, eqeqeq, consistent-return */
28 if (!React.Children) {
29 var Children = {
30 map: function map(children, fn, ctx) {
31 if (children == null) {
32 return null;
33 }
34 children = Children.toArray(children);
35 if (ctx && ctx !== children) {
36 fn = fn.bind(ctx);
37 }
38 return children.map(fn);
39 },
40 forEach: function forEach(children, fn, ctx) {
41 if (children == null) {
42 return null;
43 }
44 children = Children.toArray(children);
45 if (ctx && ctx !== children) {
46 fn = fn.bind(ctx);
47 }
48 children.forEach(fn);
49 },
50 count: function count(children) {
51 return children && children.length || 0;
52 },
53 only: function only(children) {
54 children = Children.toArray(children);
55 if (children.length !== 1) {
56 throw new Error('Children.only() expects only one child.');
57 }
58 return children[0];
59 },
60 toArray: function toArray(children) {
61 if (children == null) {
62 return [];
63 }
64 return [].concat(children);
65 }
66 };
67 React.Children = Children;
68 }
69 /* eslint-enable no-eq-null, eqeqeq, consistent-return */
70} else if (parseFloat(React.version.slice(0, 4)) >= 15.5) {
71 /* istanbul ignore next */
72 try {
73 _PropTypes = (typeof window !== 'undefined' ? window : global).PropTypes;
74 /* istanbul ignore next */
75 } catch (error) {
76 // ignore
77 }
78}
79/* istanbul ignore next */
80_PropTypes = _PropTypes || React.PropTypes;
81
82/*
83eslint
84 import/no-mutable-exports:0,
85 import/prefer-default-export:0,
86 react/no-deprecated:0
87 */
88
89var classCallCheck = function (instance, Constructor) {
90 if (!(instance instanceof Constructor)) {
91 throw new TypeError("Cannot call a class as a function");
92 }
93};
94
95var _extends = Object.assign || function (target) {
96 for (var i = 1; i < arguments.length; i++) {
97 var source = arguments[i];
98
99 for (var key in source) {
100 if (Object.prototype.hasOwnProperty.call(source, key)) {
101 target[key] = source[key];
102 }
103 }
104 }
105
106 return target;
107};
108
109var inherits = function (subClass, superClass) {
110 if (typeof superClass !== "function" && superClass !== null) {
111 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
112 }
113
114 subClass.prototype = Object.create(superClass && superClass.prototype, {
115 constructor: {
116 value: subClass,
117 enumerable: false,
118 writable: true,
119 configurable: true
120 }
121 });
122 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
123};
124
125var objectWithoutProperties = function (obj, keys) {
126 var target = {};
127
128 for (var i in obj) {
129 if (keys.indexOf(i) >= 0) continue;
130 if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
131 target[i] = obj[i];
132 }
133
134 return target;
135};
136
137var possibleConstructorReturn = function (self, call) {
138 if (!self) {
139 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
140 }
141
142 return call && (typeof call === "object" || typeof call === "function") ? call : self;
143};
144
145function generateWarningMessage(Comp) {
146 var componentName = Comp.displayName || Comp.name || 'FunctionComponent';
147 // eslint-disable-next-line max-len
148 return 'glamorous warning: Expected component called "' + componentName + '" which uses withTheme to be within a ThemeProvider but none was found.';
149}
150
151function withTheme(ComponentToTheme) {
152 var _defaultContextTypes;
153
154 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
155 _ref$noWarn = _ref.noWarn,
156 noWarn = _ref$noWarn === undefined ? false : _ref$noWarn,
157 _ref$createElement = _ref.createElement,
158 createElement = _ref$createElement === undefined ? true : _ref$createElement;
159
160 var ThemedComponent = function (_React$Component) {
161 inherits(ThemedComponent, _React$Component);
162
163 function ThemedComponent() {
164 var _temp, _this, _ret;
165
166 classCallCheck(this, ThemedComponent);
167
168 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
169 args[_key] = arguments[_key];
170 }
171
172 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) {
173 return _this.setState({ theme: theme });
174 }, _temp), possibleConstructorReturn(_this, _ret);
175 }
176
177 // eslint-disable-next-line complexity
178 ThemedComponent.prototype.componentWillMount = function componentWillMount() {
179 if (!this.context[CHANNEL]) {
180 if ('development' !== 'production' && !this.warned) {
181 this.warned = true;
182 // eslint-disable-next-line no-console
183 console.warn(generateWarningMessage(ComponentToTheme));
184 }
185 }
186 var theme = this.props.theme;
187
188 if (this.context[CHANNEL]) {
189 // if a theme is provided via props,
190 // it takes precedence over context
191 this.setTheme(theme ? theme : this.context[CHANNEL].getState());
192 } else {
193 this.setTheme(theme || {});
194 }
195 };
196
197 ThemedComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
198 if (this.props.theme !== nextProps.theme) {
199 this.setTheme(nextProps.theme);
200 }
201 };
202
203 ThemedComponent.prototype.componentDidMount = function componentDidMount() {
204 if (this.context[CHANNEL] && !this.props.theme) {
205 // subscribe to future theme changes
206 this.subscriptionId = this.context[CHANNEL].subscribe(this.setTheme);
207 }
208 };
209
210 ThemedComponent.prototype.componentWillUnmount = function componentWillUnmount() {
211 // cleanup subscription
212 this.subscriptionId && this.context[CHANNEL].unsubscribe(this.subscriptionId);
213 };
214
215 ThemedComponent.prototype.render = function render() {
216 if (createElement) {
217 return React.createElement(ComponentToTheme, _extends({}, this.props, this.state));
218 } else {
219 // this allows us to effectively use the GlamorousComponent
220 // as our `render` method without going through lifecycle hooks.
221 // Also allows us to forward the context in the scenario where
222 // a user wants to add more context.
223 // eslint-disable-next-line babel/new-cap
224 return ComponentToTheme.call(this, _extends({}, this.props, this.state), this.context);
225 }
226 };
227
228 return ThemedComponent;
229 }(React.Component);
230
231 ThemedComponent.propTypes = {
232 theme: _PropTypes.object
233 };
234
235
236 var defaultContextTypes = (_defaultContextTypes = {}, _defaultContextTypes[CHANNEL] = _PropTypes.object, _defaultContextTypes);
237
238 var userDefinedContextTypes = null;
239
240 // configure the contextTypes to be settable by the user,
241 // however also retaining the glamorous channel.
242 Object.defineProperty(ThemedComponent, 'contextTypes', {
243 enumerable: true,
244 configurable: true,
245 set: function set$$1(value) {
246 userDefinedContextTypes = value;
247 },
248 get: function get$$1() {
249 // if the user has provided a contextTypes definition,
250 // merge the default context types with the provided ones.
251 if (userDefinedContextTypes) {
252 return _extends({}, defaultContextTypes, userDefinedContextTypes);
253 }
254 return defaultContextTypes;
255 }
256 });
257
258 return ThemedComponent;
259}
260
261/**
262 * This function takes a className string and gets all the
263 * associated glamor styles. It's used to merge glamor styles
264 * from a className to make sure that specificity is not
265 * a problem when passing a className to a component.
266 * @param {String} [className=''] the className string
267 * @return {Object} { glamorStyles, glamorlessClassName }
268 * - glamorStyles is an array of all the glamor styles objects
269 * - glamorlessClassName is the rest of the className string
270 * without the glamor classNames
271 */
272function extractGlamorStyles(className) {
273 var glamorlessClassName = [];
274 var glamorStyles = [];
275 className.toString().split(' ').forEach(function (name) {
276 if (glamor.styleSheet.registered[name.substring(4)] === undefined) {
277 glamorlessClassName.push(name);
278 } else {
279 var style = buildGlamorSrcFromClassName(name);
280 glamorStyles.push(style);
281 }
282 });
283
284 return { glamorlessClassName: glamorlessClassName, glamorStyles: glamorStyles };
285}
286
287/** Glamor's css function returns an object with the shape
288 *
289 * {
290 * [`data-css-${hash}`]: '',
291 * toString() { return `css-${hash}` }
292 * }
293 *
294 * Whenever glamor's build function encounters an object with
295 * this shape it just pulls the resulting styles from the cache.
296 *
297 * note: the toString method is not needed to qualify the shape
298 **/
299function buildGlamorSrcFromClassName(className) {
300 var _ref;
301
302 return _ref = {}, _ref['data-' + className] = '', _ref;
303}
304
305function getGlamorClassName(_ref2) {
306 var styles = _ref2.styles,
307 props = _ref2.props,
308 cssOverrides = _ref2.cssOverrides,
309 cssProp = _ref2.cssProp,
310 context = _ref2.context,
311 displayName = _ref2.displayName;
312
313 var _handleStyles = handleStyles([].concat(styles, [props.className, cssOverrides, cssProp]), props, context),
314 mappedArgs = _handleStyles.mappedArgs,
315 nonGlamorClassNames = _handleStyles.nonGlamorClassNames;
316 // eslint-disable-next-line max-len
317
318
319 var devRules = { label: displayName };
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 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 };
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
607return glamorous;
608
609})));
610//# sourceMappingURL=glamorous.umd.tiny.js.map