code
stringlengths 28
313k
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
74
| language
stringclasses 1
value | repo
stringlengths 5
60
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async getItem(itemPosition) {
const items = await $(this.rootElement).$$('[data-id="vertical-item"]');
if (items[itemPosition]) {
return new PageVerticalItem(
`${this.rootElement} [data-id="vertical-item"]:nth-child(${itemPosition + 1})`,
);
}
return null;
}
|
Returns a new VerticalItem page object of the element in item position.
@method
@param {number} itemPosition - The base 0 index of the vertical item.
|
getItem
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalNavigation/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalNavigation/pageObject/index.js
|
MIT
|
async getSectionOverflow(itemPosition) {
const items = await $(this.rootElement).$$('[data-id="vertical-overflow-container"]');
if (items[itemPosition]) {
return new PageVerticalSectionOverflow(
`${
this.rootElement
} [data-id="vertical-overflow-container"]:nth-child(${itemPosition + 1})`,
);
}
return null;
}
|
Returns a new VerticalSectionOverflow page object of the element in item position.
@method
@param {number} itemPosition - The base 0 index of the vertical section overflow.
|
getSectionOverflow
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalNavigation/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalNavigation/pageObject/index.js
|
MIT
|
constructor(props) {
super(props);
this.entityHeaderId = uniqueId('entity-header');
}
|
Represents a section within a VerticalNavigation.
@category Layout
|
constructor
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSection/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSection/index.js
|
MIT
|
constructor(props) {
super(props);
this.searchResultsId = uniqueId('search-results');
this.state = {
isExpanded: props.expanded,
};
this.toggleOverflow = this.toggleOverflow.bind(this);
}
|
Represents an overflow of items from a preceding VerticalNavigationSection,
with the ability to toggle visibility.
@category Layout
|
constructor
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/index.js
|
MIT
|
async click() {
await $(this.rootElement)
.$('[data-id="vertical-overflow-button"]')
.click();
}
|
Clicks the vertical section overflow button.
@method
|
click
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/pageObject/index.js
|
MIT
|
async isExpanded() {
return $(this.rootElement)
.$('[data-id="vertical-overflow"]')
.isDisplayed();
}
|
Returns true when the overflow section is visible, false otherwise.
@method
@returns {bool}
|
isExpanded
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/pageObject/index.js
|
MIT
|
async waitUntilExpand() {
await browser.waitUntil(async () => this.isExpanded());
}
|
Wait until the expand transition has finished.
@method
|
waitUntilExpand
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/pageObject/index.js
|
MIT
|
async waitUntilCollapse() {
await browser.waitUntil(async () => !(await this.isExpanded()));
}
|
Wait until the contract transition has finished.
@method
|
waitUntilCollapse
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/pageObject/index.js
|
MIT
|
async hasFocusButton() {
return $(this.rootElement)
.$('[data-id="vertical-overflow-button"]')
.isFocused();
}
|
Returns true when the vertical section overflow button has focus.
@method
@returns {bool}
|
hasFocusButton
|
javascript
|
nexxtway/react-rainbow
|
src/components/VerticalSectionOverflow/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VerticalSectionOverflow/pageObject/index.js
|
MIT
|
constructor(props) {
super(props);
this.errorId = uniqueId('error-message');
this.groupNameId = props.name || uniqueId('visual-picker');
this.handleChange = this.handleChange.bind(this);
}
|
A VisualPicker can be either radio buttons, checkboxes, or links that are visually enhanced.
@category Form
|
constructor
|
javascript
|
nexxtway/react-rainbow
|
src/components/VisualPicker/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VisualPicker/index.js
|
MIT
|
async getItem(itemPosition) {
const items = await $(this.rootElement).$$(
'span[data-id="visual-picker_option-container"]',
);
if (items[itemPosition]) {
return new PageVisualPickerOption(
`${
this.rootElement
} span[data-id="visual-picker_option-container"]:nth-child(${itemPosition + 1})`,
);
}
return null;
}
|
Returns a new VisualPickerOption page object of the element in item position.
@method
@param {number} itemPosition - The base 0 index of the VisualPickerOption.
|
getItem
|
javascript
|
nexxtway/react-rainbow
|
src/components/VisualPicker/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VisualPicker/pageObject/index.js
|
MIT
|
async hasFocus() {
return $(this.rootElement)
.$('input')
.isFocused();
}
|
Returns true when the input has the focus.
@method
@returns {bool}
|
hasFocus
|
javascript
|
nexxtway/react-rainbow
|
src/components/VisualPickerOption/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VisualPickerOption/pageObject/index.js
|
MIT
|
async isChecked() {
return $(this.rootElement)
.$('input')
.isSelected();
}
|
Returns true when the input is checked.
@method
@returns {bool}
|
isChecked
|
javascript
|
nexxtway/react-rainbow
|
src/components/VisualPickerOption/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/VisualPickerOption/pageObject/index.js
|
MIT
|
handleOnChange = event => {
const weekDayValue = event.target.value;
const isChecked = event.target.checked;
if (!disabled && !readOnly) {
onChange(getNormalizedValue(weekDayValue, isChecked, multiple, value));
}
}
|
A WeekDayPicker allows to select the days of the week
@category Form
|
handleOnChange
|
javascript
|
nexxtway/react-rainbow
|
src/components/WeekDayPicker/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/WeekDayPicker/index.js
|
MIT
|
async clickOn(weekDay) {
const inputRef = await this.getInputRef(weekDay);
await inputRef.click();
}
|
Triggers a click over the checkbox/radio input by clicking his label reference.
@method
@param {string} weekDay - The value of the day we want the make click.
|
clickOn
|
javascript
|
nexxtway/react-rainbow
|
src/components/WeekDayPicker/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/WeekDayPicker/pageObject/index.js
|
MIT
|
async getSelectedDays() {
const selected = (await Promise.all(
weekDays.map(async weekDay => {
const input = await this.getInput(weekDay);
return (await input.isSelected()) ? weekDay : undefined;
}),
)).filter(value => value);
return selected;
}
|
Returns an array with the selected days
@method
|
getSelectedDays
|
javascript
|
nexxtway/react-rainbow
|
src/components/WeekDayPicker/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/WeekDayPicker/pageObject/index.js
|
MIT
|
async getFocusedDay() {
const focusedDay = (await Promise.all(
weekDays.map(async weekDay => {
const input = await this.getInput(weekDay);
return (await input.isFocused()) ? weekDay : undefined;
}),
)).filter(value => value);
return focusedDay.length ? focusedDay[0] : undefined;
}
|
Returns the day that has the current focus or empty
@method
|
getFocusedDay
|
javascript
|
nexxtway/react-rainbow
|
src/components/WeekDayPicker/pageObject/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/WeekDayPicker/pageObject/index.js
|
MIT
|
ZoomableImage = ({ className, style, src, alt, width, height }) => {
const ref = useRef();
const imageRect = useRef({});
const [isOpen, setIsOpen] = useState(false);
const open = () => {
imageRect.current = ref.current.getBoundingClientRect();
setIsOpen(true);
};
const close = () => {
setIsOpen(false);
};
return (
<>
<StyledImage
className={className}
style={style}
src={src}
alt={alt}
width={width}
height={height}
ref={ref}
isOpen={isOpen}
onClick={open}
/>
<RenderIf isTrue={isOpen}>
<ZoomedImage src={src} alt={alt} close={close} originalRect={imageRect.current} />
</RenderIf>
</>
);
}
|
ZoomableImage renders an image that is zoomed in when clicked
|
ZoomableImage
|
javascript
|
nexxtway/react-rainbow
|
src/components/ZoomableImage/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/components/ZoomableImage/index.js
|
MIT
|
function getElementSize(element) {
const rect = element.getBoundingClientRect();
return {
width: Math.round(rect.width),
height: Math.round(rect.height),
};
}
|
Get element size
@param {HTMLElement} element - element to return the size.
@returns {Object} {width, height}
|
getElementSize
|
javascript
|
nexxtway/react-rainbow
|
src/libs/ResizeSensor/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/libs/ResizeSensor/index.js
|
MIT
|
function attachResizeEvent(element, resizeListener) {
if (!element) {
return;
}
if (element.resizedAttached) {
element.resizedAttached.add(() => resizeListener());
return;
}
element.resizedAttached = new EventQueue();
element.resizedAttached.add(() => resizeListener());
const resizeSensor = createResizeSensor();
element.resizeSensor = resizeSensor;
element.appendChild(resizeSensor);
const position = (window.getComputedStyle(element) || element.style).getPropertyValue(
'position',
);
if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
element.style.position = 'relative';
}
const expand = resizeSensor.childNodes[0];
const expandChild = expand.childNodes[0];
const shrink = resizeSensor.childNodes[1];
let dirty;
let rafId;
let size = getElementSize(element);
let lastWidth = size.width;
let lastHeight = size.height;
let initialHiddenCheck = true;
let resetRafId;
const resetExpandShrink = () => {
expandChild.style.width = '100000px';
expandChild.style.height = '100000px';
expand.scrollLeft = 100000;
expand.scrollTop = 100000;
shrink.scrollLeft = 100000;
shrink.scrollTop = 100000;
};
const reset = () => {
// Check if element is hidden
if (initialHiddenCheck) {
if (!expand.scrollTop && !expand.scrollLeft) {
// reset
resetExpandShrink();
// Check in next frame
if (!resetRafId) {
resetRafId = requestAnimationFrame(() => {
resetRafId = 0;
reset();
});
}
return;
}
initialHiddenCheck = false;
}
resetExpandShrink();
};
resizeSensor.resetSensor = reset;
const onResized = () => {
rafId = 0;
if (!dirty) {
return;
}
lastWidth = size.width;
lastHeight = size.height;
if (element.resizedAttached) {
element.resizedAttached.call(size);
}
};
const onScroll = () => {
size = getElementSize(element);
dirty = size.width !== lastWidth || size.height !== lastHeight;
if (dirty && !rafId) {
rafId = requestAnimationFrame(onResized);
}
reset();
};
const addEvent = (elem, name, callback) => {
elem.addEventListener(name, callback);
};
addEvent(expand, 'scroll', onScroll);
addEvent(shrink, 'scroll', onScroll);
// Fix for custom Elements
requestAnimationFrame(reset);
}
|
@param {HTMLElement} element - element to listen resize.
@param {Function} resizeListener - resize event listener.
|
attachResizeEvent
|
javascript
|
nexxtway/react-rainbow
|
src/libs/ResizeSensor/index.js
|
https://github.com/nexxtway/react-rainbow/blob/master/src/libs/ResizeSensor/index.js
|
MIT
|
constructor(regexp, m) {
this._setDefaults(regexp);
if (regexp instanceof RegExp) {
this.ignoreCase = regexp.ignoreCase;
this.multiline = regexp.multiline;
regexp = regexp.source;
} else if (typeof regexp === 'string') {
this.ignoreCase = m && m.indexOf('i') !== -1;
this.multiline = m && m.indexOf('m') !== -1;
} else {
throw Error('Expected a regexp or string');
}
this.tokens = ret(regexp);
}
|
@constructor
@param {RegExp|string} regexp
@param {string} m
|
constructor
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_setDefaults(regexp) {
// When a repetitional token has its max set to Infinite,
// randexp won't actually generate a random amount between min and Infinite
// instead it will see Infinite as min + 100.
this.max = regexp.max != null ? regexp.max :
RandExp.prototype.max != null ? RandExp.prototype.max : 100;
// This allows expanding to include additional characters
// for instance: RandExp.defaultRange.add(0, 65535);
this.defaultRange = regexp.defaultRange ?
regexp.defaultRange : this.defaultRange.clone();
if (regexp.randInt) {
this.randInt = regexp.randInt;
}
}
|
Checks if some custom properties have been set for this regexp.
@param {RandExp} randexp
@param {RegExp} regexp
|
_setDefaults
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
gen() {
return this._gen(this.tokens, []);
}
|
Generates the random string.
@return {string}
|
gen
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_gen(token, groups) {
let stack, str, n, i, l, code, expandedSet;
switch (token.type) {
case types.ROOT:
case types.GROUP:
// Ignore lookaheads for now.
if (token.followedBy || token.notFollowedBy) { return ''; }
// Insert placeholder until group string is generated.
if (token.remember && token.groupNumber === undefined) {
token.groupNumber = groups.push(null) - 1;
}
stack = token.options ?
this._randSelect(token.options) : token.stack;
str = '';
for (i = 0, l = stack.length; i < l; i++) {
str += this._gen(stack[i], groups);
}
if (token.remember) {
groups[token.groupNumber] = str;
}
return str;
case types.POSITION:
// Do nothing for now.
return '';
case types.SET:
expandedSet = this._expand(token);
if (!expandedSet.length) { return ''; }
return String.fromCharCode(this._randSelect(expandedSet));
case types.REPETITION:
// Randomly generate number between min and max.
n = this.randInt(token.min,
token.max === Infinity ? token.min + this.max : token.max);
str = '';
for (i = 0; i < n; i++) {
str += this._gen(token.value, groups);
}
return str;
case types.REFERENCE:
return groups[token.value - 1] || '';
case types.CHAR:
code = this.ignoreCase && this._randBool() ?
this._toOtherCase(token.value) : token.value;
return String.fromCharCode(code);
}
}
|
Generate random string modeled after given tokens.
@param {Object} token
@param {Array.<string>} groups
@return {string}
|
_gen
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_toOtherCase(code) {
return code + (97 <= code && code <= 122 ? -32 :
65 <= code && code <= 90 ? 32 : 0);
}
|
If code is alphabetic, converts to other case.
If not alphabetic, returns back code.
@param {number} code
@return {number}
|
_toOtherCase
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_randBool() {
return !this.randInt(0, 1);
}
|
Randomly returns a true or false value.
@return {boolean}
|
_randBool
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_randSelect(arr) {
if (arr instanceof DRange) {
return arr.index(this.randInt(0, arr.length - 1));
}
return arr[this.randInt(0, arr.length - 1)];
}
|
Randomly selects and returns a value from the array.
@param {Array.<Object>} arr
@return {Object}
|
_randSelect
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
_expand(token) {
if (token.type === ret.types.CHAR) {
return new DRange(token.value);
} else if (token.type === ret.types.RANGE) {
return new DRange(token.from, token.to);
} else {
let drange = new DRange();
for (let i = 0; i < token.set.length; i++) {
let subrange = this._expand(token.set[i]);
drange.add(subrange);
if (this.ignoreCase) {
for (let j = 0; j < subrange.length; j++) {
let code = subrange.index(j);
let otherCaseCode = this._toOtherCase(code);
if (code !== otherCaseCode) {
drange.add(otherCaseCode);
}
}
}
}
if (token.not) {
return this.defaultRange.clone().subtract(drange);
} else {
return this.defaultRange.clone().intersect(drange);
}
}
}
|
Expands a token to a DiscontinuousRange of characters which has a
length and an index function (for random selecting).
@param {Object} token
@return {DiscontinuousRange}
|
_expand
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
randInt(a, b) {
return a + Math.floor(Math.random() * (1 + b - a));
}
|
Randomly generates and returns a number between a and b (inclusive).
@param {number} a
@param {number} b
@return {number}
|
randInt
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
get defaultRange() {
return this._range = this._range || new DRange(32, 126);
}
|
Default range of characters to generate from.
|
defaultRange
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
static randexp(regexp, m) {
let randexp;
if(typeof regexp === 'string') {
regexp = new RegExp(regexp, m);
}
if (regexp._randexp === undefined) {
randexp = new RandExp(regexp, m);
regexp._randexp = randexp;
} else {
randexp = regexp._randexp;
randexp._setDefaults(regexp);
}
return randexp.gen();
}
|
Enables use of randexp with a shorter call.
@param {RegExp|string| regexp}
@param {string} m
@return {string}
|
randexp
|
javascript
|
fent/randexp.js
|
lib/randexp.js
|
https://github.com/fent/randexp.js/blob/master/lib/randexp.js
|
MIT
|
setWindowOptions = function () {
for (const key in options) {
if (typeof window !== 'undefined' &&
typeof window.texme !== 'undefined' &&
typeof window.texme[key] !== 'undefined') {
options[key] = window.texme[key]
}
}
}
|
Read configuration options specified in `window.texme` and
configure TeXMe.
@memberof inner
|
setWindowOptions
|
javascript
|
susam/texme
|
texme.js
|
https://github.com/susam/texme/blob/master/texme.js
|
MIT
|
loadjs = function (url, callback) {
const script = window.document.createElement('script')
script.src = url
script.onload = callback
window.document.head.appendChild(script)
}
|
Load JS in browser environment.
@param {string} url - URL of JavaScript file.
@param {function} callback - Callback to invoke after script loads.
@memberof inner
|
loadjs
|
javascript
|
susam/texme
|
texme.js
|
https://github.com/susam/texme/blob/master/texme.js
|
MIT
|
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this);
});
}
}
|
highlight a given string on a jquery object by wrapping it in
span elements with the given class name.
|
highlight
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/doctools.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/doctools.js
|
MIT
|
function displayNextItem() {
// results left, load the summary and display it
if (results.length) {
var item = results.pop();
var listItem = $('<li style="display:none"></li>');
if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
// dirhtml builder
var dirname = item[0] + '/';
if (dirname.match(/\/index\/$/)) {
dirname = dirname.substring(0, dirname.length-6);
} else if (dirname == 'index/') {
dirname = '';
}
listItem.append($('<a/>').attr('href',
DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
highlightstring + item[2]).html(item[1]));
} else {
// normal html builders
listItem.append($('<a/>').attr('href',
item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
highlightstring + item[2]).html(item[1]));
}
if (item[3]) {
listItem.append($('<span> (' + item[3] + ')</span>'));
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
$.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt',
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
if (data !== '' && data !== undefined) {
listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
}
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}});
} else {
// no source available, just display title
Search.output.append(listItem);
listItem.slideDown(5, function() {
displayNextItem();
});
}
}
// search finished, update title and status message
else {
Search.stopPulse();
Search.title.text(_('Search Results'));
if (!resultCount)
Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
else
Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
Search.status.fadeIn(500);
}
}
|
execute search (requires search index to be loaded)
|
displayNextItem
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/searchtools.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/searchtools.js
|
MIT
|
function setComparator() {
// If the first three letters are "asc", sort in ascending order
// and remove the prefix.
if (by.substring(0,3) == 'asc') {
var i = by.substring(3);
comp = function(a, b) { return a[i] - b[i]; };
} else {
// Otherwise sort in descending order.
comp = function(a, b) { return b[by] - a[by]; };
}
// Reset link styles and format the selected sort option.
$('a.sel').attr('href', '#').removeClass('sel');
$('a.by' + by).removeAttr('href').addClass('sel');
}
|
Set comp, which is a comparator function used for sorting and
inserting comments into the list.
|
setComparator
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function initComparator() {
by = 'rating'; // Default to sort by rating.
// If the sortBy cookie is set, use that instead.
if (document.cookie.length > 0) {
var start = document.cookie.indexOf('sortBy=');
if (start != -1) {
start = start + 7;
var end = document.cookie.indexOf(";", start);
if (end == -1) {
end = document.cookie.length;
by = unescape(document.cookie.substring(start, end));
}
}
}
setComparator();
}
|
Create a comp function. If the user has preferences stored in
the sortBy cookie, use those, otherwise use the default.
|
initComparator
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source);
if (data.comments.length === 0) {
ul.html('<li>No comments yet.</li>');
ul.data('empty', true);
} else {
// If there are comments, sort them and put them in the list.
var comments = sortComments(data.comments);
speed = data.comments.length * 100;
appendComments(comments, ul);
ul.data('empty', false);
}
$('#cn' + id).slideUp(speed + 200);
ul.slideDown(speed);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem retrieving the comments.');
},
dataType: 'json'
});
}
|
Perform an ajax request to get comments for a node
and insert the comments into the comments tree.
|
getComments
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function addComment(form) {
var node_id = form.find('input[name="node"]').val();
var parent_id = form.find('input[name="parent"]').val();
var text = form.find('textarea[name="comment"]').val();
var proposal = form.find('textarea[name="proposal"]').val();
if (text == '') {
showError('Please enter a comment.');
return;
}
// Disable the form that is being submitted.
form.find('textarea,input').attr('disabled', 'disabled');
// Send the comment to the server.
$.ajax({
type: "POST",
url: opts.addCommentURL,
dataType: 'json',
data: {
node: node_id,
parent: parent_id,
text: text,
proposal: proposal
},
success: function(data, textStatus, error) {
// Reset the form.
if (node_id) {
hideProposeChange(node_id);
}
form.find('textarea')
.val('')
.add(form.find('input'))
.removeAttr('disabled');
var ul = $('#cl' + (node_id || parent_id));
if (ul.data('empty')) {
$(ul).empty();
ul.data('empty', false);
}
insertComment(data.comment);
var ao = $('#ao' + node_id);
ao.find('img').attr({'src': opts.commentBrightImage});
if (node_id) {
// if this was a "root" comment, remove the commenting box
// (the user can get it back by reopening the comment popup)
$('#ca' + node_id).slideUp();
}
},
error: function(request, textStatus, error) {
form.find('textarea,input').removeAttr('disabled');
showError('Oops, there was a problem adding the comment.');
}
});
}
|
Add a comment via ajax and insert the comment into the comment tree.
|
addComment
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function appendComments(comments, ul) {
$.each(comments, function() {
var div = createCommentDiv(this);
ul.append($(document.createElement('li')).html(div));
appendComments(this.children, div.find('ul.comment-children'));
// To avoid stagnating data, don't store the comments children in data.
this.children = null;
div.data('comment', this);
});
}
|
Recursively append comments to the main comment list and children
lists, creating the comment tree.
|
appendComments
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function insertComment(comment) {
var div = createCommentDiv(comment);
// To avoid stagnating data, don't store the comments children in data.
comment.children = null;
div.data('comment', comment);
var ul = $('#cl' + (comment.node || comment.parent));
var siblings = getChildren(ul);
var li = $(document.createElement('li'));
li.hide();
// Determine where in the parents children list to insert this comment.
for(i=0; i < siblings.length; i++) {
if (comp(comment, siblings[i]) <= 0) {
$('#cd' + siblings[i].id)
.parent()
.before(li.html(div));
li.slideDown('fast');
return;
}
}
// If we get here, this comment rates lower than all the others,
// or it is the only comment in the list.
ul.append(li.html(div));
li.slideDown('fast');
}
|
After adding a new comment, it must be inserted in the correct
location in the comment tree.
|
insertComment
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function handleReSort(link) {
var classes = link.attr('class').split(/\s+/);
for (var i=0; i<classes.length; i++) {
if (classes[i] != 'sort-option') {
by = classes[i].substring(2);
}
}
setComparator();
// Save/update the sortBy cookie.
var expiration = new Date();
expiration.setDate(expiration.getDate() + 365);
document.cookie= 'sortBy=' + escape(by) +
';expires=' + expiration.toUTCString();
$('ul.comment-ul').each(function(index, ul) {
var comments = getChildren($(ul), true);
comments = sortComments(comments);
appendComments(comments, $(ul).empty());
});
}
|
Handle when the user clicks on a sort by link.
|
handleReSort
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function handleVote(link) {
if (!opts.voting) {
showError("You'll need to login to vote.");
return;
}
var id = link.attr('id');
if (!id) {
// Didn't click on one of the voting arrows.
return;
}
// If it is an unvote, the new vote value is 0,
// Otherwise it's 1 for an upvote, or -1 for a downvote.
var value = 0;
if (id.charAt(1) != 'u') {
value = id.charAt(0) == 'u' ? 1 : -1;
}
// The data to be sent to the server.
var d = {
comment_id: id.substring(2),
value: value
};
// Swap the vote and unvote links.
link.hide();
$('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
.show();
// The div the comment is displayed in.
var div = $('div#cd' + d.comment_id);
var data = div.data('comment');
// If this is not an unvote, and the other vote arrow has
// already been pressed, unpress it.
if ((d.value !== 0) && (data.vote === d.value * -1)) {
$('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
$('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
}
// Update the comments rating in the local data.
data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
data.vote = d.value;
div.data('comment', data);
// Change the rating text.
div.find('.rating:first')
.text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));
// Send the vote information to the server.
$.ajax({
type: "POST",
url: opts.processVoteURL,
data: d,
error: function(request, textStatus, error) {
showError('Oops, there was a problem casting that vote.');
}
});
}
|
Function to process a vote when a user clicks an arrow.
|
handleVote
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function openReply(id) {
// Swap out the reply link for the hide link
$('#rl' + id).hide();
$('#cr' + id).show();
// Add the reply li to the children ul.
var div = $(renderTemplate(replyTemplate, {id: id})).hide();
$('#cl' + id)
.prepend(div)
// Setup the submit handler for the reply form.
.find('#rf' + id)
.submit(function(event) {
event.preventDefault();
addComment($('#rf' + id));
closeReply(id);
})
.find('input[type=button]')
.click(function() {
closeReply(id);
});
div.slideDown('fast', function() {
$('#rf' + id).find('textarea').focus();
});
}
|
Open a reply form used to reply to an existing comment.
|
openReply
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function closeReply(id) {
// Remove the reply div from the DOM.
$('#rd' + id).slideUp('fast', function() {
$(this).remove();
});
// Swap out the hide link for the reply link
$('#cr' + id).hide();
$('#rl' + id).show();
}
|
Close the reply form opened with openReply.
|
closeReply
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function sortComments(comments) {
comments.sort(comp);
$.each(comments, function() {
this.children = sortComments(this.children);
});
return comments;
}
|
Recursively sort a tree of comments using the comp comparator.
|
sortComments
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function getChildren(ul, recursive) {
var children = [];
ul.children().children("[id^='cd']")
.each(function() {
var comment = $(this).data('comment');
if (recursive)
comment.children = getChildren($(this).find('#cl' + comment.id), true);
children.push(comment);
});
return children;
}
|
Get the children comments from a ul. If recursive is true,
recursively include childrens' children.
|
getChildren
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function createCommentDiv(comment) {
if (!comment.displayed && !opts.moderator) {
return $('<div class="moderate">Thank you! Your comment will show up '
+ 'once it is has been approved by a moderator.</div>');
}
// Prettify the comment rating.
comment.pretty_rating = comment.rating + ' point' +
(comment.rating == 1 ? '' : 's');
// Make a class (for displaying not yet moderated comments differently)
comment.css_class = comment.displayed ? '' : ' moderate';
// Create a div for this comment.
var context = $.extend({}, opts, comment);
var div = $(renderTemplate(commentTemplate, context));
// If the user has voted on this comment, highlight the correct arrow.
if (comment.vote) {
var direction = (comment.vote == 1) ? 'u' : 'd';
div.find('#' + direction + 'v' + comment.id).hide();
div.find('#' + direction + 'u' + comment.id).show();
}
if (opts.moderator || comment.text != '[deleted]') {
div.find('a.reply').show();
if (comment.proposal_diff)
div.find('#sp' + comment.id).show();
if (opts.moderator && !comment.displayed)
div.find('#cm' + comment.id).show();
if (opts.moderator || (opts.username == comment.username))
div.find('#dc' + comment.id).show();
}
return div;
}
|
Create a div to display a comment in.
|
createCommentDiv
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
function renderTemplate(template, context) {
var esc = $(document.createElement('div'));
function handle(ph, escape) {
var cur = context;
$.each(ph.split('.'), function() {
cur = cur[this];
});
return escape ? esc.text(cur || "").html() : cur;
}
return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
return handle(arguments[2], arguments[1] == '%' ? true : false);
});
}
|
A simple template renderer. Placeholders such as <%id%> are replaced
by context['id'] with items being escaped. Placeholders such as <#id#>
are not escaped.
|
renderTemplate
|
javascript
|
stitchfix/pyxley
|
docs/_build/html/_static/websupport.js
|
https://github.com/stitchfix/pyxley/blob/master/docs/_build/html/_static/websupport.js
|
MIT
|
FixedColumns = function ( dt, init ) {
var that = this;
/* Sanity check - you just know it will happen */
if ( ! ( this instanceof FixedColumns ) )
{
alert( "FixedColumns warning: FixedColumns must be initialised with the 'new' keyword." );
return;
}
if ( typeof init == 'undefined' )
{
init = {};
}
// Use the DataTables Hungarian notation mapping method, if it exists to
// provide forwards compatibility for camel case variables
var camelToHungarian = $.fn.dataTable.camelToHungarian;
if ( camelToHungarian ) {
camelToHungarian( FixedColumns.defaults, FixedColumns.defaults, true );
camelToHungarian( FixedColumns.defaults, init );
}
// v1.10 allows the settings object to be got form a number of sources
var dtSettings = $.fn.dataTable.Api ?
new $.fn.dataTable.Api( dt ).settings()[0] :
dt.fnSettings();
/**
* Settings object which contains customisable information for FixedColumns instance
* @namespace
* @extends FixedColumns.defaults
* @private
*/
this.s = {
/**
* DataTables settings objects
* @type object
* @default Obtained from DataTables instance
*/
"dt": dtSettings,
/**
* Number of columns in the DataTable - stored for quick access
* @type int
* @default Obtained from DataTables instance
*/
"iTableColumns": dtSettings.aoColumns.length,
/**
* Original outer widths of the columns as rendered by DataTables - used to calculate
* the FixedColumns grid bounding box
* @type array.<int>
* @default []
*/
"aiOuterWidths": [],
/**
* Original inner widths of the columns as rendered by DataTables - used to apply widths
* to the columns
* @type array.<int>
* @default []
*/
"aiInnerWidths": []
};
/**
* DOM elements used by the class instance
* @namespace
* @private
*
*/
this.dom = {
/**
* DataTables scrolling element
* @type node
* @default null
*/
"scroller": null,
/**
* DataTables header table
* @type node
* @default null
*/
"header": null,
/**
* DataTables body table
* @type node
* @default null
*/
"body": null,
/**
* DataTables footer table
* @type node
* @default null
*/
"footer": null,
/**
* Display grid elements
* @namespace
*/
"grid": {
/**
* Grid wrapper. This is the container element for the 3x3 grid
* @type node
* @default null
*/
"wrapper": null,
/**
* DataTables scrolling element. This element is the DataTables
* component in the display grid (making up the main table - i.e.
* not the fixed columns).
* @type node
* @default null
*/
"dt": null,
/**
* Left fixed column grid components
* @namespace
*/
"left": {
"wrapper": null,
"head": null,
"body": null,
"foot": null
},
/**
* Right fixed column grid components
* @namespace
*/
"right": {
"wrapper": null,
"head": null,
"body": null,
"foot": null
}
},
/**
* Cloned table nodes
* @namespace
*/
"clone": {
/**
* Left column cloned table nodes
* @namespace
*/
"left": {
/**
* Cloned header table
* @type node
* @default null
*/
"header": null,
/**
* Cloned body table
* @type node
* @default null
*/
"body": null,
/**
* Cloned footer table
* @type node
* @default null
*/
"footer": null
},
/**
* Right column cloned table nodes
* @namespace
*/
"right": {
/**
* Cloned header table
* @type node
* @default null
*/
"header": null,
/**
* Cloned body table
* @type node
* @default null
*/
"body": null,
/**
* Cloned footer table
* @type node
* @default null
*/
"footer": null
}
}
};
/* Attach the instance to the DataTables instance so it can be accessed easily */
dtSettings._oFixedColumns = this;
/* Let's do it */
if ( ! dtSettings._bInitComplete )
{
dtSettings.oApi._fnCallbackReg( dtSettings, 'aoInitComplete', function () {
that._fnConstruct( init );
}, 'FixedColumns' );
}
else
{
this._fnConstruct( init );
}
}
|
When making use of DataTables' x-axis scrolling feature, you may wish to
fix the left most column in place. This plug-in for DataTables provides
exactly this option (note for non-scrolling tables, please use the
FixedHeader plug-in, which can fix headers, footers and columns). Key
features include:
* Freezes the left or right most columns to the side of the table
* Option to freeze two or more columns
* Full integration with DataTables' scrolling options
* Speed - FixedColumns is fast in its operation
@class
@constructor
@global
@param {object} dt DataTables instance. With DataTables 1.10 this can also
be a jQuery collection, a jQuery selector, DataTables API instance or
settings object.
@param {object} [init={}] Configuration object for FixedColumns. Options are
defined by {@link FixedColumns.defaults}
@requires jQuery 1.7+
@requires DataTables 1.8.0+
@example
var table = $('#example').dataTable( {
"scrollX": "100%"
} );
new $.fn.dataTable.fixedColumns( table );
|
FixedColumns
|
javascript
|
stitchfix/pyxley
|
examples/datatables/project/static/dataTables.fixedColumns.js
|
https://github.com/stitchfix/pyxley/blob/master/examples/datatables/project/static/dataTables.fixedColumns.js
|
MIT
|
scrollbarAdjust = function ( node, width ) {
if ( ! oOverflow.bar ) {
// If there is no scrollbar (Macs) we need to hide the auto scrollbar
node.style.width = (width+20)+"px";
node.style.paddingRight = "20px";
node.style.boxSizing = "border-box";
}
else {
// Otherwise just overflow by the scrollbar
node.style.width = (width+oOverflow.bar)+"px";
}
}
|
Style and position the grid used for the FixedColumns layout
@returns {void}
@private
|
scrollbarAdjust
|
javascript
|
stitchfix/pyxley
|
examples/datatables/project/static/dataTables.fixedColumns.js
|
https://github.com/stitchfix/pyxley/blob/master/examples/datatables/project/static/dataTables.fixedColumns.js
|
MIT
|
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
|
PooledClass representing the bookkeeping associated with performing a child
traversal. Allows avoiding binding callbacks.
@constructor ForEachBookKeeping
@param {!function} forEachFunction Function to perform traversal with.
@param {?*} forEachContext Context to perform context with.
|
ForEachBookKeeping
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
|
Iterates through children that are typically specified as `props.children`.
See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
|
PooledClass representing the bookkeeping associated with performing a child
mapping. Allows avoiding binding callbacks.
@constructor MapBookKeeping
@param {!*} mapResult Object containing the ordered map of results.
@param {!function} mapFunction Function to perform mapping with.
@param {?*} mapContext Context to perform mapping with.
|
MapBookKeeping
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
|
Maps children that are typically specified as `props.children`.
See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
The provided mapFunction(child, key, 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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
|
Count the number of children that are typically specified as
`props.children`.
See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
@param {?*} children Children tree container.
@return {number} The number of children.
|
countChildren
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
|
Flatten a children object (typically specified as `props.children`) and
return an array with appropriately re-keyed children.
See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
|
toArray
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
}
|
Static poolers. Several custom versions for each potential number of
arguments. A completely generic pooler is easy to implement, but would
require accessing the `arguments` object. In each of these, `this` refers to
the Class itself, not an instance. If any others are needed, simply add them
here, or in their own files.
|
oneArgumentPooler
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
addPoolingTo = function (CopyConstructor, pooler) {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
}
|
Augments `CopyConstructor` to be a poolable class, augmenting only the class
itself (statically) not adding any prototypical fields. Any CopyConstructor
you give this may have a `poolSize` property, and will look for a
prototypical `destructor` on instances.
@param {Function} CopyConstructor Constructor that can be used to reset.
@param {Function} pooler Customizable pooler.
|
addPoolingTo
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
|
WARNING: DO NOT manually require this module.
This is a replacement for `invariant(...)` used by the error code system
and will _only_ be required by the corresponding babel pass.
It always throws.
|
reactProdInvariant
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
|
Use invariant() to assert state which your program assumes to be true.
Provide sprintf-style format (only %s is supported) and arguments
to provide information about what broke and what you were
expecting.
The invariant message will be stripped in production, but the invariant
will remain to ensure logic does not differ in production.
|
invariant
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if (process.env.NODE_ENV !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
}
|
Factory method to create a new React element. This no longer adheres to
the class pattern, so do not use new to call it. Also, no instanceof check
will work. Instead test $$typeof field against Symbol.for('react.element') to check
if something is a React Element.
@param {*} type
@param {*} key
@param {string|object} ref
@param {*} self A *temporary* helper to detect places where `this` is
different from the `owner` when React.createElement is called, so that we
can warn. We want to get rid of owner and replace string `ref`s with arrow
functions, and as long as `this` and owner are the same, there will be no
change in behavior.
@param {*} source An annotation object (added by a transpiler or otherwise)
indicating filename, line number, and/or other information.
@param {*} owner
@param {*} props
@internal
|
ReactElement
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
|
Similar to invariant but only logs a warning if the condition is not met.
This can be used to log issues in development environments in critical
paths. Removing the logging code for production environments will keep the
same logic and follow the same code paths.
|
printWarning
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
|
Generate a key string that identifies a component within a set.
@param {*} component A component that could contain a manual key.
@param {number} index Index that is used if a manual key is not provided.
@return {string}
|
getComponentKey
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' ||
// The following is inlined from ReactElement. This means we can optimize
// some checks. React Fiber also inlines this logic for similar purposes.
type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if (process.env.NODE_ENV !== 'production') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
return subtreeCount;
}
|
@param {?*} children Children tree container.
@param {!string} nameSoFar Name of the key path so far.
@param {!function} callback Callback to invoke with each child found.
@param {?*} traverseContext Used to pass information throughout the traversal
process.
@return {!number} The number of children in this subtree.
|
traverseAllChildrenImpl
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
|
Traverses children that are typically specified as `props.children`, but
might also be specified through attributes:
- `traverseAllChildren(this.props.children, ...)`
- `traverseAllChildren(this.props.leftPanelChildren, ...)`
The `traverseContext` is an optional argument that is passed through the
entire traversal. It can be used to store accumulations or anything else that
the callback might find relevant.
@param {?*} children Children tree object.
@param {!function} callback To invoke upon traversing each child.
@param {?*} traverseContext Context for traversal.
@return {!number} The number of children in this subtree.
|
traverseAllChildren
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
|
Returns the iterator method function contained on the iterable object.
Be sure to invoke the function with the iterable as context:
var iteratorFn = getIteratorFn(myIterable);
if (iteratorFn) {
var iterator = iteratorFn.call(myIterable);
...
}
@param {?object} maybeIterable
@return {?function}
|
getIteratorFn
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function unescape(key) {
var unescapeRegex = /(=0|=2)/g;
var unescaperLookup = {
'=0': '=',
'=2': ':'
};
var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
return ('' + keySubstring).replace(unescapeRegex, function (match) {
return unescaperLookup[match];
});
}
|
Unescape and unwrap key for human-readable display
@param {string} key to unescape.
@return {string} the unescaped key.
|
unescape
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
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.
|
ReactComponent
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0;
return undefined;
}
});
}
}
|
Deprecated APIs. These APIs used to exist on classic React classes but since
we would like to deprecate them, we're not going to move them over to this
modern base class. Instead, we define a getter that warns if it's accessed.
|
defineDeprecationWarning
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but only in __DEV__
process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0;
}
}
}
|
Special case getDefaultProps which should move into statics but requires
automatic merging.
|
validateTypeDef
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
}
return;
}
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0;
!!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0;
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
|
Mixin helper which handles policy validation and reserved
specification keys when building React classes.
|
mixSpecIntoComponent
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0;
one[key] = two[key];
}
}
return one;
}
|
Merge two objects, but throw if both contain the same key.
@param {object} one The first object, which is mutated.
@param {object} two The second object
@return {object} one after it has been mutated to contain everything in two.
|
mergeIntoWithNoDuplicateKeys
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
|
Creates a function that invokes two functions and merges their return values.
@param {function} one Function to invoke first.
@param {function} two Function to invoke second.
@return {function} Function that invokes the two argument functions.
@private
|
createMergedResultFunction
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
|
Creates a function that invokes two functions and ignores their return vales.
@param {function} one Function to invoke first.
@param {function} two Function to invoke second.
@return {function} Function that invokes the two argument functions.
@private
|
createChainedFunction
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0;
} else if (!args.length) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
|
Binds a method to the component.
@param {object} component Component whose method is going to be bound.
@param {function} method Method to be bound.
@return {function} The bound method.
|
bindAutoBindMethod
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
|
Binds all auto-bound methods in a component.
@param {object} component Component whose method is going to be bound.
|
bindAutoBindMethods
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
|
ReactElementValidator provides a wrapper around a element factory
which validates the props passed to the element. This is intended to be
used only in DEV and could be replaced by a static type checker for languages
that support it.
|
getDeclarationErrorAddendum
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = ' Check the top-level render call using <' + parentName + '>.';
}
}
return info;
}
|
Warn if there's no key explicitly set on dynamic arrays of children or
object keys are not valid. This allows us to keep track of children between
updates.
|
getCurrentComponentErrorInfo
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (memoizer[currentComponentErrorInfo]) {
return;
}
memoizer[currentComponentErrorInfo] = true;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0;
}
|
Warn if the element doesn't have an explicit key assigned to it.
This element is in an array. The array could grow and shrink or be
reordered. All children that haven't already been validated are required to
have a "key" property assigned to it. Error statuses are cached so a warning
will only be shown once.
@internal
@param {ReactElement} element Element that requires a key.
@param {*} parentType element's parent's type.
|
validateExplicitKey
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null);
}
if (typeof componentClass.getDefaultProps === 'function') {
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
}
}
|
Given an element, validate that its props follow the propTypes definition,
provided by the type.
@param {ReactElement} element
|
validatePropTypes
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var componentStackInfo = '';
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = __webpack_require__(28);
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
}
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
|
Assert that the values match with the type specs.
Error messages are memorized and will only be shown once.
@param {object} typeSpecs Map of name to a ReactPropType
@param {object} values Runtime values that need to be type-checked
@param {string} location e.g. "prop", "context", "child context"
@param {string} componentName Name of the component for error messages.
@param {?object} element The React element that is being type-checked
@param {?number} debugID The React component instance that is being type-checked
@private
|
checkReactTypeSpec
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
|
We use an Error-like object for backward compatibility as people may call
PropTypes directly and inspect their output. However we don't use real
Errors anymore. We don't inspect their stack anyway, and creating them
is prohibitively expensive if they are created too often, such as what
happens in oneOfType() for any type before the one that matched.
|
PropTypeError
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function onlyChild(children) {
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0;
return children;
}
|
Returns the first child in a collection of children and verifies that there
is only one child in the collection.
See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function shouldPrecacheNode(node, nodeID) {
return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' ';
}
|
Check if a given node should be cached.
|
shouldPrecacheNode
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getRenderedHostOrTextFromComponent(component) {
var rendered;
while (rendered = component._renderedComponent) {
component = rendered;
}
return component;
}
|
Drill down (through composites and empty components) until we get a host or
host text component.
This is pretty polymorphic but unavoidable with the current structure we have
for `_renderedChildren`.
|
getRenderedHostOrTextFromComponent
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function precacheNode(inst, node) {
var hostInst = getRenderedHostOrTextFromComponent(inst);
hostInst._hostNode = node;
node[internalInstanceKey] = hostInst;
}
|
Populate `_hostNode` on the rendered host/text component with the given
DOM node. The passed `inst` can be a composite.
|
precacheNode
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function precacheChildNodes(inst, node) {
if (inst._flags & Flags.hasCachedChildNodes) {
return;
}
var children = inst._renderedChildren;
var childNode = node.firstChild;
outer: for (var name in children) {
if (!children.hasOwnProperty(name)) {
continue;
}
var childInst = children[name];
var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
if (childID === 0) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
}
// We assume the child nodes are in the same order as the child instances.
for (; childNode !== null; childNode = childNode.nextSibling) {
if (shouldPrecacheNode(childNode, childID)) {
precacheNode(childInst, childNode);
continue outer;
}
}
// We reached the end of the DOM children without finding an ID match.
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0;
}
inst._flags |= Flags.hasCachedChildNodes;
}
|
Populate `_hostNode` on each child of `inst`, assuming that the children
match up with the DOM (element) children of `node`.
We cache entire levels at once to avoid an n^2 problem where we access the
children of a node sequentially and have to walk from the start to our target
node every time.
Since we update `_renderedChildren` and the actual DOM at (slightly)
different times, we could race here and see a newer `_renderedChildren` than
the DOM nodes we see. To avoid this, ReactMultiChild calls
`prepareToManageChildren` before we change `_renderedChildren`, at which
time the container's child nodes are always cached (until it unmounts).
|
precacheChildNodes
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) {
return node[internalInstanceKey];
}
// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = [];
while (!node[internalInstanceKey]) {
parents.push(node);
if (node.parentNode) {
node = node.parentNode;
} else {
// Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
}
}
var closest;
var inst;
for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
closest = inst;
if (parents.length) {
precacheChildNodes(inst, node);
}
}
return closest;
}
|
Given a DOM node, return the closest ReactDOMComponent or
ReactDOMTextComponent instance ancestor.
|
getClosestInstanceFromNode
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
if (inst != null && inst._hostNode === node) {
return inst;
} else {
return null;
}
}
|
Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
instance, or null if the node was not rendered by this React.
|
getInstanceFromNode
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
!(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
if (inst._hostNode) {
return inst._hostNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
while (!inst._hostNode) {
parents.push(inst);
!inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0;
inst = inst._hostParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
precacheChildNodes(inst, inst._hostNode);
}
return inst._hostNode;
}
|
Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
DOM node.
|
getNodeFromInstance
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
|
Opera <= 12 includes TextEvent in window, but does not fire
text input events. Rely on keypress instead.
|
isPresto
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case 'topCompositionStart':
return eventTypes.compositionStart;
case 'topCompositionEnd':
return eventTypes.compositionEnd;
case 'topCompositionUpdate':
return eventTypes.compositionUpdate;
}
}
|
Translate native top level events into event types.
@param {string} topLevelType
@return {object}
|
getCompositionEventType
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE;
}
|
Does our fallback best-guess model think this event signifies that
composition has begun?
@param {string} topLevelType
@param {object} nativeEvent
@return {boolean}
|
isFallbackCompositionStart
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case 'topKeyUp':
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case 'topKeyDown':
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case 'topKeyPress':
case 'topMouseDown':
case 'topBlur':
// 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?
@param {string} topLevelType
@param {object} nativeEvent
@return {boolean}
|
isFallbackCompositionEnd
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.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
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case 'topCompositionEnd':
return getDataFromCustomEvent(nativeEvent);
case 'topKeyPress':
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case 'topTextInput':
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
|
@param {string} topLevelType Record from `EventConstants`.
@param {object} nativeEvent Native browser event.
@return {?string} The string corresponding to this `beforeInput` event.
|
getNativeBeforeInputChars
|
javascript
|
stitchfix/pyxley
|
tests/app/static/bundle.js
|
https://github.com/stitchfix/pyxley/blob/master/tests/app/static/bundle.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.