beforeEach(function() { require('mock-modules').dumpCache(); React = require('React'); var ReactMultiChild = require('ReactMultiChild'); var ReactDOMComponent = require('ReactDOMComponent'); var ReactReconcileTransaction = require('ReactReconcileTransaction'); var StubNativeComponent = function(element) { this._currentElement = element; }; assign(StubNativeComponent.prototype, ReactDOMComponent.Mixin); assign(StubNativeComponent.prototype, ReactMultiChild.Mixin); mountComponent = function(props) { var transaction = new ReactReconcileTransaction(); var stubComponent = new StubNativeComponent({ type: StubNativeComponent, props: props, _owner: null, _context: null }); return stubComponent.mountComponent('test', transaction, {}); }; });
_processPendingState: function(props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign( nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial ); } return nextState; },
ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement( element.type, key, ref, self, source, owner, props ); };
function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var writes = measurement.writes; var dirtyComposites = {}; Object.keys(writes).forEach(function(id) { writes[id].forEach(function(write) { // Root mounting (innerHTML set) is recorded with an ID of '' if (id !== '') { measurement.hierarchy[id].forEach((c) => dirtyComposites[c] = true); } }); }); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // See if any of the DOM operations applied to this component's subtree. if (dirtyComposites[id]) { isDirty = true; } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; }
/** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} fnName The name of the function * @param {string} newModule The module that fn will exist in * @param {string} newPackage The module that fn will exist in * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {function} The function that will warn once and then call fn */ function deprecated(fnName, newModule, newPackage, ctx, fn) { var warned = false; if (__DEV__) { var newFn = function() { warning( warned, // Require examples in this string must be split to prevent React's // build tools from mistaking them for real requires. // Otherwise the build tools will attempt to build a '%s' module. 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage ); warned = true; return fn.apply(ctx, arguments); }; // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; }
render: function() { return ( ReactTransitionGroup( assign({}, this.props, {childFactory: this._wrapChild}) ) ); },
_processChildContext: function(currentContext) { var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); var displayName = inst.constructor.displayName || 'ReactCompositeComponent'; if (childContext) { invariant( typeof inst.constructor.childContextTypes === 'object', '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', displayName ); if (__DEV__) { this._checkPropTypes( inst.constructor.childContextTypes, childContext, ReactPropTypeLocations.childContext ); } for (var name in childContext) { invariant( name in inst.constructor.childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', displayName, name ); } return assign({}, currentContext, childContext); } return currentContext; },
setState: function(partialState, callback) { // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( assign({}, this._pendingState || this._instance.state, partialState), callback ); },
SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); };
beforeEach(function() { var ReactDefaultInjection = require('ReactDefaultInjection'); ReactDefaultInjection.inject(); var ReactDOMComponent = require('ReactDOMComponent'); var ReactReconcileTransaction = require('ReactReconcileTransaction'); var NodeStub = function(initialProps) { this._currentElement = {props: initialProps}; this._rootNodeID = 'test'; }; assign(NodeStub.prototype, ReactDOMComponent.Mixin); genMarkup = function(props) { var transaction = new ReactReconcileTransaction(); return (new NodeStub(props))._createOpenTagMarkupAndPutListeners( transaction, props ); }; this.addMatchers({ toHaveAttribute: function(attr, value) { var expected = '(?:^|\\s)' + attr + '=[\\\'"]'; if (typeof value !== 'undefined') { expected += quoteRegexp(value) + '[\\\'"]'; } return this.actual.match(new RegExp(expected)); }, }); });
function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; }
return function(domComponentOrNode, eventData) { var node; if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { node = domComponentOrNode.getDOMNode(); } else if (domComponentOrNode.tagName) { node = domComponentOrNode; } var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent( ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType], ReactMount.getID(node), fakeNativeEvent ); assign(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(); }); };
/** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode( componentInstance, rootID, container, transaction, shouldReuseMarkup, context ) { if (ReactDOMFeatureFlags.useCreateElement) { context = assign({}, context); if (container.nodeType === DOC_NODE_TYPE) { context[ownerDocumentContextKey] = container; } else { context[ownerDocumentContextKey] = container.ownerDocument; } } if (__DEV__) { if (context === emptyObject) { context = {}; } var tag = container.nodeName.toLowerCase(); context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); } var markup = ReactReconciler.mountComponent( componentInstance, rootID, transaction, context ); componentInstance._renderedComponent._topLevelWrapper = componentInstance; ReactMount._mountImageIntoNode( markup, container, shouldReuseMarkup, transaction ); }
render: function() { var props = this.props; // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (this.state.selected != null) { props = assign({}, props, {selected: this.state.selected}); } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(this.props.children, function(child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { warning( false, 'Only strings and numbers are supported as <option> children.' ); } }); return option(props, content); }
beforeEach(function() { var ReactDOMComponent = require('ReactDOMComponent'); var ReactReconcileTransaction = require('ReactReconcileTransaction'); var NodeStub = function(initialProps) { this._currentElement = {props: initialProps}; this._rootNodeID = 'test'; }; assign(NodeStub.prototype, ReactDOMComponent.Mixin); genMarkup = function(props) { var transaction = new ReactReconcileTransaction(); return (new NodeStub(props))._createContentMarkup( transaction, props, {} ); }; this.addMatchers({ toHaveInnerhtml: function(html) { var expected = '^' + quoteRegexp(html) + '$'; return this.actual.match(new RegExp(expected)); }, }); });
function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign( {}, measurement.exclusive, measurement.inclusive ); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0, }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function(a, b) { return b.time - a.time; }); return arr; }
setProps: function(partialProps, callback) { // Merge with the pending element if it exists, otherwise with existing // element props. var element = this._pendingElement || this._currentElement; this.replaceProps( assign({}, element.props, partialProps), callback ); },
_createOpenTagMarkupAndPutListeners: function(transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (__DEV__) { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else if (this._namespaceURI === DOMNamespaces.svg) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForSVGAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._nativeParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; },
_setPropsInternal: function(partialProps, callback) { // This is a deoptimized path. We optimize for always having an element. // This creates an extra internal element. var element = this._pendingElement || this._currentElement; this._pendingElement = ReactElement.cloneAndReplaceProps( element, assign({}, element.props, partialProps) ); ReactUpdates.enqueueUpdate(this, callback); },
function processChildContext(context, inst) { if (__DEV__) { // Pass down our tag name to child components for validation purposes context = assign({}, context); var info = context[validateDOMNesting.ancestorInfoContextKey]; context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); } return context; }
function cleanData(data, opts) { var options = assign( {}, { allowedTags: [], allowedAttributes: [] }, opts || {} ); return sanitizeHtml(data, options).replace(/";/g, '"'); }
propTypes: function(Constructor, propTypes) { validateTypeDef( Constructor, propTypes, ReactPropTypeLocations.prop ); Constructor.propTypes = assign( {}, Constructor.propTypes, propTypes ); },
/** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of properties that should be set on the element * @param {Object=} attributes An object of attributes that should be set on the element * @return {Element} * @method createEl */ createEl(tag='button', props={}, attributes={}) { props = assign({ className: this.buildCSSClass() }, props); if (tag !== 'button') { log.warn(`Creating a Button with an HTML element of ${tag} is deprecated; use ClickableComponent instead.`); } // Add attributes for button element attributes = assign({ type: 'button', // Necessary since the default button type is "submit" 'aria-live': 'polite' // let the screen reader user know that the text of the button may change }, attributes); let el = Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }
contextTypes: function(Constructor, contextTypes) { validateTypeDef( Constructor, contextTypes, ReactPropTypeLocations.context ); Constructor.contextTypes = assign( {}, Constructor.contextTypes, contextTypes ); },
/** * Create the component's DOM element * * @return {Element} */ createEl() { let el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this.movingMediaElementInDOM === false) { // If the original tag is still there, clone and remove it. if (el) { const clone = el.cloneNode(true); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = document.createElement('video'); // determine if native controls should be used const tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); const attributes = mergeOptions({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, assign(attributes, { id: this.options_.techId, class: 'vjs-tech' }) ); } el.playerId = this.options_.playerId; } // Update specific tag settings, in case they were overridden const settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (let i = settingsAttrs.length - 1; i >= 0; i--) { const attr = settingsAttrs[i]; const overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }
exports.number = function (opt) { var opts = assign({}, opt); var f = exports.string(opts); f.parse = function (raw_data) { if (raw_data === null || raw_data === '') { return NaN; } return Number(raw_data); }; return f; };
/** * Create the component's DOM element * * @return {Element} * @method createEl */ createEl() { let options = this.options_; // Generate ID for swf object let objId = options.techId; // Merge default flashvars with ones passed in to init let flashVars = assign({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': options.autoplay, 'preload': options.preload, 'loop': options.loop, 'muted': options.muted }, options.flashVars); // Merge default parames with ones passed in let params = assign({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in let attributes = assign({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }
constructor(player, options, ready) { // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = assign({}, this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options or options element if one is supplied this.id_ = options.id || (options.el && options.el.id); // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players let id = player && player.id && player.id() || 'no_player'; this.id_ = `${id}_component_${Guid.newGUID()}`; } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } }
withContext: function(newContext, scopedCallback) { monitorCodeUse('react_with_context', {newContext: newContext}); var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; }
/** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ createEl(type, props={}) { // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = assign({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return super.createEl(type, props); }