code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
query(selector) {
return this.collection.query(selector)
} | Lookup one or multiple triggers by a query string
@param {string} selector
@returns {Trigger[]} | query ( selector ) | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
search(element) {
return this.collection.search(element)
} | Lookup one or multiple triggers by a certain HTMLElement or NodeList
@param {HTMLElement|HTMLElement[]|NodeList} element
@returns {Trigger|Trigger[]|null} | search ( element ) | javascript | terwanerik/ScrollTrigger | src/ScrollTrigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js | MIT |
checkVisibility(parent, direction) {
if (!this.active) {
return this.visible
}
const parentWidth = parent.offsetWidth || parent.innerWidth || 0
const parentHeight = parent.offsetHeight || parent.innerHeight || 0
const parentFrame = { w: parentWidth, h: parentHeight }
const rect = this.getBounds()
const visible = this._checkVisibility(rect, parentFrame, direction)
if (visible !== this.visible) {
this.visible = visible
const response = this._toggleCallback()
if (response instanceof Promise) {
response.then(this._toggleClass.bind(this)).catch(e => {
console.error('Trigger promise failed')
console.error(e)
})
} else {
this._toggleClass()
}
if (this.visible && this.once) {
this.active = false
}
} else if (visible) {
if (typeof this.toggle.callback.visible == 'function') {
return this.toggle.callback.visible.call(this.element, this)
}
}
return visible
} | Checks if the Trigger is in the viewport, calls the callbacks and toggles the classes
@param {HTMLElement|HTMLDocument|Window} parent
@param {string} direction top, bottom, left, right
@returns {boolean} If the element is visible | checkVisibility ( parent , direction ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
getBounds() {
return this.element.getBoundingClientRect()
} | Get the bounds of this element
@return {ClientRect | DOMRect} | getBounds ( ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_getElementOffset(rect, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.element.x === 'function') {
offset.x = rect.width * this.offset.element.x(this, rect, direction)
} else if (isFloat(this.offset.element.x)) {
offset.x = rect.width * this.offset.element.x
} else if (isInt(this.offset.element.x)) {
offset.x = this.offset.element.x
}
if (typeof this.offset.element.y === 'function') {
offset.y = rect.height * this.offset.element.y(this, rect, direction)
} else if (isFloat(this.offset.element.y)) {
offset.y = rect.height * this.offset.element.y
} else if (isInt(this.offset.element.y)) {
offset.y = this.offset.element.y
}
return offset
} | Get the calculated offset to place on the element
@param {ClientRect} rect
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private | _getElementOffset ( rect , direction ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_getViewportOffset(parent, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.viewport.x === 'function') {
offset.x = parent.w * this.offset.viewport.x(this, parent, direction)
} else if (isFloat(this.offset.viewport.x)) {
offset.x = parent.w * this.offset.viewport.x
} else if (isInt(this.offset.viewport.x)) {
offset.x = this.offset.viewport.x
}
if (typeof this.offset.viewport.y === 'function') {
offset.y = parent.h * this.offset.viewport.y(this, parent, direction)
} else if (isFloat(this.offset.viewport.y)) {
offset.y = parent.h * this.offset.viewport.y
} else if (isInt(this.offset.viewport.y)) {
offset.y = this.offset.viewport.y
}
return offset
} | Get the calculated offset to place on the viewport
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private | _getViewportOffset ( parent , direction ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_checkVisibility(rect, parent, direction) {
const elementOffset = this._getElementOffset(rect, direction)
const viewportOffset = this._getViewportOffset(parent, direction)
let visible = true
if ((rect.left - viewportOffset.x) < -(rect.width - elementOffset.x)) {
visible = false
}
if ((rect.left + viewportOffset.x) > (parent.w - elementOffset.x)) {
visible = false
}
if ((rect.top - viewportOffset.y) < -(rect.height - elementOffset.y)) {
visible = false
}
if ((rect.top + viewportOffset.y) > (parent.h - elementOffset.y)) {
visible = false
}
return visible
} | Check the visibility of the trigger in the viewport, with offsets applied
@param {ClientRect} rect
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {boolean}
@private | _checkVisibility ( rect , parent , direction ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_toggleCallback() {
if (this.visible) {
if (typeof this.toggle.callback.in == 'function') {
return this.toggle.callback.in.call(this.element, this)
}
} else {
if (typeof this.toggle.callback.out == 'function') {
return this.toggle.callback.out.call(this.element, this)
}
}
} | Toggles the callback
@private
@return null|Promise | _toggleCallback ( ) | javascript | terwanerik/ScrollTrigger | src/scripts/Trigger.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js | MIT |
_tick() {
this.callback(this.position, this.direction)
const now = this._getTimestamp()
if (now - this.lastAction > this.sustain) {
this._stopRun()
}
if (this.running) {
this._loop()
}
} | One single tick of the animation
@private | _tick ( ) | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
_loop() {
const frame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
((callback) => { setTimeout(callback, 1000 / 60) })
frame(this._tick.bind(this))
} | Requests an animation frame
@private | _loop ( ) | javascript | terwanerik/ScrollTrigger | src/scripts/ScrollAnimationLoop.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js | MIT |
remove(objects) {
if (objects instanceof Trigger) {
objects = [objects]
}
this.triggers = this.triggers.filter((trigger) => {
let hit = false
objects.each((object) => {
if (object == trigger) {
hit = true
}
})
return !hit
})
} | Removes one or multiple Trigger objects
@param {Trigger|Trigger[]} objects | remove ( objects ) | javascript | terwanerik/ScrollTrigger | src/scripts/TriggerCollection.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js | MIT |
call(callback) {
this.triggers.each(callback)
} | Calls a function on all triggers
@param {(function())} callback | call ( callback ) | javascript | terwanerik/ScrollTrigger | src/scripts/TriggerCollection.js | https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js | MIT |
const checkParams = config => {
const DEFAULT_GUTTER = 25;
const booleanProps = ["useTransform", "center"];
if (!config) {
throw new Error("No config object has been provided.");
}
for(let prop of booleanProps){
if(typeof config[prop] !== "boolean"){
config[prop] = true;
}
}
if(typeof config.gutter !== "number"){
config.gutter = DEFAULT_GUTTER;
}
if (!config.container) error("container");
if (!config.items && !config.static) error("items or static");
}; | Validates the configuration object.
@param config - configuration object | checkParams | javascript | e-oj/Magic-Grid | src/utils.js | https://github.com/e-oj/Magic-Grid/blob/master/src/utils.js | MIT |
const error = prop => {
throw new Error(`Missing property '${prop}' in MagicGrid config`);
}; | Handles invalid configuration object
errors.
@param prop - a property with a missing value | error | javascript | e-oj/Magic-Grid | src/utils.js | https://github.com/e-oj/Magic-Grid/blob/master/src/utils.js | MIT |
const getMin = cols => {
let min = cols[0];
for (let col of cols) {
if (col.height < min.height) min = col;
}
return min;
}; | Finds the shortest column in
a column list.
@param cols - list of columns
@return shortest column | getMin | javascript | e-oj/Magic-Grid | src/utils.js | https://github.com/e-oj/Magic-Grid/blob/master/src/utils.js | MIT |
constructor (config) {
super();
checkParams(config);
if (config.container instanceof HTMLElement) {
this.container = config.container;
this.containerClass = config.container.className;
}
else {
this.containerClass = config.container;
this.container = document.querySelector(config.container);
}
this.static = config.static || false;
this.size = config.items;
this.gutter = config.gutter;
this.maxColumns = config.maxColumns || false;
this.useMin = config.useMin || false;
this.useTransform = config.useTransform;
this.animate = config.animate || false;
this.center = config.center;
this.styledItems = new Set();
this.resizeObserver = null;
this.isPositioning = false;
} | Initializes the necessary variables
for a magic grid.
@param config - configuration object | constructor ( config ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
setContainer(container){
const previousContainer = this.container;
this.container = container;
this.resizeObserver.unobserve(previousContainer);
this.resizeObserver.observe(container);
} | Set a new container. Useful in cases where
the container reference changes for any reason.
@param container {HTMLElement} | setContainer ( container ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
items () {
return this.container.children;
} | Gets a collection of all items in a grid.
@return {HTMLCollection}
@private | items ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
colWidth () {
return this.items()[0].getBoundingClientRect().width + this.gutter;
} | Calculates the width of a column.
@return width of a column in the grid
@private | colWidth ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
setup () {
let width = this.container.getBoundingClientRect().width;
let colWidth = this.colWidth();
let numCols = Math.floor(width/colWidth) || 1;
let cols = [];
if (this.maxColumns && numCols > this.maxColumns) {
numCols = this.maxColumns;
}
for (let i = 0; i < numCols; i++) {
cols[i] = {height: 0, index: i};
}
let wSpace = width - numCols * colWidth + this.gutter;
return {cols, wSpace};
} | Initializes an array of empty columns
and calculates the leftover whitespace.
@return {{cols: Array, wSpace: number}}
@private | setup ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
nextCol (cols, i) {
if (this.useMin) {
return getMin(cols);
}
return cols[i % cols.length];
} | Gets the next available column.
@param cols list of columns
@param i index of dom element
@return {*} next available column
@private | nextCol ( cols , i ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
positionItems () {
if(this.isPositioning){
return;
}
this.isPositioning = true;
let { cols, wSpace } = this.setup();
let maxHeight = 0;
let colWidth = this.colWidth();
let items = this.items();
wSpace = this.center ? Math.floor(wSpace / 2) : 0;
this.initStyles();
for (let i = 0; i < items.length; i++) {
let col = this.nextCol(cols, i);
let item = items[i];
let topGutter = col.height ? this.gutter : 0;
let left = col.index * colWidth + wSpace + "px";
let top = col.height + topGutter + "px";
if(this.useTransform){
item.style.transform = `translate(${left}, ${top})`;
}
else{
item.style.top = top;
item.style.left = left;
}
col.height += item.getBoundingClientRect().height + topGutter;
if(col.height > maxHeight){
maxHeight = col.height;
}
}
this.container.style.height = maxHeight + this.gutter + "px";
this.isPositioning = false;
this.emit(POSITIONING_COMPLETE_EVENT);
} | Positions each item in the grid, based
on their corresponding column's height
and index then stretches the container to
the height of the grid. | positionItems ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
ready () {
if (this.static) return true;
return this.items().length >= this.size;
} | Checks if every item has been loaded
in the dom.
@return {Boolean} true if every item is present | ready ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
getReady () {
let interval = setInterval(() => {
this.container = document.querySelector(this.containerClass);
if (this.ready()) {
clearInterval(interval);
this.listen();
}
}, 100);
} | Periodically checks that all items
have been loaded in the dom. Calls
this.listen() once all the items are
present.
@private | getReady ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
listen () {
if (this.ready()) {
window.addEventListener("resize", () => {
setTimeout(() => {
this.positionItems();
}, REPOSITIONING_DELAY);
});
this.observeContainerResize();
this.positionItems();
this.emit(READY_EVENT);
}
else this.getReady();
} | Positions all the items and
repositions them whenever the
window size changes. | listen ( ) | javascript | e-oj/Magic-Grid | src/index.js | https://github.com/e-oj/Magic-Grid/blob/master/src/index.js | MIT |
module.exports = function leakFilter(node, _snapshot, _leakedNodeIds) {
return node.retainedSize > 1000000;
}; | Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@format
@oncall memory_lab | leakFilter ( node , _snapshot , _leakedNodeIds ) | javascript | facebook/memlab | packages/cli/src/options/heap/leak-filter/examples/large-object-as-leak.example.js | https://github.com/facebook/memlab/blob/master/packages/cli/src/options/heap/leak-filter/examples/large-object-as-leak.example.js | MIT |
module.exports = function leakFilter(node, _snapshot, _leakedNodeIds) {
return node.retainedSize > 1000 * 1000;
}; | Copyright (c) Meta Platforms, Inc. and affiliates.
@nolint
@oncall memory_lab | leakFilter ( node , _snapshot , _leakedNodeIds ) | javascript | facebook/memlab | packages/e2e/static/example/leak-filters/filter-by-retained-size.js | https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/leak-filters/filter-by-retained-size.js | MIT |
function url() {
return 'http://localhost:3000/examples/detached-dom';
} | The initial `url` of the scenario we would like to run. | url ( ) | javascript | facebook/memlab | packages/e2e/static/example/scenarios/detached-dom.js | https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js | MIT |
async function action(page) {
const elements = await page.$x(
"//button[contains(., 'Create detached DOMs')]",
);
const [button] = elements;
if (button) {
await button.click();
}
// clean up external references from memlab
await Promise.all(elements.map(e => e.dispose()));
} | Specify how memlab should perform action that you want
to test whether the action is causing memory leak.
@param page - Puppeteer's page object:
https://pptr.dev/api/puppeteer.page/ | action ( page ) | javascript | facebook/memlab | packages/e2e/static/example/scenarios/detached-dom.js | https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js | MIT |
async function back(page) {
await page.click('a[href="/"]');
} | Specify how memlab should perform action that would
reset the action you performed above.
@param page - Puppeteer's page object:
https://pptr.dev/api/puppeteer.page/ | back ( page ) | javascript | facebook/memlab | packages/e2e/static/example/scenarios/detached-dom.js | https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js | MIT |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict'; | @license React
react.development.js
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree. | (anonymous) ( global , factory ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
isMounted: function (publicInstance) {
return false;
}, | Checks whether or not this composite component is mounted.
@param {ReactClass} publicInstance The instance we want to test.
@return {boolean} True if mounted, false otherwise.
@protected
@final | isMounted ( publicInstance ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
}, | Forces an update. This should only be invoked when it is known with
certainty that we are **not** in a DOM transaction.
You may want to call this when you know that some deeper aspect of the
component's state has changed but `setState` was not called.
This will not invoke `shouldComponentUpdate`, but it will invoke
`componentWillUpdate` and `componentDidUpdate`.
@param {ReactClass} publicInstance The instance that should rerender.
@param {?function} callback Called after component is updated.
@param {?string} callerName name of the calling function in the public API.
@internal | enqueueForceUpdate ( publicInstance , callback , callerName ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
}, | Replaces all of the state. Always use this or `setState` to mutate state.
You should treat `this.state` as immutable.
There is no guarantee that `this.state` will be immediately updated, so
accessing `this.state` after calling this method may return the old value.
@param {ReactClass} publicInstance The instance that should rerender.
@param {object} completeState Next state.
@param {?function} callback Called after component is updated.
@param {?string} callerName name of the calling function in the public API.
@internal | enqueueReplaceState ( publicInstance , completeState , callback , callerName ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
} | Sets a subset of the state. This only exists because _pendingState is
internal. This provides a merging strategy that is not available to deep
properties which is confusing. TODO: Expose pendingState or don't use it
during the merge.
@param {ReactClass} publicInstance The instance that should rerender.
@param {object} partialState Next partial state to be merged with state.
@param {?function} callback Called after component is updated.
@param {?string} Name of the calling function in the public API.
@internal | enqueueSetState ( publicInstance , partialState , callback , callerName ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
} | Base class helpers for the updating state of a component. | Component ( props , context , updater ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
Component.prototype.setState = function (partialState, callback) {
if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
}; | Sets a subset of the state. Always use this to mutate
state. You should treat `this.state` as immutable.
There is no guarantee that `this.state` will be immediately updated, so
accessing `this.state` after calling this method may return the old value.
There is no guarantee that calls to `setState` will run synchronously,
as they may eventually be batched together. You can provide an optional
callback that will be executed when the call to setState is actually
completed.
When a function is provided to setState, it will be called at some point in
the future (not synchronously). It will be called with the up to date
component arguments (state, props, context). These values can be different
from this.* because your function may be called after receiveProps but before
shouldComponentUpdate, and this new state, props, and context will not yet be
assigned to this.
@param {object|function} partialState Next partial state or function to
produce next partial state to be merged with current state.
@param {?function} callback Called after state is updated.
@final
@protected | Component.prototype.setState ( partialState , callback ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
}; | Forces an update. This should only be invoked when it is known with
certainty that we are **not** in a DOM transaction.
You may want to call this when you know that some deeper aspect of the
component's state has changed but `setState` was not called.
This will not invoke `shouldComponentUpdate`, but it will invoke
`componentWillUpdate` and `componentDidUpdate`.
@param {?function} callback Called after update is complete.
@final
@protected | Component.prototype.forceUpdate ( callback ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
} | Convenience component with default shallow equality check for sCU. | PureComponent ( props , context , updater ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
} | Verifies the object is a ReactElement.
See https://reactjs.org/docs/react-api.html#isvalidelement
@param {?object} object
@return {boolean} True if `object` is a ReactElement.
@final | isValidElement ( object ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
} | Escape and wrap key so it is safe to use as a reactid
@param {string} key to be escaped.
@return {string} the escaped key. | escape ( key ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
} | Maps children that are typically specified as `props.children`.
See https://reactjs.org/docs/react-api.html#reactchildrenmap
The provided mapFunction(child, index) will be called for each
leaf child.
@param {?*} children Children tree container.
@param {function(*, int)} func The map function.
@param {*} context Context for mapFunction.
@return {object} Object containing the ordered map of results. | mapChildren ( children , func , context ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
} | Count the number of children that are typically specified as
`props.children`.
See https://reactjs.org/docs/react-api.html#reactchildrencount
@param {?*} children Children tree container.
@return {number} The number of children. | countChildren ( children ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
} | Iterates through children that are typically specified as `props.children`.
See https://reactjs.org/docs/react-api.html#reactchildrenforeach
The provided forEachFunc(child, index) will be called for each
leaf child.
@param {?*} children Children tree container.
@param {function(*, int)} forEachFunc
@param {*} forEachContext Context for forEachContext. | forEachChildren ( children , forEachFunc , forEachContext ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
} | Flatten a children object (typically specified as `props.children`) and
return an array with appropriately re-keyed children.
See https://reactjs.org/docs/react-api.html#reactchildrentoarray | toArray ( children ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function onlyChild(children) {
if (!isValidElement(children)) {
throw new Error('React.Children.only expected to receive a single React element child.');
}
return children;
} | Returns the first child in a collection of children and verifies that there
is only one child in the collection.
See https://reactjs.org/docs/react-api.html#reactchildrenonly
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 {ReactElement} The first and only `ReactElement` contained in the
structure. | onlyChild ( children ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
{
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // 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:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
{
// The `if` statement here prevents auto-disabling of the safe
// coercion ESLint rule, so we must manually disable it below.
// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
checkKeyStringCoercion(mappedChild.key);
}
}
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
// eslint-disable-next-line react-internal/safe-string-coercion
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
// eslint-disable-next-line react-internal/safe-string-coercion
var childrenString = String(children);
throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* 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 {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
throw new Error('React.Children.only expected to receive a single React element child.');
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null,
// Add these to use same hidden class in VM as ServerContext
_defaultValue: null,
_globalName: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
} | Generate a key string that identifies a element within a set.
@param {*} element A element that could contain a manual key.
@param {number} index Index that is used if a manual key is not provided.
@return {string} | getElementKey ( element , index ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function cloneElement(element, config, children) {
if (element === null || element === undefined) {
throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
}
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 (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
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);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
{
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // 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:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
{
// The `if` statement here prevents auto-disabling of the safe
// coercion ESLint rule, so we must manually disable it below.
// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
checkKeyStringCoercion(mappedChild.key);
}
}
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
// eslint-disable-next-line react-internal/safe-string-coercion
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
// eslint-disable-next-line react-internal/safe-string-coercion
var childrenString = String(children);
throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* 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 {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
throw new Error('React.Children.only expected to receive a single React element child.');
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null,
// Add these to use same hidden class in VM as ServerContext
_defaultValue: null,
_globalName: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
} | Clone and return a new ReactElement using element as the starting point.
See https://reactjs.org/docs/react-api.html#cloneelement | cloneElement ( element , config , children ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
} | Ensure that every element either is passed in a static location, in an
array with an explicit keys property defined, or in an object literal
with valid key property.
@internal
@param {ReactNode} node Statically passed child of any type.
@param {*} parentType node's parent's type. | validateChildKeys ( node , parentType ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
} | Given an element, validate that its props follow the propTypes definition,
provided by the type.
@param {ReactElement} element | validatePropTypes ( element ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === REACT_FRAGMENT_TYPE) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
} | Given a fragment, validate that it can only be provided with fragment props
@param {ReactElement} fragment | validateFragmentProps ( fragment ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.dev.js | MIT |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory(global.ReactDOM = {}, global.React));
}(this, (function (exports, React) { 'use strict'; | @license React
react-dom.development.js
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree. | (anonymous) ( global , factory ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getHostProps(element, props) {
var node = element;
var checked = props.checked;
var hostProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: undefined,
checked: checked != null ? checked : node._wrapperState.initialChecked
});
return hostProps; | Implements an <input> host component that allows setting these optional
props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
If `checked` or `value` are not supplied (or null/undefined), user actions
that affect the checked state or value will trigger updates to the element.
If they are supplied (and not null/undefined), the rendered element will not
trigger updates to the element. Instead, the props must change in order for
the rendered element to be updated.
The rendered element will be initialized as unchecked (or `defaultChecked`)
with an empty value (or `defaultValue`).
See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html | getHostProps ( element , props ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function validateProps(element, props) {
{
// If a value is not provided, then the children must be simple.
if (props.value == null) {
if (typeof props.children === 'object' && props.children !== null) {
React.Children.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
return;
}
if (!didWarnInvalidChild) {
didWarnInvalidChild = true;
error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
}
});
} else if (props.dangerouslySetInnerHTML != null) {
if (!didWarnInvalidInnerHTML) {
didWarnInvalidInnerHTML = true;
error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
}
}
} // TODO: Remove support for `selected` in <option>.
if (props.selected != null && !didWarnSelectedSetOnOption) {
error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
didWarnSelectedSetOnOption = true;
}
} | Implements an <option> host component that warns when `selected` is set. | validateProps ( element , props ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getHostProps$1(element, props) {
return assign({}, props, {
value: undefined
}); | Implements a <select> host component that allows optionally setting the
props `value` and `defaultValue`. If `multiple` is false, the prop must be a
stringable. If `multiple` is true, the prop must be an array of stringables.
If `value` is not supplied (or null/undefined), user actions that change the
selected option will trigger updates to the rendered options.
If it is supplied (and not null/undefined), the rendered options will not
update in response to user actions. Instead, the `value` prop must change in
order for the rendered options to update.
If `defaultValue` is provided, any options with the supplied values will be
selected. | $1 ( element , props ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
if (node.namespaceURI === SVG_NAMESPACE) {
if (!('innerHTML' in node)) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
var svgNode = reusableSVGContainer.firstChild;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
return;
}
}
node.innerHTML = html; | Set the innerHTML property of a node
@param {DOMElement} node
@param {string} html
@internal | (anonymous) ( node , html ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
var setTextContent = function (node, text) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text; | Set the textContent property of a node. For text updates, it's faster
to set the `nodeValue` of the Text node directly instead of using
`.textContent` which will remove the existing node and create a new one.
@param {DOMElement} node
@param {string} text
@internal | setTextContent ( node , text ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1); | @param {string} prefix vendor-specific prefix, eg: Webkit
@param {string} key style name, eg: transitionDuration
@return {string} style name prefixed with `prefix`, properly camelCased, eg:
WebkitTransitionDuration | prefixKey ( prefix , key ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function hyphenateStyleName(name) {
return name.replace(uppercasePattern, '-$1').toLowerCase().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-`. | hyphenateStyleName ( name ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function createDangerousStringForStyles(styles) {
{
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
var isCustomProperty = styleName.indexOf('--') === 0;
serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
delimiter = ';';
}
}
return serialized || null;
} | This creates a string that is expected to be equivalent to the style
attribute generated by server-side rendering. It by-passes warnings and
security checks so it's not safe to use this value for anything other than
comparison. It is only used in DEV for SSR validation. | createDangerousStringForStyles ( styles ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function setValueForStyles(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
{
if (!isCustomProperty) {
warnValidStyle$1(styleName, styles[styleName]);
}
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
if (styleName === 'float') {
styleName = 'cssFloat';
}
if (isCustomProperty) {
style.setProperty(styleName, styleValue);
} else {
style[styleName] = styleValue;
}
} | Sets the value for multiple styles on a node. If a value is specified as
'' (empty string), the corresponding style property will be unset.
@param {DOMElement} node
@param {object} styles | setValueForStyles ( node , styles ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function expandShorthandMap(styles) {
var expanded = {};
for (var key in styles) {
var longhands = shorthandToLonghand[key] || [key];
for (var i = 0; i < longhands.length; i++) {
expanded[longhands[i]] = key;
}
}
return expanded; | Given {color: 'red', overflow: 'hidden'} returns {
color: 'color',
overflowX: 'overflow',
overflowY: 'overflow',
}. This can be read as "the overflowY property was set by the overflow
shorthand". That is, the values are the property that each was derived from. | expandShorthandMap ( styles ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getEventTarget(nativeEvent) {
// Fallback to nativeEvent.srcElement for IE9
// https://github.com/facebook/react/issues/12506
var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
} // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === TEXT_NODE ? 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 ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getListener(inst, registrationName) {
var stateNode = inst.stateNode;
if (stateNode === null) {
// Work in progress (ex: onload events in incremental mode).
return null;
}
var props = getFiberCurrentPropsFromNode(stateNode);
if (props === null) {
// Work in progress.
return null;
}
var listener = props[registrationName];
if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
return null;
}
if (listener && typeof listener !== 'function') {
throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
}
return listener; | @param {object} inst The instance, which is the source of events.
@param {string} registrationName Name of listener (e.g. `onClick`).
@return {?function} The stored callback. | getListener ( inst , registrationName ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
hasError = false;
caughtError = null;
invokeGuardedCallbackImpl$1.apply(reporter, arguments); | Call a function while guarding against errors that happens within it.
Returns an error if it throws, otherwise null.
In production, this is implemented using a try-catch. The reason we don't
use a try-catch directly is so that we can swap out a different
implementation in DEV mode.
@param {String} name of the guard to use for logging or debugging
@param {Function} func The function to invoke
@param {*} context The context to use when calling the function
@param {...*} args Arguments for function | invokeGuardedCallback ( name , func , context , a , b , c , d , e , f ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
invokeGuardedCallback.apply(this, arguments);
if (hasError) {
var error = clearCaughtError();
if (!hasRethrowError) {
hasRethrowError = true;
rethrowError = error;
}
} | Same as invokeGuardedCallback, but instead of returning an error, it stores
it in a global so it can be rethrown by `rethrowCaughtError` later.
TODO: See if caughtError and rethrowError can be unified.
@param {String} name of the guard to use for logging or debugging
@param {Function} func The function to invoke
@param {*} context The context to use when calling the function
@param {...*} args Arguments for function | invokeGuardedCallbackAndCatchFirstError ( name , func , context , a , b , c , d , e , f ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function rethrowCaughtError() {
if (hasRethrowError) {
var error = rethrowError;
hasRethrowError = false;
rethrowError = null;
throw error;
} | During execution of guarded functions we will capture the first error which
we will rethrow to be handled by the top level error handler. | rethrowCaughtError ( ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
var MouseEventInterface = assign({}, UIEventInterface, {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
pageX: 0,
pageY: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
getModifierState: getEventModifierState,
button: 0,
buttons: 0,
relatedTarget: function (event) {
if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
return event.relatedTarget; | @interface MouseEvent
@see http://www.w3.org/TR/DOM-Level-3-Events/ | assign ( { } , UIEventInterface , { screenX : 0 , screenY : 0 , clientX : 0 , clientY : 0 , pageX : 0 , pageY : 0 , ctrlKey : 0 , shiftKey : 0 , altKey : 0 , metaKey : 0 , getModifierState : getEventModifierState , button : 0 , buttons : 0 , relatedTarget : function ( event ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
var ClipboardEventInterface = assign({}, EventInterface, {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData; | @interface Event
@see http://www.w3.org/TR/clipboard-apis/ | clipboardData ( event ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.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 ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
var WheelEventInterface = assign({}, MouseEventInterface, {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0; | @interface WheelEvent
@see http://www.w3.org/TR/DOM-Level-3-Events/ | deltaX ( event ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey); | Return whether a native keypress event is assumed to be a command.
This is required because Firefox fires `keypress` events for key commands
(cut, copy, select-all, etc.) even though no character is inserted. | isKeypressCommand ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getCompositionEventType(domEventName) {
switch (domEventName) {
case 'compositionstart':
return 'onCompositionStart';
case 'compositionend':
return 'onCompositionEnd';
case 'compositionupdate':
return 'onCompositionUpdate';
} | Translate native top level events into event types. | getCompositionEventType ( domEventName ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function isFallbackCompositionStart(domEventName, nativeEvent) {
return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE; | Does our fallback best-guess model think this event signifies that
composition has begun? | isFallbackCompositionStart ( domEventName , nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function isFallbackCompositionEnd(domEventName, nativeEvent) {
switch (domEventName) {
case 'keyup':
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case 'keydown':
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case 'keypress':
case 'mousedown':
case 'focusout':
// Events are not possible without cancelling IME.
return true;
default:
return false;
} | Does our fallback mode think that this event is the end of composition? | isFallbackCompositionEnd ( domEventName , nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null; | Google Input Tools provides composition data via a CustomEvent,
with the `data` property populated in the `detail` object. If this
is available on the event object, use it. If not, this is a plain
composition event and we have nothing special to extract.
@param {object} nativeEvent
@return {?string} | getDataFromCustomEvent ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function isUsingKoreanIME(nativeEvent) {
return nativeEvent.locale === 'ko'; | Check if a composition event was triggered by Korean IME.
Our fallback mode does not work well with IE's Korean IME,
so just use native composition events when Korean IME is used.
Although CompositionEvent.locale property is deprecated,
it is available in IE, where our fallback mode is enabled.
@param {object} nativeEvent
@return {boolean} | isUsingKoreanIME ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(domEventName);
} else if (!isComposing) {
if (isFallbackCompositionStart(domEventName, nativeEvent)) {
eventType = 'onCompositionStart';
}
} else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
eventType = 'onCompositionEnd';
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!isComposing && eventType === 'onCompositionStart') {
isComposing = initialize(nativeEventTarget);
} else if (eventType === 'onCompositionEnd') {
if (isComposing) {
fallbackData = getData();
}
}
}
var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
if (listeners.length > 0) {
var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: event,
listeners: listeners
});
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
} | @return {?object} A SyntheticCompositionEvent. | extractCompositionEvent ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getFallbackBeforeInputChars(domEventName, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if (isComposing) {
if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
var chars = getData();
reset();
isComposing = false;
return chars;
}
return null;
}
switch (domEventName) {
case 'paste':
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case 'keypress':
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (!isKeypressCommand(nativeEvent)) {
// IE fires the `keypress` event when a user types an emoji via
// Touch keyboard of Windows. In such a case, the `char` property
// holds an emoji character like `\uD83D\uDE0A`. Because its length
// is 2, the property `which` does not represent an emoji correctly.
// In such a case, we directly return the `char` property instead of
// using `which`.
if (nativeEvent.char && nativeEvent.char.length > 1) {
return nativeEvent.char;
} else if (nativeEvent.which) {
return String.fromCharCode(nativeEvent.which);
}
}
return null;
case 'compositionend':
return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
default:
return null;
} | For browsers that do not provide the `textInput` event, extract the
appropriate string to use for SyntheticInputEvent. | getFallbackBeforeInputChars ( domEventName , nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(domEventName, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
} // If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput');
if (listeners.length > 0) {
var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: event,
listeners: listeners
});
event.data = chars;
} | Extract a SyntheticInputEvent for `beforeInput`, based on either native
`textInput` or fallback behavior.
@return {?object} A SyntheticInputEvent. | extractBeforeInputEvent ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); | Create an `onBeforeInput` event to match
http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
This event plugin is based on the native `textInput` event
available in Chrome, Safari, Opera, and IE. This event fires after
`onKeyPress` and `onCompositionEnd`, but before `onInput`.
`beforeInput` is spec'd but not implemented in any browsers, and
the `input` event does not provide any useful information about what has
actually been added, contrary to the spec. Thus, `textInput` is the best
available event to identify the characters that have actually been inserted
into the target node.
This plugin is also responsible for emitting `composition` events, thus
allowing us to share composition fallback code for both `beforeInput` and
`composition` event types. | extractEvents ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget , eventSystemFlags , targetContainer ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function isEventSupported(eventNameSuffix) {
if (!canUseDOM) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = (eventName in document);
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
return isSupported; | Checks if an event is supported in the current execution environment.
NOTE: This will not work correctly for non-generic events such as `change`,
`reset`, `load`, `error`, and `select`.
Borrows from Modernizr.
@param {string} eventNameSuffix Event name, e.g. "click".
@return {boolean} True if the event is supported.
@internal
@license Modernizr 3.0.0pre (Custom Build) | MIT | isEventSupported ( eventNameSuffix ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onpropertychange', handlePropertyChange); | (For IE <=9) Starts tracking propertychange events on the passed-in element
and override the value property so that we can distinguish user events from
value changes in JS. | startWatchingForValueChange ( target , targetInst ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementInst = null; | (For IE <=9) Removes the event listeners from the currently-tracked element,
if any exists. | stopWatchingForValueChange ( ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
if (getInstIfValueChanged(activeElementInst)) {
manualDispatchChangeEvent(nativeEvent);
} | (For IE <=9) Handles a propertychange event, sending a `change` event if
the value of the active element has changed. | handlePropertyChange ( nativeEvent ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputOrChangeEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventPolyfill;
handleEventFunc = handleEventsForInputEventPolyfill;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(domEventName, targetInst);
if (inst) {
createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
return;
}
}
if (handleEventFunc) {
handleEventFunc(domEventName, targetNode, targetInst);
} // When blurring, set the value attribute for number inputs
if (domEventName === 'focusout') {
handleControlledInputBlur(targetNode);
} | This plugin creates an `onChange` event that normalizes change events
across form elements. This event fires at a time when it's possible to
change the element's value without seeing a flicker.
Supported elements are:
- input (see `isTextInputElement`)
- textarea
- select | $1 ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget , eventSystemFlags , targetContainer ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover';
var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout';
if (isOverEvent && !isReplayingEvent(nativeEvent)) {
// If this is an over event with a target, we might have already dispatched
// the event in the out event of the other target. If this is replayed,
// then it's because we couldn't dispatch against this target previously
// so we have to do it now instead.
var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
if (related) {
// If the related node is managed by React, we can assume that we have
// already dispatched the corresponding events during its mouseout.
if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
return;
}
}
}
if (!isOutEvent && !isOverEvent) {
// Must not be a mouse or pointer in or out - ignoring.
return;
}
var win; // TODO: why is this nullable in the types but we read from it?
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (isOutEvent) {
var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
from = targetInst;
to = _related ? getClosestInstanceFromNode(_related) : null;
if (to !== null) {
var nearestMounted = getNearestMountedFiber(to);
if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
to = null;
}
}
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return;
}
var SyntheticEventCtor = SyntheticMouseEvent;
var leaveEventType = 'onMouseLeave';
var enterEventType = 'onMouseEnter';
var eventTypePrefix = 'mouse';
if (domEventName === 'pointerout' || domEventName === 'pointerover') {
SyntheticEventCtor = SyntheticPointerEvent;
leaveEventType = 'onPointerLeave';
enterEventType = 'onPointerEnter';
eventTypePrefix = 'pointer';
}
var fromNode = from == null ? win : getNodeFromInstance(from);
var toNode = to == null ? win : getNodeFromInstance(to);
var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget);
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = null; // We should only process this nativeEvent if we are processing
// the first ancestor. Next time, we will ignore the event.
var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
if (nativeTargetInst === targetInst) {
var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget);
enterEvent.target = toNode;
enterEvent.relatedTarget = fromNode;
enter = enterEvent;
}
accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to); | For almost every interaction we care about, there will be both a top-level
`mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
we do not extract duplicate events. However, moving the mouse into the
browser from outside will not fire a `mouseout` event. In this case, we use
the `mouseover` top-level event. | $2 ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget , eventSystemFlags , targetContainer ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function shallowEqual(objA, objB) {
if (objectIs(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.
for (var i = 0; i < keysA.length; i++) {
var currentKey = keysA[i];
if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
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 ( objA , objB ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.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 ( node ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.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 ( node ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === TEXT_NODE) {
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 ( root , offset ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getOffsets(outerNode) {
var ownerDocument = outerNode.ownerDocument;
var win = ownerDocument && ownerDocument.defaultView || window;
var selection = win.getSelection && win.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode,
anchorOffset = selection.anchorOffset,
focusNode = selection.focusNode,
focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
// up/down buttons on an <input type="number">. Anonymous divs do not seem to
// expose properties, triggering a "Permission denied error" if any of its
// properties are accessed. The only seemingly possible way to avoid erroring
// is to access a property that typically works for non-anonymous divs and
// catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
anchorNode.nodeType;
focusNode.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); | @param {DOMElement} outerNode
@return {?object} | getOffsets ( outerNode ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
var length = 0;
var start = -1;
var end = -1;
var indexWithinAnchor = 0;
var indexWithinFocus = 0;
var node = outerNode;
var parentNode = null;
outer: while (true) {
var next = null;
while (true) {
if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
start = length + anchorOffset;
}
if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
end = length + focusOffset;
}
if (node.nodeType === TEXT_NODE) {
length += node.nodeValue.length;
}
if ((next = node.firstChild) === null) {
break;
} // Moving from `node` to its first child `next`.
parentNode = node;
node = next;
}
while (true) {
if (node === outerNode) {
// If `outerNode` has children, this is always the second time visiting
// it. If it has no children, this is still the first loop, and the only
// valid selection is anchorNode and focusNode both equal to this node
// and both offsets 0, in which case we will have handled above.
break outer;
}
if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
start = length;
}
if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
end = length;
}
if ((next = node.nextSibling) !== null) {
break;
}
node = parentNode;
parentNode = node.parentNode;
} // Moving from `node` to its next sibling `next`.
node = next;
}
if (start === -1 || end === -1) {
// This should never happen. (Would happen if the anchor/focus nodes aren't
// actually inside the passed-in node.)
return null;
}
return {
start: start,
end: end
}; | Returns {start, end} where `start` is the character/codepoint index of
(anchorNode, anchorOffset) within the textContent of `outerNode`, and
`end` is the index of (focusNode, focusOffset).
Returns null if you pass in garbage input but we should probably just crash.
Exported only for testing. | getModernOffsetsFromPoints ( outerNode , anchorNode , anchorOffset , focusNode , focusOffset ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function setOffsets(node, offsets) {
var doc = node.ownerDocument || document;
var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
// (For instance: TinyMCE editor used in a list component that supports pasting to add more,
// fails when pasting 100+ items)
if (!win.getSelection) {
return;
}
var selection = win.getSelection();
var length = node.textContent.length;
var start = Math.min(offsets.start, length);
var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
return;
}
var range = doc.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
} | In modern non-IE browsers, we can support both forward and backward
selections.
Note: IE10+ supports the Selection object, but it does not support
the `extend` method, which means that even in modern IE, it's not possible
to programmatically create a backward selection. Thus, for all IE
versions, we use the old IE API to create our selections.
@param {DOMElement|DOMTextNode} node
@param {object} offsets | setOffsets ( node , offsets ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function hasSelectionCapabilities(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true'); | @hasSelectionCapabilities: we get the element types that support selection
from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
and `selectionEnd` rows. | hasSelectionCapabilities ( elem ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function restoreSelection(priorSelectionInformation) {
var curFocusedElem = getActiveElementDeep();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
setSelection(priorFocusedElem, priorSelectionRange);
} // Focusing a node can change the scroll position, which is undesirable
var ancestors = [];
var ancestor = priorFocusedElem;
while (ancestor = ancestor.parentNode) {
if (ancestor.nodeType === ELEMENT_NODE) {
ancestors.push({
element: ancestor,
left: ancestor.scrollLeft,
top: ancestor.scrollTop
});
}
}
if (typeof priorFocusedElem.focus === 'function') {
priorFocusedElem.focus();
}
for (var i = 0; i < ancestors.length; i++) {
var info = ancestors[i];
info.element.scrollLeft = info.left;
info.element.scrollTop = info.top;
}
} | @restoreSelection: If any selection information was potentially lost,
restore it. This is useful when performing operations that could remove dom
nodes and place them back in, resulting in focus being lost. | restoreSelection ( priorSelectionInformation ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getSelection(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else {
// Content editable or old IE textarea.
selection = getOffsets(input);
}
return selection || {
start: 0,
end: 0
}; | @getSelection: Gets the selection bounds of a focused textarea, input or
contentEditable node.
-@input: Look up selection bounds of this input
-@return {start: selectionStart, end: selectionEnd} | getSelection ( input ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function setSelection(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else {
setOffsets(input, offsets);
} | @setSelection: Sets the selection bounds of a textarea or input and focuses
the input.
-@input Set selection bounds of this input or textarea
-@offsets Object of same form that is returned from get* | setSelection ( input , offsets ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getSelection$1(node) {
if ('selectionStart' in node && hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else {
var win = node.ownerDocument && node.ownerDocument.defaultView || window;
var selection = win.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} | 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. | $1 ( node ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
function getEventTargetDocument(eventTarget) {
return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument; | Get document associated with the event target. | getEventTargetDocument ( eventTarget ) | javascript | facebook/memlab | packages/lens/src/tests/lib/react-dom-v18.dev.js | https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.