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 |
|---|---|---|---|---|---|---|---|
function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) {
if (ReactDOMFeatureFlags.useCreateElement) {
context = assign({}, context);
if (container.nodeType === DOC_NODE_TYPE) {
context[ownerDocumentContextKey] = container;
} else {
context[ownerDocumentContextKey] = container.ownerDocument;
}
}
if ("development" !== 'production') {
if (context === emptyObject) {
context = {};
}
var tag = container.nodeName.toLowerCase();
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null);
}
var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context);
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction);
}
|
Mounts this component and inserts it into the DOM.
@param {ReactComponent} componentInstance The instance to mount.
@param {string} rootID DOM ID of the root node.
@param {DOMElement} container DOM element to mount into.
@param {ReactReconcileTransaction} transaction
@param {boolean} shouldReuseMarkup If true, do not insert markup
|
mountComponentIntoNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* forceHTML */shouldReuseMarkup);
transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
|
Batched mount.
@param {ReactComponent} componentInstance The instance to mount.
@param {string} rootID DOM ID of the root node.
@param {DOMElement} container DOM element to mount into.
@param {boolean} shouldReuseMarkup If true, do not insert markup
|
batchedMountComponentIntoNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function findFirstReactDOMImpl(node) {
// This node might be from another React instance, so we make sure not to
// examine the node cache here
for (; node && node.parentNode !== node; node = node.parentNode) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
continue;
}
var nodeID = internalGetID(node);
if (!nodeID) {
continue;
}
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
// If containersByReactRootID contains the container we find by crawling up
// the tree, we know that this instance of React rendered the node.
// nb. isValid's strategy (with containsNode) does not work because render
// trees may be nested and we don't want a false positive in that case.
var current = node;
var lastID;
do {
lastID = internalGetID(current);
current = current.parentNode;
if (current == null) {
// The passed-in node has been detached from the container it was
// originally rendered into.
return null;
}
} while (lastID !== reactRootID);
if (current === containersByReactRootID[reactRootID]) {
return node;
}
}
return null;
}
|
Returns the first (deepest) ancestor of a node which is rendered by this copy
of React.
|
findFirstReactDOMImpl
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function enqueueInsertMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
content: null,
fromIndex: null,
toIndex: toIndex
});
}
|
Enqueues markup to be rendered and inserted at a supplied index.
@param {string} parentID ID of the parent component.
@param {string} markup Markup that renders into an element.
@param {number} toIndex Destination index.
@private
|
enqueueInsertMarkup
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
|
Enqueues moving an existing element to another index.
@param {string} parentID ID of the parent component.
@param {number} fromIndex Source index of the existing element.
@param {number} toIndex Destination index of the element.
@private
|
enqueueMove
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: null
});
}
|
Enqueues removing an element at an index.
@param {string} parentID ID of the parent component.
@param {number} fromIndex Index of the element to remove.
@private
|
enqueueRemove
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function enqueueSetMarkup(parentID, markup) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.SET_MARKUP,
markupIndex: null,
content: markup,
fromIndex: null,
toIndex: null
});
}
|
Enqueues setting the markup of a node.
@param {string} parentID ID of the parent component.
@param {string} markup Markup that renders into an element.
@private
|
enqueueSetMarkup
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
content: textContent,
fromIndex: null,
toIndex: null
});
}
|
Enqueues setting the text content.
@param {string} parentID ID of the parent component.
@param {string} textContent Text content to set.
@private
|
enqueueTextContent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
|
Get a composite component wrapper class for a specific tag.
@param {ReactElement} element The tag for which to get the class.
@return {function} The React class constructor function.
|
getComponentClassForElement
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function createInternalComponent(element) {
!genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
return new genericComponentClass(element.type, element.props);
}
|
Get a native internal component class for a specific tag.
@param {ReactElement} element The element to create.
@return {function} The internal class constructor function.
|
createInternalComponent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
wrapper = function () {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
}
|
Use this to wrap methods you want to measure. Zero overhead in production.
@param {string} objName
@param {string} fnName
@param {function} func
@return {function}
|
wrapper
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function _noMeasure(objName, fnName, func) {
return func;
}
|
Simply passes through the measured function, without measuring it.
@param {string} objName
@param {string} fnName
@param {function} func
@return {function}
|
_noMeasure
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
|
Collection of methods that allow declaration and validation of props that are
supplied to React components. Example usage:
var Props = require('ReactPropTypes');
var MyArticle = React.createClass({
propTypes: {
// An optional string prop named "description".
description: Props.string,
// A required enum prop named "category".
category: Props.oneOf(['News','Photos']).isRequired,
// A prop named "dialog" that requires an instance of Dialog.
dialog: Props.instanceOf(Dialog).isRequired
},
render: function() { ... }
});
A more formal specification of how these methods are used:
type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
decl := ReactPropTypes.{type}(.isRequired)?
Each and every declaration produces a function with the same signature. This
allows the creation of custom validation functions. For example:
var MyLink = React.createClass({
propTypes: {
// An optional string or URI prop named "href".
href: function(props, propName, componentName) {
var propValue = props[propName];
if (propValue != null && typeof propValue !== 'string' &&
!(propValue instanceof URI)) {
return new Error(
'Expected a string or an URI for ' + propName + ' in ' +
componentName
);
}
}
},
render: function() {...}
});
@internal
|
createChainableTypeChecker
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function renderToString(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
var markup = componentInstance.mountComponent(id, transaction, emptyObject);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
|
@param {ReactElement} element
@return {string} the HTML markup
|
renderToString
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function renderToStaticMarkup(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, emptyObject);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
|
@param {ReactElement} element
@return {string} the HTML markup, without the extra React ID and checksum
(for generating static pages)
|
renderToStaticMarkup
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
|
Synthetic events are dispatched by event plugins, typically in response to a
top-level event delegation handler.
These systems should generally use pooling to reduce the frequency of garbage
collection. The system should check `isPersistent` to determine whether the
event should be released into the pool after being dispatched. Users that
need a persisted event should invoke `persist`.
Synthetic events (and subclasses) implement the DOM Level 3 Events API by
normalizing browser quirks. Subclasses do not necessarily have to implement a
DOM interface; custom application-specific events can also subclass this.
@param {object} dispatchConfig Configuration used to dispatch this event.
@param {string} dispatchMarker Marker identifying the event target.
@param {object} nativeEvent Native browser event.
|
SyntheticEvent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
|
Convert a value into the proper css writable value. The style name `name`
should be logical (no hyphens), as specified
in `CSSProperty.isUnitlessNumber`.
@param {string} name CSS property name such as `topMargin`.
@param {*} value CSS property value such as `10px`.
@return {string} Normalized style value with dimensions applied.
|
dangerousStyleValue
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function deprecated(fnName, newModule, newPackage, ctx, fn) {
var warned = false;
if ("development" !== 'production') {
var newFn = function () {
"development" !== 'production' ? warning(warned,
// Require examples in this string must be split to prevent React's
// build tools from mistaking them for real requires.
// Otherwise the build tools will attempt to build a '%s' module.
'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined;
warned = true;
return fn.apply(ctx, arguments);
};
// We need to make sure all properties of the original fn are copied over.
// In particular, this is needed to support PropTypes
return assign(newFn, fn);
}
return fn;
}
|
This will log a single deprecation notice per function and forward the call
on to the new API.
@param {string} fnName The name of the function
@param {string} newModule The module that fn will exist in
@param {string} newPackage The module that fn will exist in
@param {*} ctx The context this forwarded call should run in
@param {function} fn The function to forward on to
@return {function} The function that will warn once and then call fn
|
deprecated
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function findDOMNode(componentOrElement) {
if ("development" !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
"development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
if (ReactInstanceMap.has(componentOrElement)) {
return ReactMount.getNodeFromInstance(componentOrElement);
}
!(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
!false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
}
|
Returns the DOM node rendered by this element.
@param {ReactComponent|DOMElement} componentOrElement
@return {?DOMElement} The root node of this element.
|
findDOMNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = result[name] === undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (keyUnique && child != null) {
result[name] = child;
}
}
|
@param {function} traverseContext Context passed through traversal.
@param {?ReactComponent} child React child component.
@param {!string} name String name of key path to child.
|
flattenSingleChildIntoContext
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function instantiateReactComponent(node) {
var instance;
if (node === null || node === false) {
instance = new ReactEmptyComponent(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper();
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
!false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
}
// Sets up the instance. This can probably just move into the constructor now.
instance.construct(node);
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if ("development" !== 'production') {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if ("development" !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
|
Given a ReactNode, create an instance that will actually be mounted.
@param {ReactNode} node
@return {object} A new instance of the element's constructor.
@protected
|
instantiateReactComponent
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function onlyChild(children) {
!ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
return children;
}
|
Returns the first child in a collection of children and verifies that there
is only one child in the collection. The current implementation of this
function assumes that a single child gets passed without a wrapper, but the
purpose of this helper function is to abstract away the particular structure
of children.
@param {?object} children Child collection structure.
@return {ReactComponent} The first and only `ReactComponent` contained in the
structure.
|
onlyChild
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
setInnerHTML = function (node, html) {
node.innerHTML = html;
}
|
Set the innerHTML property of a node, ensuring that whitespace is preserved
even in IE8.
@param {DOMElement} node
@param {string} html
@internal
|
setInnerHTML
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
|
TODO: Test that a single child and an array with one item have the same key
pattern.
|
userProvidedKeyEscaper
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
}
|
Escape a component key so that it is safe to use in a reactid.
@param {*} text Component key to be escaped.
@return {string} An escaped string.
|
escapeUserProvidedKey
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
|
Wrap a `key` value explicitly provided by the user to distinguish it from
implicitly-generated keys generated by a component's index in its parent.
@param {string} key Value of a user-provided `key` attribute
@return {string}
|
wrapUserProvidedKey
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function containsNode(_x, _x2) {
var _again = true;
_function: while (_again) {
var outerNode = _x,
innerNode = _x2;
_again = false;
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
_x = outerNode;
_x2 = innerNode.parentNode;
_again = true;
continue _function;
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
}
|
Checks if a given DOM node contains or is another DOM node.
@param {?DOMNode} outerNode Outer DOM node.
@param {?DOMNode} innerNode Inner DOM node.
@return {boolean} True if `outerNode` contains or is `innerNode`.
|
containsNode
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
}
|
Constructs an enumeration with keys equal to their value.
For example:
var COLORS = keyMirror({blue: null, red: null});
var myColor = COLORS.blue;
var isColorValid = !!COLORS[myColor];
The last line could not be performed if the values of the generated enum were
not equal to their keys.
Input: {key1: val1, key2: val2}
Output: {key1: key1, key2: key2}
@param {object} obj
@return {object}
|
keyMirror
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
}
|
Allows extraction of a minified key. Let's the build system minify keys
without losing the ability to dynamically use key strings as values
themselves. Pass in an object with a single key/val pair and it will return
you the string key of that single record. Suppose you want to grab the
value for a key 'className' inside of an object. Key/val minification may
have aliased that key to be 'xa12'. keyOf({className: null}) will return
'xa12' in that case. Resolve keys you want to use once at startup time, then
reuse those resolutions.
|
keyOf
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
|
Executes the provided `callback` once for each enumerable own property in the
object and constructs a new object from the results. The `callback` is
invoked with three arguments:
- the property value
- the property name
- the object being traversed
Properties that are added after the call to `mapObject` will not be visited
by `callback`. If the values of existing properties are changed, the value
passed to `callback` will be the value at the time `mapObject` visits them.
Properties that are deleted before being visited are not visited.
@grep function objectMap()
@grep function objMap()
@param {?object} object
@param {function} callback
@param {*} context
@return {?object}
|
mapObject
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
|
Memoizes the return value of a function that accepts one string argument.
@param {function} callback
@return {function}
|
memoizeStringOnly
|
javascript
|
amol-/dukpy
|
dukpy/jsmodules/react/react.js
|
https://github.com/amol-/dukpy/blob/master/dukpy/jsmodules/react/react.js
|
MIT
|
function GithubView(name, options){
this.name = name;
options = options || {};
this.engine = options.engines[extname(name)];
// "root" is the app.set('views') setting, however
// in your own implementation you could ignore this
this.path = '/' + options.root + '/master/' + name;
}
|
Custom view that fetches and renders
remove github templates. You could
render templates from a database etc.
|
GithubView
|
javascript
|
expressjs/express
|
examples/view-constructor/github-view.js
|
https://github.com/expressjs/express/blob/master/examples/view-constructor/github-view.js
|
MIT
|
function logerror(err) {
/* istanbul ignore next */
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
|
Log error using console.error.
@param {Error} err
@private
|
logerror
|
javascript
|
expressjs/express
|
lib/application.js
|
https://github.com/expressjs/express/blob/master/lib/application.js
|
MIT
|
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
|
Create an express application.
@return {Function}
@api public
|
createApplication
|
javascript
|
expressjs/express
|
lib/express.js
|
https://github.com/expressjs/express/blob/master/lib/express.js
|
MIT
|
function defineGetter(obj, name, getter) {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get: getter
});
}
|
Helper function for creating a getter on an object.
@param {Object} obj
@param {String} name
@param {Function} getter
@private
|
defineGetter
|
javascript
|
expressjs/express
|
lib/request.js
|
https://github.com/expressjs/express/blob/master/lib/request.js
|
MIT
|
function sendfile(res, file, options, callback) {
var done = false;
var streaming;
// request aborted
function onaborted() {
if (done) return;
done = true;
var err = new Error('Request aborted');
err.code = 'ECONNABORTED';
callback(err);
}
// directory
function ondirectory() {
if (done) return;
done = true;
var err = new Error('EISDIR, read');
err.code = 'EISDIR';
callback(err);
}
// errors
function onerror(err) {
if (done) return;
done = true;
callback(err);
}
// ended
function onend() {
if (done) return;
done = true;
callback();
}
// file
function onfile() {
streaming = false;
}
// finished
function onfinish(err) {
if (err && err.code === 'ECONNRESET') return onaborted();
if (err) return onerror(err);
if (done) return;
setImmediate(function () {
if (streaming !== false && !done) {
onaborted();
return;
}
if (done) return;
done = true;
callback();
});
}
// streaming
function onstream() {
streaming = true;
}
file.on('directory', ondirectory);
file.on('end', onend);
file.on('error', onerror);
file.on('file', onfile);
file.on('stream', onstream);
onFinished(res, onfinish);
if (options.headers) {
// set headers on successful transfer
file.on('headers', function headers(res) {
var obj = options.headers;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
res.setHeader(k, obj[k]);
}
});
}
// pipe
file.pipe(res);
}
|
Render `view` with the given `options` and optional callback `fn`.
When a callback function is given a response will _not_ be made
automatically, otherwise a response of _200_ and _text/html_ is given.
Options:
- `cache` boolean hinting to the engine it should cache
- `filename` filename of the view being rendered
@public
|
sendfile
|
javascript
|
expressjs/express
|
lib/response.js
|
https://github.com/expressjs/express/blob/master/lib/response.js
|
MIT
|
function stringify (value, replacer, spaces, escape) {
// v8 checks arguments.length for optimizing simple call
// https://bugs.chromium.org/p/v8/issues/detail?id=4730
var json = replacer || spaces
? JSON.stringify(value, replacer, spaces)
: JSON.stringify(value);
if (escape && typeof json === 'string') {
json = json.replace(/[<>&]/g, function (c) {
switch (c.charCodeAt(0)) {
case 0x3c:
return '\\u003c'
case 0x3e:
return '\\u003e'
case 0x26:
return '\\u0026'
/* istanbul ignore next: unreachable default */
default:
return c
}
})
}
return json
}
|
Stringify JSON, like JSON.stringify, but v8 optimized, with the
ability to escape characters that can trigger HTML sniffing.
@param {*} value
@param {function} replacer
@param {number} spaces
@param {boolean} escape
@returns {string}
@private
|
stringify
|
javascript
|
expressjs/express
|
lib/response.js
|
https://github.com/expressjs/express/blob/master/lib/response.js
|
MIT
|
function acceptParams (str) {
var length = str.length;
var colonIndex = str.indexOf(';');
var index = colonIndex === -1 ? length : colonIndex;
var ret = { value: str.slice(0, index).trim(), quality: 1, params: {} };
while (index < length) {
var splitIndex = str.indexOf('=', index);
if (splitIndex === -1) break;
var colonIndex = str.indexOf(';', index);
var endIndex = colonIndex === -1 ? length : colonIndex;
if (splitIndex > endIndex) {
index = str.lastIndexOf(';', splitIndex - 1) + 1;
continue;
}
var key = str.slice(index, splitIndex).trim();
var value = str.slice(splitIndex + 1, endIndex).trim();
if (key === 'q') {
ret.quality = parseFloat(value);
} else {
ret.params[key] = value;
}
index = endIndex + 1;
}
return ret;
}
|
Parse accept params `str` returning an
object with `.value`, `.quality` and `.params`.
@param {String} str
@return {Object}
@api private
|
acceptParams
|
javascript
|
expressjs/express
|
lib/utils.js
|
https://github.com/expressjs/express/blob/master/lib/utils.js
|
MIT
|
function createETagGenerator (options) {
return function generateETag (body, encoding) {
var buf = !Buffer.isBuffer(body)
? Buffer.from(body, encoding)
: body
return etag(buf, options)
}
}
|
Create an ETag generator function, generating ETags with
the given options.
@param {object} options
@return {function}
@private
|
createETagGenerator
|
javascript
|
expressjs/express
|
lib/utils.js
|
https://github.com/expressjs/express/blob/master/lib/utils.js
|
MIT
|
function parseExtendedQueryString(str) {
return qs.parse(str, {
allowPrototypes: true
});
}
|
Parse an extended query string with qs.
@param {String} str
@return {Object}
@private
|
parseExtendedQueryString
|
javascript
|
expressjs/express
|
lib/utils.js
|
https://github.com/expressjs/express/blob/master/lib/utils.js
|
MIT
|
function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
var fileName = name;
if (!this.ext) {
// get extension from default engine name
this.ext = this.defaultEngine[0] !== '.'
? '.' + this.defaultEngine
: this.defaultEngine;
fileName += this.ext;
}
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.slice(1)
debug('require "%s"', mod)
// default engine export
var fn = require(mod).__express
if (typeof fn !== 'function') {
throw new Error('Module "' + mod + '" does not provide a view engine.')
}
opts.engines[this.ext] = fn
}
// store loaded engine
this.engine = opts.engines[this.ext];
// lookup path
this.path = this.lookup(fileName);
}
|
Initialize a new `View` with the given `name`.
Options:
- `defaultEngine` the default template engine name
- `engines` template engine require() cache
- `root` root path for view lookup
@param {string} name
@param {object} options
@public
|
View
|
javascript
|
expressjs/express
|
lib/view.js
|
https://github.com/expressjs/express/blob/master/lib/view.js
|
MIT
|
function tryStat(path) {
debug('stat "%s"', path);
try {
return fs.statSync(path);
} catch (e) {
return undefined;
}
}
|
Return a stat, maybe.
@param {string} path
@return {fs.Stats}
@private
|
tryStat
|
javascript
|
expressjs/express
|
lib/view.js
|
https://github.com/expressjs/express/blob/master/lib/view.js
|
MIT
|
function getExpectedClientAddress(server) {
return server.address().address === '::'
? '::ffff:127.0.0.1'
: '127.0.0.1';
}
|
Get the local client address depending on AF_NET of server
|
getExpectedClientAddress
|
javascript
|
expressjs/express
|
test/req.ip.js
|
https://github.com/expressjs/express/blob/master/test/req.ip.js
|
MIT
|
function shouldHaveBody (buf) {
return function (res) {
var body = !Buffer.isBuffer(res.body)
? Buffer.from(res.text)
: res.body
assert.ok(body, 'response has body')
assert.strictEqual(body.toString('hex'), buf.toString('hex'))
}
}
|
Assert that a supertest response has a specific body.
@param {Buffer} buf
@returns {function}
|
shouldHaveBody
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldHaveHeader (header) {
return function (res) {
assert.ok((header.toLowerCase() in res.headers), 'should have header ' + header)
}
}
|
Assert that a supertest response does have a header.
@param {string} header Header name to check
@returns {function}
|
shouldHaveHeader
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldNotHaveBody () {
return function (res) {
assert.ok(res.text === '' || res.text === undefined)
}
}
|
Assert that a supertest response does not have a body.
@returns {function}
|
shouldNotHaveBody
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
function shouldNotHaveHeader(header) {
return function (res) {
assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header);
};
}
|
Assert that a supertest response does not have a header.
@param {string} header Header name to check
@returns {function}
|
shouldNotHaveHeader
|
javascript
|
expressjs/express
|
test/support/utils.js
|
https://github.com/expressjs/express/blob/master/test/support/utils.js
|
MIT
|
unlock = function(e) {
// Create a pool of unlocked HTML5 Audio objects that can
// be used for playing sounds without user interaction. HTML5
// Audio objects must be individually unlocked, as opposed
// to the WebAudio API which only needs a single activation.
// This must occur before WebAudio setup or the source.onended
// event will not fire.
while (self._html5AudioPool.length < self.html5PoolSize) {
try {
var audioNode = new Audio();
// Mark this Audio object as unlocked to ensure it can get returned
// to the unlocked pool when released.
audioNode._unlocked = true;
// Add the audio node to the pool.
self._releaseHtml5Audio(audioNode);
} catch (e) {
self.noAudio = true;
break;
}
}
// Loop through any assigned audio nodes and unlock them.
for (var i=0; i<self._howls.length; i++) {
if (!self._howls[i]._webAudio) {
// Get all of the sounds in this Howl group.
var ids = self._howls[i]._getSoundIds();
// Loop through all sounds and unlock the audio nodes.
for (var j=0; j<ids.length; j++) {
var sound = self._howls[i]._soundById(ids[j]);
if (sound && sound._node && !sound._node._unlocked) {
sound._node._unlocked = true;
sound._node.load();
}
}
}
}
// Fix Android can not play in suspend state.
self._autoResume();
// Create an empty buffer.
var source = self.ctx.createBufferSource();
source.buffer = self._scratchBuffer;
source.connect(self.ctx.destination);
// Play the empty buffer.
if (typeof source.start === 'undefined') {
source.noteOn(0);
} else {
source.start(0);
}
// Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55.
if (typeof self.ctx.resume === 'function') {
self.ctx.resume();
}
// Setup a timeout to check that we are unlocked on the next event loop.
source.onended = function() {
source.disconnect(0);
// Update the unlocked state and prevent this check from happening again.
self._audioUnlocked = true;
// Remove the touch start listener.
document.removeEventListener('touchstart', unlock, true);
document.removeEventListener('touchend', unlock, true);
document.removeEventListener('click', unlock, true);
document.removeEventListener('keydown', unlock, true);
// Let all sounds know that audio has been unlocked.
for (var i=0; i<self._howls.length; i++) {
self._howls[i]._emit('unlock');
}
};
}
|
Some browsers/devices will only allow audio to be played after a user interaction.
Attempt to automatically unlock audio on the first user interaction.
Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
@return {Howler}
|
unlock
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
handleSuspension = function() {
self.state = 'suspended';
if (self._resumeAfterSuspend) {
delete self._resumeAfterSuspend;
self._autoResume();
}
}
|
Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds.
This saves processing/energy and fixes various browser-specific bugs with audio getting stuck.
@return {Howler}
|
handleSuspension
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Howl = function(o) {
var self = this;
// Throw an error if no source is provided.
if (!o.src || o.src.length === 0) {
console.error('An array of source files must be passed with any new Howl.');
return;
}
self.init(o);
}
|
Create an audio group controller.
@param {Object} o Passed in properties for this group.
|
Howl
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setParams = function() {
sound._paused = false;
sound._seek = seek;
sound._start = start;
sound._stop = stop;
sound._loop = !!(sound._loop || self._sprite[sprite][2]);
}
|
Play a sound or resume previous playback.
@param {String/Number} sprite Sprite name for sprite playback or sound id to continue previous.
@param {Boolean} internal Internal Use: true prevents event firing.
@return {Number} Sound ID.
|
setParams
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
seekAndEmit = function() {
// Restart the playback if the sound was playing.
if (playing) {
self.play(id, true);
}
self._emit('seek', id);
}
|
Get/set the seek position of a sound. This method can optionally take 0, 1 or 2 arguments.
seek() -> Returns the first sound node's current seek position.
seek(id) -> Returns the sound id's current seek position.
seek(seek) -> Sets the seek position of the first sound node.
seek(seek, id) -> Sets the seek position of passed sound id.
@return {Howl/Number} Returns self or the current seek position.
|
seekAndEmit
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Sound = function(howl) {
this._parent = howl;
this.init();
}
|
Setup the sound object, which each node attached to a Howl group is contained in.
@param {Object} howl The Howl parent group.
|
Sound
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
loadBuffer = function(self) {
var url = self._src;
// Check if the buffer has already been cached and use it instead.
if (cache[url]) {
// Set the duration from the cache.
self._duration = cache[url].duration;
// Load the sound into this Howl.
loadSound(self);
return;
}
if (/^data:[^;]+;base64,/.test(url)) {
// Decode the base64 data URI without XHR, since some browsers don't support it.
var data = atob(url.split(',')[1]);
var dataView = new Uint8Array(data.length);
for (var i=0; i<data.length; ++i) {
dataView[i] = data.charCodeAt(i);
}
decodeAudioData(dataView.buffer, self);
} else {
// Load the buffer from the URL.
var xhr = new XMLHttpRequest();
xhr.open(self._xhr.method, url, true);
xhr.withCredentials = self._xhr.withCredentials;
xhr.responseType = 'arraybuffer';
// Apply any custom headers to the request.
if (self._xhr.headers) {
Object.keys(self._xhr.headers).forEach(function(key) {
xhr.setRequestHeader(key, self._xhr.headers[key]);
});
}
xhr.onload = function() {
// Make sure we get a successful response back.
var code = (xhr.status + '')[0];
if (code !== '0' && code !== '2' && code !== '3') {
self._emit('loaderror', null, 'Failed loading audio file with status: ' + xhr.status + '.');
return;
}
decodeAudioData(xhr.response, self);
};
xhr.onerror = function() {
// If there is an error, switch to HTML5 Audio.
if (self._webAudio) {
self._html5 = true;
self._webAudio = false;
self._sounds = [];
delete cache[url];
self.load();
}
};
safeXhrSend(xhr);
}
}
|
Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
@param {Howl} self
|
loadBuffer
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
safeXhrSend = function(xhr) {
try {
xhr.send();
} catch (e) {
xhr.onerror();
}
}
|
Send the XHR request wrapped in a try/catch.
@param {Object} xhr XHR to send.
|
safeXhrSend
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
decodeAudioData = function(arraybuffer, self) {
// Fire a load error if something broke.
var error = function() {
self._emit('loaderror', null, 'Decoding audio data failed.');
};
// Load the sound on success.
var success = function(buffer) {
if (buffer && self._sounds.length > 0) {
cache[self._src] = buffer;
loadSound(self, buffer);
} else {
error();
}
};
// Decode the buffer into an audio source.
if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
} else {
Howler.ctx.decodeAudioData(arraybuffer, success, error);
}
}
|
Decode audio data from an array buffer.
@param {ArrayBuffer} arraybuffer The audio data.
@param {Howl} self
|
decodeAudioData
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
loadSound = function(self, buffer) {
// Set the duration.
if (buffer && !self._duration) {
self._duration = buffer.duration;
}
// Setup a sprite if none is defined.
if (Object.keys(self._sprite).length === 0) {
self._sprite = {__default: [0, self._duration * 1000]};
}
// Fire the loaded event.
if (self._state !== 'loaded') {
self._state = 'loaded';
self._emit('load');
self._loadQueue();
}
}
|
Sound is now loaded, so finish setting everything up and fire the loaded event.
@param {Howl} self
@param {Object} buffer The decoded buffer sound source.
|
loadSound
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setupAudioContext = function() {
// If we have already detected that Web Audio isn't supported, don't run this step again.
if (!Howler.usingWebAudio) {
return;
}
// Check if we are using Web Audio and setup the AudioContext if we are.
try {
if (typeof AudioContext !== 'undefined') {
Howler.ctx = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
Howler.ctx = new webkitAudioContext();
} else {
Howler.usingWebAudio = false;
}
} catch(e) {
Howler.usingWebAudio = false;
}
// If the audio context creation still failed, set using web audio to false.
if (!Howler.ctx) {
Howler.usingWebAudio = false;
}
// Check if a webview is being used on iOS8 or earlier (rather than the browser).
// If it is, disable Web Audio as it causes crashing.
var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
var version = appVersion ? parseInt(appVersion[1], 10) : null;
if (iOS && version && version < 9) {
var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
if (Howler._navigator && !safari) {
Howler.usingWebAudio = false;
}
}
// Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
if (Howler.usingWebAudio) {
Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : Howler._volume, Howler.ctx.currentTime);
Howler.masterGain.connect(Howler.ctx.destination);
}
// Re-run the setup on Howler.
Howler._setup();
}
|
Setup the audio context when available, or switch to HTML5 Audio mode.
|
setupAudioContext
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
setupPanner = function(sound, type) {
type = type || 'spatial';
// Create the new panner node.
if (type === 'spatial') {
sound._panner = Howler.ctx.createPanner();
sound._panner.coneInnerAngle = sound._pannerAttr.coneInnerAngle;
sound._panner.coneOuterAngle = sound._pannerAttr.coneOuterAngle;
sound._panner.coneOuterGain = sound._pannerAttr.coneOuterGain;
sound._panner.distanceModel = sound._pannerAttr.distanceModel;
sound._panner.maxDistance = sound._pannerAttr.maxDistance;
sound._panner.refDistance = sound._pannerAttr.refDistance;
sound._panner.rolloffFactor = sound._pannerAttr.rolloffFactor;
sound._panner.panningModel = sound._pannerAttr.panningModel;
if (typeof sound._panner.positionX !== 'undefined') {
sound._panner.positionX.setValueAtTime(sound._pos[0], Howler.ctx.currentTime);
sound._panner.positionY.setValueAtTime(sound._pos[1], Howler.ctx.currentTime);
sound._panner.positionZ.setValueAtTime(sound._pos[2], Howler.ctx.currentTime);
} else {
sound._panner.setPosition(sound._pos[0], sound._pos[1], sound._pos[2]);
}
if (typeof sound._panner.orientationX !== 'undefined') {
sound._panner.orientationX.setValueAtTime(sound._orientation[0], Howler.ctx.currentTime);
sound._panner.orientationY.setValueAtTime(sound._orientation[1], Howler.ctx.currentTime);
sound._panner.orientationZ.setValueAtTime(sound._orientation[2], Howler.ctx.currentTime);
} else {
sound._panner.setOrientation(sound._orientation[0], sound._orientation[1], sound._orientation[2]);
}
} else {
sound._panner = Howler.ctx.createStereoPanner();
sound._panner.pan.setValueAtTime(sound._stereo, Howler.ctx.currentTime);
}
sound._panner.connect(sound._node);
// Update the connections.
if (!sound._paused) {
sound._parent.pause(sound._id, true).play(sound._id, true);
}
}
|
Create a new panner node and save it on the sound.
@param {Sound} sound Specific sound to setup panning on.
@param {String} type Type of panner to create: 'stereo' or 'spatial'.
|
setupPanner
|
javascript
|
goldfire/howler.js
|
dist/howler.js
|
https://github.com/goldfire/howler.js/blob/master/dist/howler.js
|
MIT
|
Camera = function(resolution) {
this.width = canvas.width = window.innerWidth;
this.height = canvas.height = window.innerHeight;
this.resolution = resolution;
this.spacing = this.width / resolution;
this.focalLen = this.height / this.width;
this.range = isMobile ? 9 : 18;
this.lightRange = 9;
this.scale = canvas.width / 1200;
}
|
Camera that draws everything you see on the screen from the player's perspective.
@param {Number} resolution Resolution to render at (higher has better quality, but lower performance).
|
Camera
|
javascript
|
goldfire/howler.js
|
examples/3d/js/camera.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/camera.js
|
MIT
|
Controls = function() {
// Define our control key codes and states.
this.codes = {
// Arrows
37: 'left', 39: 'right', 38: 'front', 40: 'back',
// WASD
65: 'left', 68: 'right', 87: 'front', 83: 'back',
};
this.states = {left: false, right: false, front: false, back: false};
// Setup the DOM listeners.
document.addEventListener('keydown', this.key.bind(this, true), false);
document.addEventListener('keyup', this.key.bind(this, false), false);
document.addEventListener('touchstart', this.touch.bind(this), false);
document.addEventListener('touchmove', this.touch.bind(this), false);
document.addEventListener('touchend', this.touchEnd.bind(this), false);
}
|
Defines and handles the various controls.
|
Controls
|
javascript
|
goldfire/howler.js
|
examples/3d/js/controls.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/controls.js
|
MIT
|
Game = function() {
this.lastTime = 0;
// Setup our different game components.
this.audio = new Sound();
this.player = new Player(10, 26, Math.PI * 1.9, 2.5);
this.controls = new Controls();
this.map = new Map(25);
this.camera = new Camera(isMobile ? 256 : 512);
requestAnimationFrame(this.tick.bind(this));
}
|
Main game class that runs the tick and sets up all other components.
|
Game
|
javascript
|
goldfire/howler.js
|
examples/3d/js/game.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/game.js
|
MIT
|
Map = function(size) {
this.size = size;
this.grid = new Array(size * size);
this.skybox = new Texture('./assets/skybox.jpg', 4096, 1024);
this.wall = new Texture('./assets/wall.jpg', 1024, 1024);
this.speaker = new Texture('./assets/speaker.jpg', 1024, 1024);
this.light = 0;
// Define the pre-defined map template on a 25x25 grid.
this.grid = [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1];
}
|
Generates the map and calculates the casting of arrays for the camera to display on screen.
@param {Number} size Grid size of the map to use.
|
Map
|
javascript
|
goldfire/howler.js
|
examples/3d/js/map.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/map.js
|
MIT
|
Player = function(x, y, dir, speed) {
this.x = x;
this.y = y;
this.dir = dir;
this.speed = speed || 3;
this.steps = 0;
this.hand = new Texture('./assets/gun.png', 512, 360);
// Update the position of the audio listener.
Howler.pos(this.x, this.y, -0.5);
// Update the direction and orientation.
this.rotate(dir);
}
|
The player from which we cast the rays.
@param {Number} x Starting x-position.
@param {Number} y Starting y-position.
@param {Number} dir Direction they are facing in radians.
@param {Number} speed Speed they walk at.
|
Player
|
javascript
|
goldfire/howler.js
|
examples/3d/js/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/player.js
|
MIT
|
Sound = function() {
// Setup the shared Howl.
this.sound = new Howl({
src: ['./assets/sprite.webm', './assets/sprite.mp3'],
sprite: {
lightning: [2000, 4147],
rain: [8000, 9962, true],
thunder: [19000, 13858],
music: [34000, 31994, true]
},
volume: 0
});
// Begin playing background sounds.
this.rain();
this.thunder();
}
|
Setup and control all of the game's audio.
|
Sound
|
javascript
|
goldfire/howler.js
|
examples/3d/js/sound.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/sound.js
|
MIT
|
Texture = function(src, w, h) {
this.image = new Image();
this.image.src = src;
this.width = w;
this.height = h;
}
|
Load a texture and store its details.
@param {String} src Image URL.
@param {Number} w Image width.
@param {Number} h Image height.
|
Texture
|
javascript
|
goldfire/howler.js
|
examples/3d/js/texture.js
|
https://github.com/goldfire/howler.js/blob/master/examples/3d/js/texture.js
|
MIT
|
Player = function(playlist) {
this.playlist = playlist;
this.index = 0;
// Display the title of the first track.
track.innerHTML = '1. ' + playlist[0].title;
// Setup the playlist display.
playlist.forEach(function(song) {
var div = document.createElement('div');
div.className = 'list-song';
div.innerHTML = song.title;
div.onclick = function() {
player.skipTo(playlist.indexOf(song));
};
list.appendChild(div);
});
}
|
Player class containing the state of our playlist and where we are in it.
Includes all methods for playing, skipping, updating the display, etc.
@param {Array} playlist Array of objects with playlist song details ({title, file, howl}).
|
Player
|
javascript
|
goldfire/howler.js
|
examples/player/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/player/player.js
|
MIT
|
move = function(event) {
if (window.sliderDown) {
var x = event.clientX || event.touches[0].clientX;
var startX = window.innerWidth * 0.05;
var layerX = x - startX;
var per = Math.min(1, Math.max(0, layerX / parseFloat(barEmpty.scrollWidth)));
player.volume(per);
}
}
|
Format the time from seconds to M:SS.
@param {Number} secs Seconds to format.
@return {String} Formatted time.
|
move
|
javascript
|
goldfire/howler.js
|
examples/player/player.js
|
https://github.com/goldfire/howler.js/blob/master/examples/player/player.js
|
MIT
|
Radio = function(stations) {
var self = this;
self.stations = stations;
self.index = 0;
// Setup the display for each station.
for (var i=0; i<self.stations.length; i++) {
window['title' + i].innerHTML = '<b>' + self.stations[i].freq + '</b> ' + self.stations[i].title;
window['station' + i].addEventListener('click', function(index) {
var isNotPlaying = (self.stations[index].howl && !self.stations[index].howl.playing());
// Stop other sounds or the current one.
radio.stop();
// If the station isn't already playing or it doesn't exist, play it.
if (isNotPlaying || !self.stations[index].howl) {
radio.play(index);
}
}.bind(self, i));
}
}
|
Radio class containing the state of our stations.
Includes all methods for playing, stopping, etc.
@param {Array} stations Array of objects with station details ({title, src, howl, ...}).
|
Radio
|
javascript
|
goldfire/howler.js
|
examples/radio/radio.js
|
https://github.com/goldfire/howler.js/blob/master/examples/radio/radio.js
|
MIT
|
Sprite = function(options) {
var self = this;
self.sounds = [];
// Setup the options to define this sprite display.
self._width = options.width;
self._left = options.left;
self._spriteMap = options.spriteMap;
self._sprite = options.sprite;
self.setupListeners();
// Create our audio sprite definition.
self.sound = new Howl({
src: options.src,
sprite: options.sprite
});
// Setup a resize event and fire it to setup our sprite overlays.
window.addEventListener('resize', function() {
self.resize();
}, false);
self.resize();
// Begin the progress step tick.
requestAnimationFrame(self.step.bind(self));
}
|
Sprite class containing the state of our sprites to play and their progress.
@param {Object} options Settings to pass into and setup the sound and visuals.
|
Sprite
|
javascript
|
goldfire/howler.js
|
examples/sprite/sprite.js
|
https://github.com/goldfire/howler.js/blob/master/examples/sprite/sprite.js
|
MIT
|
function innerState(cm, state) {
return CodeMirror.innerMode(cm.getMode(), state).state;
}
|
Array of tag names where an end tag is forbidden.
|
innerState
|
javascript
|
jbt/markdown-editor
|
codemirror/lib/util/closetag.js
|
https://github.com/jbt/markdown-editor/blob/master/codemirror/lib/util/closetag.js
|
ISC
|
function isWhitespace(s) {
return s === ' ' || s === '\t' || s === '\r' || s === '\n' || s === '';
}
|
NB!
The namedEmojiString variable is updated automatically by the
`update.sh` script. Do not remove the markers as this will
cause `update.sh` to stop working.
|
isWhitespace
|
javascript
|
jbt/markdown-editor
|
lib/emojify.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/emojify.js
|
ISC
|
function Renderer() {
/**
* Renderer#rules -> Object
*
* Contains render rules for tokens. Can be updated and extended.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')();
*
* md.renderer.rules.strong_open = function () { return '<b>'; };
* md.renderer.rules.strong_close = function () { return '</b>'; };
*
* var result = md.renderInline(...);
* ```
*
* Each rule is called as independed static function with fixed signature:
*
* ```javascript
* function my_token_render(tokens, idx, options, env, renderer) {
* // ...
* return renderedHTML;
* }
* ```
*
* See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js)
* for more details and examples.
**/
this.rules = assign({}, default_rules);
}
|
new Renderer()
Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults.
|
Renderer
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function isLetter(ch) {
/*eslint no-bitwise:0*/
var lc = ch | 0x20; // to lower case
return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);
}
|
Ruler.getRules(chainName) -> Array
Return array of active functions (rules) for given chain name. It analyzes
rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's
done intentionally, to keep signature monomorphic for high speed.
|
isLetter
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function Token(type, tag, nesting) {
/**
* Token#type -> String
*
* Type of the token (string, e.g. "paragraph_open")
**/
this.type = type;
/**
* Token#tag -> String
*
* html tag name, e.g. "p"
**/
this.tag = tag;
/**
* Token#attrs -> Array
*
* Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]`
**/
this.attrs = null;
/**
* Token#map -> Array
*
* Source map info. Format: `[ line_begin, line_end ]`
**/
this.map = null;
/**
* Token#nesting -> Number
*
* Level change (number in {-1, 0, 1} set), where:
*
* - `1` means the tag is opening
* - `0` means the tag is self-closing
* - `-1` means the tag is closing
**/
this.nesting = nesting;
/**
* Token#level -> Number
*
* nesting level, the same as `state.level`
**/
this.level = 0;
/**
* Token#children -> Array
*
* An array of child nodes (inline and img tokens)
**/
this.children = null;
/**
* Token#content -> String
*
* In a case of self-closing tag (code, html, fence, etc.),
* it has contents of this tag.
**/
this.content = '';
/**
* Token#markup -> String
*
* '*' or '_' for emphasis, fence string for fence, etc.
**/
this.markup = '';
/**
* Token#info -> String
*
* fence infostring
**/
this.info = '';
/**
* Token#meta -> Object
*
* A place for plugins to store an arbitrary data
**/
this.meta = null;
/**
* Token#block -> Boolean
*
* True for block-level tokens, false for inline tokens.
* Used in renderer to calculate line breaks
**/
this.block = false;
/**
* Token#hidden -> Boolean
*
* If it's true, ignore this element when rendering. Used for tight lists
* to hide paragraphs.
**/
this.hidden = false;
}
|
new Token(type, tag, nesting)
Create new token and fill passed properties.
|
Token
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
|
A simple `Array#map`-like wrapper to work with domain name strings.
@private
@param {String} domain The domain name.
@param {Function} callback The function that gets called for every
character.
@returns {Array} A new string of characters returned by the callback
function.
|
mapDomain
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
|
Creates an array containing the numeric code points of each Unicode
character in the string. While JavaScript uses UCS-2 internally,
this function will convert a pair of surrogate halves (each of which
UCS-2 exposes as separate characters) into a single code point,
matching UTF-16.
@see `punycode.ucs2.encode`
@see <http://mathiasbynens.be/notes/javascript-encoding>
@memberOf punycode.ucs2
@name decode
@param {String} string The Unicode input string (UCS-2).
@returns {Array} The new array of code points.
|
ucs2decode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
|
Bias adaptation function as per section 3.4 of RFC 3492.
http://tools.ietf.org/html/rfc3492#section-3.4
@private
|
adapt
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
|
Converts a string of Unicode symbols to a Punycode string of ASCII-only
symbols.
@memberOf punycode
@param {String} input The string of Unicode symbols.
@returns {String} The resulting Punycode string of ASCII-only symbols.
|
encode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
|
Converts a Punycode string representing a domain name to Unicode. Only the
Punycoded parts of the domain name will be converted, i.e. it doesn't
matter if you call it on a string that has already been converted to
Unicode.
@memberOf punycode
@param {String} domain The Punycode domain name to convert to Unicode.
@returns {String} The Unicode representation of the given Punycode
string.
|
toUnicode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
|
Converts a Unicode string representing a domain name to Punycode. Only the
non-ASCII parts of the domain name will be converted, i.e. it doesn't
matter if you call it with a domain that's already in ASCII.
@memberOf punycode
@param {String} domain The domain name to convert, as a Unicode string.
@returns {String} The Punycode representation of the given domain name.
|
toASCII
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function Match(self, shift) {
var start = self.__index__,
end = self.__last_index__,
text = self.__text_cache__.slice(start, end);
/**
* Match#schema -> String
*
* Prefix (protocol) for matched string.
**/
this.schema = self.__schema__.toLowerCase();
/**
* Match#index -> Number
*
* First position of matched string.
**/
this.index = start + shift;
/**
* Match#lastIndex -> Number
*
* Next position after matched string.
**/
this.lastIndex = end + shift;
/**
* Match#raw -> String
*
* Matched string.
**/
this.raw = text;
/**
* Match#text -> String
*
* Notmalized text of matched string.
**/
this.text = text;
/**
* Match#url -> String
*
* Normalized url of matched string.
**/
this.url = text;
}
|
class Match
Match result. Single element of array, returned by [[LinkifyIt#match]]
|
Match
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function createMatch(self, shift) {
var match = new Match(self, shift);
self.__compiled__[match.schema].normalize(match, self);
return match;
}
|
Match#url -> String
Normalized url of matched string.
|
createMatch
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function LinkifyIt(schemas) {
if (!(this instanceof LinkifyIt)) {
return new LinkifyIt(schemas);
}
// Cache last tested result. Used to skip repeating steps on next `match` call.
this.__index__ = -1;
this.__last_index__ = -1; // Next scan position
this.__schema__ = '';
this.__text_cache__ = '';
this.__schemas__ = assign({}, defaultSchemas, schemas);
this.__compiled__ = {};
this.__tlds__ = tlds_default;
this.__tlds_replaced__ = false;
this.re = {};
compile(this);
}
|
new LinkifyIt(schemas)
- schemas (Object): Optional. Additional schemas to validate (prefix/validator)
Creates new linkifier instance with optional additional schemas.
Can be called without `new` keyword for convenience.
By default understands:
- `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links
- "fuzzy" links and emails (example.com, [email protected]).
`schemas` is an object, where each key/value describes protocol/rule:
- __key__ - link prefix (usually, protocol name with `:` at the end, `skype:`
for example). `linkify-it` makes shure that prefix is not preceeded with
alphanumeric char and symbols. Only whitespaces and punctuation allowed.
- __value__ - rule to check tail after link prefix
- _String_ - just alias to existing rule
- _Object_
- _validate_ - validator function (should return matched length on success),
or `RegExp`.
- _normalize_ - optional function to normalize text & url of matched result
(for example, for @twitter mentions).
|
LinkifyIt
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function getDecodeCache(exclude) {
var i, ch, cache = decodeCache[exclude];
if (cache) { return cache; }
cache = decodeCache[exclude] = [];
for (i = 0; i < 128; i++) {
ch = String.fromCharCode(i);
cache.push(ch);
}
for (i = 0; i < exclude.length; i++) {
ch = exclude.charCodeAt(i);
cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2);
}
return cache;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
getDecodeCache
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
arrayBufferToBase64 = buffer => {
let binary = '';
let bytes = [].slice.call(new Uint8Array(buffer.data.data));
bytes.forEach((b) => binary += String.fromCharCode(b));
return `data:${buffer.contentType};base64,${window.btoa(binary)}`;
}
|
base64.js
this helper formulate buffer data to base64 string
|
arrayBufferToBase64
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/base64.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/base64.js
|
MIT
|
formatDate = date => {
const newDate = new Date(date);
// const newDateOptions = {
// year: "numeric",
// month: "short",
// day: "numeric"
// };
return newDate.toLocaleDateString('en-US', dateOptions);
}
|
date.js
this helper formulate date
|
formatDate
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/date.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/date.js
|
MIT
|
handleError = (err, dispatch, title = '') => {
const unsuccessfulOptions = {
title: `${title}`,
message: ``,
position: 'tr',
autoDismiss: 1
};
if (err.response) {
if (err.response.status === 400) {
unsuccessfulOptions.title = title ? title : 'Please Try Again!';
unsuccessfulOptions.message = err.response.data.error;
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 404) {
// unsuccessfulOptions.title =
// err.response.data.message ||
// 'Your request could not be processed. Please try again.';
// dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 401) {
unsuccessfulOptions.message = 'Unauthorized Access! Please login again';
dispatch(signOut());
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 403) {
unsuccessfulOptions.message =
'Forbidden! You are not allowed to access this resource.';
dispatch(error(unsuccessfulOptions));
}
} else if (err.message) {
unsuccessfulOptions.message = err.message;
dispatch(error(unsuccessfulOptions));
} else {
// fallback
unsuccessfulOptions.message =
'Your request could not be processed. Please try again.';
}
}
|
error.js
This is a generic error handler, it receives the error returned from the server and present it on a pop up
|
handleError
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/error.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/error.js
|
MIT
|
formatSelectOptions = (data, empty = false, from) => {
let newSelectOptions = [];
if (data && data.length > 0) {
data.map(option => {
let newOption = {};
newOption.value = option._id;
newOption.label = option.name;
newSelectOptions.push(newOption);
});
}
if (empty) {
const emptyOption = {
value: 0,
label: 'No option selected'
};
newSelectOptions.unshift(emptyOption);
}
return newSelectOptions;
}
|
select.js
this helper formulate data into select options
|
formatSelectOptions
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/select.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/select.js
|
MIT
|
setToken = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
delete axios.defaults.headers.common['Authorization'];
}
}
|
token.js
axios default headers setup
|
setToken
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/token.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/token.js
|
MIT
|
Tagging = function( elem, options ) {
this.elem = elem; // The tag box
this.$elem = $( elem ); // jQuerify tag box
this.options = options; // JS custom options
this.tags = []; // Here we store all tags
// this.$type_zone = void 0; // The tag box's input zone
}
|
taggingJS Constructor
@param obj elem DOM object of tag box
@param obj options Custom JS options
|
Tagging
|
javascript
|
sniperwolf/taggingJS
|
tagging.js
|
https://github.com/sniperwolf/taggingJS/blob/master/tagging.js
|
MIT
|
function _applyAttrs(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.setAttribute(attr, attrs[attr]);
}
}
}
|
Applies attributes to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyAttrs
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _applyStyles(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.style[attr] = attrs[attr];
}
}
}
|
Applies styles to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyStyles
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _getStyle(el, styleProp) {
var x = el
, y = null;
if (window.getComputedStyle) {
y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
}
else if (x.currentStyle) {
y = x.currentStyle[styleProp];
}
return y;
}
|
Returns a DOM objects computed style
@param {object} el The element you want to get the style from
@param {string} styleProp The property you want to get from the element
@returns {string} Returns a string of the value. If property is not set it will return a blank string
|
_getStyle
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _saveStyleState(el, type, styles) {
var returnState = {}
, style;
if (type === 'save') {
for (style in styles) {
if (styles.hasOwnProperty(style)) {
returnState[style] = _getStyle(el, style);
}
}
// After it's all done saving all the previous states, change the styles
_applyStyles(el, styles);
}
else if (type === 'apply') {
_applyStyles(el, styles);
}
return returnState;
}
|
Saves the current style state for the styles requested, then applies styles
to overwrite the existing one. The old styles are returned as an object so
you can pass it back in when you want to revert back to the old style
@param {object} el The element to get the styles of
@param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles
@param {object} styles Key/value style/property pairs
@returns {object}
|
_saveStyleState
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _outerWidth(el) {
var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10)
, p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10)
, w = el.offsetWidth
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total width including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerWidth
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _outerHeight(el) {
var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10)
, p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10)
, w = parseInt(_getStyle(el, 'height'), 10)
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total height including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerHeight
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _insertCSSLink(path, context, id) {
id = id || '';
var headID = context.getElementsByTagName("head")[0]
, cssNode = context.createElement('link');
_applyAttrs(cssNode, {
type: 'text/css'
, id: id
, rel: 'stylesheet'
, href: path
, name: path
, media: 'screen'
});
headID.appendChild(cssNode);
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_insertCSSLink
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _sanitizeRawContent(content) {
// Get this, 2 spaces in a content editable actually converts to:
// 0020 00a0, meaning, "space no-break space". So, manually convert
// no-break spaces to spaces again before handing to marked.
// Also, WebKit converts no-break to unicode equivalent and FF HTML.
return content.replace(/\u00a0/g, ' ').replace(/ /g, ' ');
}
|
Converts the 'raw' format of a file's contents into plaintext
@param {string} content Contents of the file
@returns {string} the sanitized content
|
_sanitizeRawContent
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _isIE() {
var rv = -1 // Return value assumes failure.
, ua = navigator.userAgent
, re;
if (navigator.appName == 'Microsoft Internet Explorer') {
re = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1, 10);
}
}
return rv;
}
|
Will return the version number if the browser is IE. If not will return -1
TRY NEVER TO USE THIS AND USE FEATURE DETECTION IF POSSIBLE
@returns {Number} -1 if false or the version number if true
|
_isIE
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.