code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
createShapeTypeChecker
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
validate
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
isNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
getPropType
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
getPreciseType
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return '<<anonymous>>'; } return propValue.constructor.name; }
Collection of methods that allow declaration and validation of props that are supplied to React components. Example usage: var Props = require('ReactPropTypes'); var MyArticle = React.createClass({ propTypes: { // An optional string prop named "description". description: Props.string, // A required enum prop named "category". category: Props.oneOf(['News','Photos']).isRequired, // A prop named "dialog" that requires an instance of Dialog. dialog: Props.instanceOf(Dialog).isRequired }, render: function() { ... } }); A more formal specification of how these methods are used: type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) decl := ReactPropTypes.{type}(.isRequired)? Each and every declaration produces a function with the same signature. This allows the creation of custom validation functions. For example: var MyLink = React.createClass({ propTypes: { // An optional string or URI prop named "href". href: function(props, propName, componentName) { var propValue = props[propName]; if (propValue != null && typeof propValue !== 'string' && !(propValue instanceof URI)) { return new Error( 'Expected a string or an URI for ' + propName + ' in ' + componentName ); } } }, render: function() {...} }); @internal
getClassName
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function ReactReconcileTransaction(forceHTML) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; }
Currently: - The order that these are listed in the transaction is critical: - Suppresses events. - Restores selection range. Future: - Restore document/overflow scroll positions that were unintentionally modified via DOM insertions above the top viewport boundary. - Implement/integrate with customized constraint based layout system and keep track of which dimensions must be remeasured. @class ReactReconcileTransaction
ReactReconcileTransaction
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function attachRefs() { ReactRef.attachRefs(this, this._currentElement); }
Helper to call ReactRef.attachRefs with this composite component, split out to avoid allocations in the transaction mount-ready queue.
attachRefs
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function renderToString(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } }
@param {ReactElement} element @return {string} the HTML markup
renderToString
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } }
@param {ReactElement} element @return {string} the HTML markup, without the extra React ID and checksum (for generating static pages)
renderToStaticMarkup
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; }
Array comparator for ReactComponents by mount ordering. @param {ReactComponent} c1 first component you're comparing @param {ReactComponent} c2 second component you're comparing @return {number} Return value usable by Array.prototype.sort().
mountOrderComparator
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } }
Array comparator for ReactComponents by mount ordering. @param {ReactComponent} c1 first component you're comparing @param {ReactComponent} c2 second component you're comparing @return {number} Return value usable by Array.prototype.sort().
runBatchedUpdates
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }
Array comparator for ReactComponents by mount ordering. @param {ReactComponent} c1 first component you're comparing @param {ReactComponent} c2 second component you're comparing @return {number} Return value usable by Array.prototype.sort().
flushBatchedUpdates
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); }
Mark a component as needing a rerender, adding an optional callback to a list of functions which will be executed once the rerender occurs.
enqueueUpdate
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; }
Enqueue a callback to be run at the end of the current batching cycle. Throws if no updates are currently being performed.
asap
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } }
Get an object which is a unique representation of the current selection. The return value will not be consistent across nodes or browsers, but two identical selections on the same node will return identical objects. @param {DOMElement} node @return {object}
getSelection
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; }
Poll selection to see whether it's changed. @param {object} nativeEvent @return {?SyntheticEvent}
constructSelectEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticClipboardEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticCompositionEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticDragEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; }
Synthetic events are dispatched by event plugins, typically in response to a top-level event delegation handler. These systems should generally use pooling to reduce the frequency of garbage collection. The system should check `isPersistent` to determine whether the event should be released into the pool after being dispatched. Users that need a persisted event should invoke `persist`. Synthetic events (and subclasses) implement the DOM Level 3 Events API by normalizing browser quirks. Subclasses do not necessarily have to implement a DOM interface; custom application-specific events can also subclass this. @param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event.
SyntheticEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticFocusEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticInputEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticKeyboardEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticMouseEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticUIEvent}
SyntheticTouchEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticEvent}
SyntheticUIEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); }
@param {object} dispatchConfig Configuration used to dispatch this event. @param {string} dispatchMarker Marker identifying the event target. @param {object} nativeEvent Native browser event. @extends {SyntheticMouseEvent}
SyntheticWheelEvent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function accumulateInto(current, next) { !(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; }
Accumulates items that must not be null or undefined into the first one. This is used to conserve memory by avoiding array allocations, and thus sacrifices API cleanness. Since `current` can be null before being passed in and not null after this function, make sure to assign it back to `current`: `a = accumulateInto(a, b);` This API should be sparingly used. Try `accumulate` for something cleaner. @return {*|array<*>} An accumulation of items.
accumulateInto
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; }
Convert a value into the proper css writable value. The style name `name` should be logical (no hyphens), as specified in `CSSProperty.isUnitlessNumber`. @param {string} name CSS property name such as `topMargin`. @param {*} value CSS property value such as `10px`. @return {string} Normalized style value with dimensions applied.
dangerousStyleValue
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function deprecated(fnName, newModule, newPackage, ctx, fn) { var warned = false; if ("development" !== 'production') { var newFn = function () { "development" !== 'production' ? 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) : undefined; 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; }
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
deprecated
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
newFn = function () { "development" !== 'production' ? 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) : undefined; warned = true; return fn.apply(ctx, arguments); }
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
newFn
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); }
Escapes text to prevent scripting attacks. @param {*} text Text value to escape. @return {string} An escaped string.
escapeTextContentForBrowser
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function findDOMNode(componentOrElement) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; }
Returns the DOM node rendered by this element. @param {ReactComponent|DOMElement} componentOrElement @return {?DOMElement} The root node of this element.
findDOMNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = result[name] === undefined; if ("development" !== 'production') { "development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (keyUnique && child != null) { result[name] = child; } }
@param {function} traverseContext Context passed through traversal. @param {?ReactComponent} child React child component. @param {!string} name String name of key path to child.
flattenSingleChildIntoContext
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; }
Flattens children that are typically specified as `props.children`. Any null children will not be included in the resulting object. @return {!object} flattened children keyed by name.
flattenChildren
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }
@param {array} arr an "accumulation" of items which is either an Array or a single item. Useful when paired with the `accumulate` module. This is a simple utility that allows us to reason about a collection of items, but handling the case when there is exactly one item (and we do not need to allocate an array).
forEachAccumulated
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; }
`charCode` represents the actual "character code" and is safe to use with `String.fromCharCode`. As such, only keys that correspond to printable characters produce a valid `charCode`, the only exception to this is Enter. The Tab-key is considered non-printable and does not have a `charCode`, presumably because it does not produce a tab-character in browsers. @param {object} nativeEvent Native browser event. @return {number} Normalized `charCode` property.
getEventCharCode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; }
@param {object} nativeEvent Native browser event. @return {string} Normalized `key` property.
getEventKey
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; }
Translation from modifier key to the associated property in the event. @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
modifierStateGetter
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getEventModifierState(nativeEvent) { return modifierStateGetter; }
Translation from modifier key to the associated property in the event. @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
getEventModifierState
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; }
Gets the target node from a native browser event by accounting for inconsistencies in browser DOM APIs. @param {object} nativeEvent Native browser event. @return {DOMEventTarget} Target node.
getEventTarget
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } }
Returns the iterator method function contained on the iterable object. Be sure to invoke the function with the iterable as context: var iteratorFn = getIteratorFn(myIterable); if (iteratorFn) { var iterator = iteratorFn.call(myIterable); ... } @param {?object} maybeIterable @return {?function}
getIteratorFn
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; }
Given any node return the first leaf node without children. @param {DOMElement|DOMTextNode} node @return {DOMElement|DOMTextNode}
getLeafNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } }
Get the next sibling within a container. This will walk up the DOM if a node's siblings have been exhausted. @param {DOMElement|DOMTextNode} node @return {?DOMElement|DOMTextNode}
getSiblingNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } }
Get object describing the nodes which contain characters at offset. @param {DOMElement|DOMTextNode} root @param {number} offset @return {?object}
getNodeForCharacterOffset
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; }
Gets the key used to access text content on a DOM node. @return {?string} Key used to access text content. @internal
getTextContentAccessor
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; }
Check if the type reference is a known internal type. I.e. not a user provided composite type. @param {function} type @return {boolean} Returns true if this is a valid internal type.
isInternalComponentType
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function instantiateReactComponent(node) { var instance; if (node === null || node === false) { instance = new ReactEmptyComponent(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; } if ("development" !== 'production') { "development" !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("development" !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("development" !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; }
Given a ReactNode, create an instance that will actually be mounted. @param {ReactNode} node @return {object} A new instance of the element's constructor. @protected
instantiateReactComponent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); }
@see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
isTextInputElement
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function onlyChild(children) { !ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; return children; }
Returns the first child in a collection of children and verifies that there is only one child in the collection. The current implementation of this function assumes that a single child gets passed without a wrapper, but the purpose of this helper function is to abstract away the particular structure of children. @param {?object} children Child collection structure. @return {ReactComponent} The first and only `ReactComponent` contained in the structure.
onlyChild
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; }
Escapes attribute value to prevent scripting attacks. @param {*} value Value to escape. @return {string} An escaped string.
quoteAttributeValueForBrowser
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
setInnerHTML = function (node, html) { node.innerHTML = html; }
Set the innerHTML property of a node, ensuring that whitespace is preserved even in IE8. @param {DOMElement} node @param {string} html @internal
setInnerHTML
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
setTextContent = function (node, text) { node.textContent = text; }
Set the textContent property of a node, ensuring that whitespace is preserved even in IE8. innerText is a poor substitute for textContent and, among many issues, inserts <br> instead of the literal newline chars. innerHTML behaves as it should. @param {DOMElement} node @param {string} text @internal
setTextContent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } return false; }
Given a `prevElement` and `nextElement`, determines if the existing instance should be updated as opposed to being destroyed or replaced by a new instance. Both arguments are elements. This ensures that this logic can operate on stateless trees without any backing instance. @param {?object} prevElement @param {?object} nextElement @return {boolean} True if the existing instance should be updated. @protected
shouldUpdateReactComponent
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; }
TODO: Test that a single child and an array with one item have the same key pattern.
userProvidedKeyEscaper
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); }
Generate a key string that identifies a component within a set. @param {*} component A component that could contain a manual key. @param {number} index Index that is used if a manual key is not provided. @return {string}
getComponentKey
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); }
Escape a component key so that it is safe to use in a reactid. @param {*} text Component key to be escaped. @return {string} An escaped string.
escapeUserProvidedKey
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); }
Wrap a `key` value explicitly provided by the user to distinguish it from implicitly-generated keys generated by a component's index in its parent. @param {string} key Value of a user-provided `key` attribute @return {string}
wrapUserProvidedKey
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("development" !== 'production') { "development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("development" !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; } } return subtreeCount; }
@param {?*} children Children tree container. @param {!string} nameSoFar Name of the key path so far. @param {!function} callback Callback to invoke with each child found. @param {?*} traverseContext Used to pass information throughout the traversal process. @return {!number} The number of children in this subtree.
traverseAllChildrenImpl
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); }
Traverses children that are typically specified as `props.children`, but might also be specified through attributes: - `traverseAllChildren(this.props.children, ...)` - `traverseAllChildren(this.props.leftPanelChildren, ...)` The `traverseContext` is an optional argument that is passed through the entire traversal. It can be used to store accumulations or anything else that the callback might find relevant. @param {?*} children Children tree object. @param {!function} callback To invoke upon traversing each child. @param {?*} traverseContext Context for traversal. @return {!number} The number of children in this subtree.
traverseAllChildren
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; /*eslint-disable space-after-keywords */ do { /*eslint-enable space-after-keywords */ stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }
Given a ReactCompositeComponent instance, return a list of its recursive owners, starting at the root and ending with the instance itself.
findOwnerStack
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); }
Camelcases a hyphenated string, for example: > camelize('background-color') < "backgroundColor" @param {string} string @return {string}
camelize
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function containsNode(_x, _x2) { var _again = true; _function: while (_again) { var outerNode = _x, innerNode = _x2; _again = false; if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { _x = outerNode; _x2 = innerNode.parentNode; _again = true; continue _function; } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } }
Checks if a given DOM node contains or is another DOM node. @param {?DOMNode} outerNode Outer DOM node. @param {?DOMNode} innerNode Inner DOM node. @return {boolean} True if `outerNode` contains or is `innerNode`.
containsNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function hasArrayNature(obj) { return( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); }
Perform a heuristic test to determine if an object is "array-like". A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" Joshu replied: "Mu." This function determines if its argument has "array nature": it returns true if the argument is an actual array, an `arguments' object, or an HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). It will return false for other array-like objects like Filelist. @param {*} obj @return {boolean}
hasArrayNature
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } }
Ensure that the argument is an array by wrapping it in an array if it is not. Creates a copy of the argument if it is already an array. This is mostly useful idiomatically: var createArrayFromMixed = require('createArrayFromMixed'); function takesOneOrMoreThings(things) { things = createArrayFromMixed(things); ... } This allows you to treat `things' as an array, but accept scalars in the API. If you need to convert an array-like object, like `arguments`, into an array use toArray instead. @param {*} obj @return {array}
createArrayFromMixed
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); }
Extracts the `nodeName` of the first element in a string of markup. @param {string} markup String of markup. @return {?string} Node name of the supplied markup.
getNodeName
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; }
Creates an array containing the nodes rendered from the supplied markup. The optionally supplied `handleScript` function will be invoked once for each <script> element that is rendered. If no `handleScript` function is supplied, an exception is thrown if any <script> elements are rendered. @param {string} markup A string of valid HTML markup. @param {?function} handleScript Invoked once for each rendered <script>. @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
createNodesFromMarkup
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} }
@param {DOMElement} node input/textarea to focus
focusNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } }
Same as document.activeElement but wraps in a try-catch block. In IE it is not safe to call document.activeElement if there is nothing focused. The activeElement will be null only if the document or document body is not yet defined.
getActiveElement
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getMarkupWrap(nodeName) { !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; }
Gets the markup wrap configuration for the supplied `nodeName`. NOTE: This lazily detects which wraps are necessary for the current browser. @param {string} nodeName Lowercase `nodeName`. @return {?array} Markup wrap configuration, if applicable.
getMarkupWrap
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; }
Gets the scroll position of the supplied element or window. The return values are unbounded, unlike `getScrollPosition`. This means they may be negative or exceed the element boundaries (which is possible using inertial scrolling). @param {DOMWindow|DOMElement} scrollable @return {object} Map with `x` and `y` keys.
getUnboundedScrollPosition
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); }
Hyphenates a camelcased string, for example: > hyphenate('backgroundColor') < "background-color" For CSS style names, use `hyphenateStyleName` instead which works properly with all vendor prefixes, including `ms`. @param {string} string @return {string}
hyphenate
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); }
Hyphenates a camelcased CSS property name, for example: > hyphenateStyleName('backgroundColor') < "background-color" > hyphenateStyleName('MozTransition') < "-moz-transition" > hyphenateStyleName('msTransition') < "-ms-transition" As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix is converted to `-ms-`. @param {string} string @return {string}
hyphenateStyleName
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function invariant(condition, format, a, b, c, d, e, f) { if ("development" !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }
Use invariant() to assert state which your program assumes to be true. Provide sprintf-style format (only %s is supported) and arguments to provide information about what broke and what you were expecting. The invariant message will be stripped in production, but the invariant will remain to ensure logic does not differ in production.
invariant
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); }
@param {*} object The object to check. @return {boolean} Whether or not the object is a DOM node.
isNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function isTextNode(object) { return isNode(object) && object.nodeType == 3; }
@param {*} object The object to check. @return {boolean} Whether or not the object is a DOM text node.
isTextNode
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
keyMirror = function (obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }
Constructs an enumeration with keys equal to their value. For example: var COLORS = keyMirror({blue: null, red: null}); var myColor = COLORS.blue; var isColorValid = !!COLORS[myColor]; The last line could not be performed if the values of the generated enum were not equal to their keys. Input: {key1: val1, key2: val2} Output: {key1: key1, key2: key2} @param {object} obj @return {object}
keyMirror
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }
Allows extraction of a minified key. Let's the build system minify keys without losing the ability to dynamically use key strings as values themselves. Pass in an object with a single key/val pair and it will return you the string key of that single record. Suppose you want to grab the value for a key 'className' inside of an object. Key/val minification may have aliased that key to be 'xa12'. keyOf({className: null}) will return 'xa12' in that case. Resolve keys you want to use once at startup time, then reuse those resolutions.
keyOf
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; }
Executes the provided `callback` once for each enumerable own property in the object and constructs a new object from the results. The `callback` is invoked with three arguments: - the property value - the property name - the object being traversed Properties that are added after the call to `mapObject` will not be visited by `callback`. If the values of existing properties are changed, the value passed to `callback` will be the value at the time `mapObject` visits them. Properties that are deleted before being visited are not visited. @grep function objectMap() @grep function objMap() @param {?object} object @param {function} callback @param {*} context @return {?object}
mapObject
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; }
Memoizes the return value of a function that accepts one string argument. @param {function} callback @return {function}
memoizeStringOnly
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; }
Performs equality by iterating through keys on an object and returning false when any key has values which are not strictly equal between the arguments. Returns true when the values of all keys are strictly equal.
shallowEqual
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; }
Convert array-like objects to arrays. This API assumes the caller knows the contents of the data type. For less well defined inputs use createArrayFromMixed. @param {object|function|filelist} obj @return {array}
toArray
javascript
amol-/dukpy
dukpy/jsmodules/react/react.js
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
MIT
function GithubView(name, options){ this.name = name; options = options || {}; this.engine = options.engines[extname(name)]; // "root" is the app.set('views') setting, however // in your own implementation you could ignore this this.path = '/' + options.root + '/master/' + name; }
Custom view that fetches and renders remove github templates. You could render templates from a database etc.
GithubView
javascript
expressjs/express
examples/view-constructor/github-view.js
https://github.com/expressjs/express/blob/master/examples/view-constructor/github-view.js
MIT
function logerror(err) { /* istanbul ignore next */ if (this.get('env') !== 'test') console.error(err.stack || err.toString()); }
Log error using console.error. @param {Error} err @private
logerror
javascript
expressjs/express
lib/application.js
https://github.com/expressjs/express/blob/master/lib/application.js
MIT
function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; mixin(app, EventEmitter.prototype, false); mixin(app, proto, false); // expose the prototype that will get set on requests app.request = Object.create(req, { app: { configurable: true, enumerable: true, writable: true, value: app } }) // expose the prototype that will get set on responses app.response = Object.create(res, { app: { configurable: true, enumerable: true, writable: true, value: app } }) app.init(); return app; }
Create an express application. @return {Function} @api public
createApplication
javascript
expressjs/express
lib/express.js
https://github.com/expressjs/express/blob/master/lib/express.js
MIT
app = function(req, res, next) { app.handle(req, res, next); }
Create an express application. @return {Function} @api public
app
javascript
expressjs/express
lib/express.js
https://github.com/expressjs/express/blob/master/lib/express.js
MIT
function defineGetter(obj, name, getter) { Object.defineProperty(obj, name, { configurable: true, enumerable: true, get: getter }); }
Helper function for creating a getter on an object. @param {Object} obj @param {String} name @param {Function} getter @private
defineGetter
javascript
expressjs/express
lib/request.js
https://github.com/expressjs/express/blob/master/lib/request.js
MIT
function sendfile(res, file, options, callback) { var done = false; var streaming; // request aborted function onaborted() { if (done) return; done = true; var err = new Error('Request aborted'); err.code = 'ECONNABORTED'; callback(err); } // directory function ondirectory() { if (done) return; done = true; var err = new Error('EISDIR, read'); err.code = 'EISDIR'; callback(err); } // errors function onerror(err) { if (done) return; done = true; callback(err); } // ended function onend() { if (done) return; done = true; callback(); } // file function onfile() { streaming = false; } // finished function onfinish(err) { if (err && err.code === 'ECONNRESET') return onaborted(); if (err) return onerror(err); if (done) return; setImmediate(function () { if (streaming !== false && !done) { onaborted(); return; } if (done) return; done = true; callback(); }); } // streaming function onstream() { streaming = true; } file.on('directory', ondirectory); file.on('end', onend); file.on('error', onerror); file.on('file', onfile); file.on('stream', onstream); onFinished(res, onfinish); if (options.headers) { // set headers on successful transfer file.on('headers', function headers(res) { var obj = options.headers; var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var k = keys[i]; res.setHeader(k, obj[k]); } }); } // pipe file.pipe(res); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
sendfile
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onaborted() { if (done) return; done = true; var err = new Error('Request aborted'); err.code = 'ECONNABORTED'; callback(err); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onaborted
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function ondirectory() { if (done) return; done = true; var err = new Error('EISDIR, read'); err.code = 'EISDIR'; callback(err); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
ondirectory
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onerror(err) { if (done) return; done = true; callback(err); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onerror
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onend() { if (done) return; done = true; callback(); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onend
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onfile() { streaming = false; }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onfile
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onfinish(err) { if (err && err.code === 'ECONNRESET') return onaborted(); if (err) return onerror(err); if (done) return; setImmediate(function () { if (streaming !== false && !done) { onaborted(); return; } if (done) return; done = true; callback(); }); }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onfinish
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function onstream() { streaming = true; }
Render `view` with the given `options` and optional callback `fn`. When a callback function is given a response will _not_ be made automatically, otherwise a response of _200_ and _text/html_ is given. Options: - `cache` boolean hinting to the engine it should cache - `filename` filename of the view being rendered @public
onstream
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function stringify (value, replacer, spaces, escape) { // v8 checks arguments.length for optimizing simple call // https://bugs.chromium.org/p/v8/issues/detail?id=4730 var json = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value); if (escape && typeof json === 'string') { json = json.replace(/[<>&]/g, function (c) { switch (c.charCodeAt(0)) { case 0x3c: return '\\u003c' case 0x3e: return '\\u003e' case 0x26: return '\\u0026' /* istanbul ignore next: unreachable default */ default: return c } }) } return json }
Stringify JSON, like JSON.stringify, but v8 optimized, with the ability to escape characters that can trigger HTML sniffing. @param {*} value @param {function} replacer @param {number} spaces @param {boolean} escape @returns {string} @private
stringify
javascript
expressjs/express
lib/response.js
https://github.com/expressjs/express/blob/master/lib/response.js
MIT
function acceptParams (str) { var length = str.length; var colonIndex = str.indexOf(';'); var index = colonIndex === -1 ? length : colonIndex; var ret = { value: str.slice(0, index).trim(), quality: 1, params: {} }; while (index < length) { var splitIndex = str.indexOf('=', index); if (splitIndex === -1) break; var colonIndex = str.indexOf(';', index); var endIndex = colonIndex === -1 ? length : colonIndex; if (splitIndex > endIndex) { index = str.lastIndexOf(';', splitIndex - 1) + 1; continue; } var key = str.slice(index, splitIndex).trim(); var value = str.slice(splitIndex + 1, endIndex).trim(); if (key === 'q') { ret.quality = parseFloat(value); } else { ret.params[key] = value; } index = endIndex + 1; } return ret; }
Parse accept params `str` returning an object with `.value`, `.quality` and `.params`. @param {String} str @return {Object} @api private
acceptParams
javascript
expressjs/express
lib/utils.js
https://github.com/expressjs/express/blob/master/lib/utils.js
MIT
function createETagGenerator (options) { return function generateETag (body, encoding) { var buf = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body return etag(buf, options) } }
Create an ETag generator function, generating ETags with the given options. @param {object} options @return {function} @private
createETagGenerator
javascript
expressjs/express
lib/utils.js
https://github.com/expressjs/express/blob/master/lib/utils.js
MIT
function parseExtendedQueryString(str) { return qs.parse(str, { allowPrototypes: true }); }
Parse an extended query string with qs. @param {String} str @return {Object} @private
parseExtendedQueryString
javascript
expressjs/express
lib/utils.js
https://github.com/expressjs/express/blob/master/lib/utils.js
MIT