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 disableEventListeners() { if (this.state.eventsEnabled) { cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } }
It will remove resize/scroll events and won't recalculate popper position when they are triggered. It also won't trigger `onUpdate` callback anymore, unless you call `update` method manually. @method @memberof Popper
disableEventListeners
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); }
Tells if a given input is a number @method @memberof Popper.Utils @param {*} input to check @return {Boolean}
isNumeric
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); }
Set the style to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the style to @argument {Object} styles Object with a list of properties and values which will be applied to the element
setStyles
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); }
Set the attributes to the given popper @method @memberof Popper.Utils @argument {Element} element - Element to apply the attributes to @argument {Object} styles Object with a list of properties and values which will be applied to the element
setAttributes
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; }
@function @memberof Modifiers @argument {Object} data - The data object generated by `update` method @argument {Object} data.styles - List of style properties - values to apply to popper element @argument {Object} data.attributes - List of attribute properties - values to apply to popper element @argument {Object} options - Modifiers configuration and options @returns {Object} The same data object
applyStyle
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; }
Set the x-placement attribute before everything else because it could be used to add margins to the popper margins needs to be calculated to get the correct popper offsets. @method @memberof Popper.modifiers @param {HTMLElement} reference - The reference element used to position the popper @param {HTMLElement} popper - The HTML element used as popper @param {Object} options - Popper.js options
applyStyleOnLoad
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function getRoundedOffsets(data, shouldRound) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var round = Math.round, floor = Math.floor; var noRound = function noRound(v) { return v; }; var referenceWidth = round(reference.width); var popperWidth = round(popper.width); var isVertical = ['left', 'right'].indexOf(data.placement) !== -1; var isVariation = data.placement.indexOf('-') !== -1; var sameWidthParity = referenceWidth % 2 === popperWidth % 2; var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1; var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor; var verticalToInteger = !shouldRound ? noRound : round; return { left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left), top: verticalToInteger(popper.top), bottom: verticalToInteger(popper.bottom), right: horizontalToInteger(popper.right) }; }
@function @memberof Popper.Utils @argument {Object} data - The data object generated by `update` method @argument {Boolean} shouldRound - If the offsets should be rounded at all @returns {Object} The popper's position offsets rounded The tale of pixel-perfect positioning. It's still not 100% perfect, but as good as it can be within reason. Discussion here: https://github.com/FezVrasta/popper.js/pull/715 Low DPI screens cause a popper to be blurry if not using full pixels (Safari as well on High DPI screens). Firefox prefers no rounding for positioning and does not have blurriness on high DPI screens. Only horizontal placement and left/right values need to be considered.
getRoundedOffsets
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox); var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { // when offsetParent is <html> the positioning is relative to the bottom of the screen (excluding the scrollbar) // and not the bottom of the html element if (offsetParent.nodeName === 'HTML') { top = -offsetParent.clientHeight + offsets.bottom; } else { top = -offsetParentRect.height + offsets.bottom; } } else { top = offsets.top; } if (sideB === 'right') { if (offsetParent.nodeName === 'HTML') { left = -offsetParent.clientWidth + offsets.right; } else { left = -offsetParentRect.width + offsets.right; } } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; }
@function @memberof Modifiers @argument {Object} data - The data object generated by `update` method @argument {Object} options - Modifiers configuration and options @returns {Object} The data object, properly modified
computeStyle
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; }
Helper used to know if the given modifier depends from another one.<br /> It checks if the needed modifier is listed and enabled. @method @memberof Popper.Utils @param {Array} modifiers - list of modifiers @param {String} requestingName - name of requesting modifier @param {String} requestedName - name of requested modifier @returns {Boolean}
isModifierRequired
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function arrow(data, options) { var _data$offsets$arrow; // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjunction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } data.offsets.popper = getClientRect(data.offsets.popper); // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var css = getStyleComputedProperty(data.instance.popper); var popperMarginSide = parseFloat(css['margin' + sideCapitalized], 10); var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width'], 10); var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow); return data; }
@function @memberof Modifiers @argument {Object} data - The data object generated by update method @argument {Object} options - Modifiers configuration and options @returns {Object} The data object, properly modified
arrow
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; }
Get the opposite placement variation of the given one @method @memberof Popper.Utils @argument {String} placement variation @returns {String} flipped placement variation
getOppositeVariation
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; }
Given an initial placement, returns all the subsequent placements clockwise (or counter-clockwise). @method @memberof Popper.Utils @argument {String} placement - A valid placement (it accepts variations) @argument {Boolean} counter - Set to true to walk the placements counterclockwise @returns {Array} placements including their variations
clockwise
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } }
Converts a string containing value + unit into a px value number @function @memberof {modifiers~offset} @private @argument {String} str - Value + unit string @argument {String} measurement - `height` or `width` @argument {Object} popperOffsets @argument {Object} referenceOffsets @returns {Number|String} Value in pixels, or original string if no values were extracted
toValue
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; }
Parse an `offset` string to extrapolate `x` and `y` numeric offsets. @function @memberof {modifiers~offset} @private @argument {String} offset @argument {Object} popperOffsets @argument {Object} referenceOffsets @argument {String} basePlacement @returns {Array} a two cells array with x and y offsets in numbers
parseOffset
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; }
@function @memberof Modifiers @argument {Object} data - The data object generated by update method @argument {Object} options - Modifiers configuration and options @argument {Number|String} options.offset=0 The offset value as described in the modifier description @returns {Object} The data object, properly modified
offset
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; }
Creates a new Popper.js instance. @class Popper @param {HTMLElement|referenceObject} reference - The reference element used to position the popper @param {HTMLElement} popper - The HTML element used as the popper @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) @return {Object} instance - The generated Popper.js instance
Popper
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
transitionComplete = function transitionComplete() { if (_this3._config.focus) { _this3._element.focus(); } _this3._isTransitioning = false; $(_this3._element).trigger(shownEvent); }
`document` has 2 events `Event.FOCUSIN` and `Event.CLICK_DATA_API` Do not move `document` in `htmlElements` array It will remove `Event.CLICK_DATA_API` event that should remain
transitionComplete
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function allowedAttribute(attr, allowedAttributeList) { var attrName = attr.nodeName.toLowerCase(); if (allowedAttributeList.indexOf(attrName) !== -1) { if (uriAttrs.indexOf(attrName) !== -1) { return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN)); } return true; } var regExp = allowedAttributeList.filter(function (attrRegex) { return attrRegex instanceof RegExp; }); // Check if a regular expression validates the attribute. for (var i = 0, l = regExp.length; i < l; i++) { if (attrName.match(regExp[i])) { return true; } } return false; }
A pattern that matches safe data URLs. Only matches image, video and audio types. Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
allowedAttribute
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
complete = function complete() { if (_this.config.animation) { _this._fixTransition(); } var prevHoverState = _this._hoverState; _this._hoverState = null; $(_this.element).trigger(_this.constructor.Event.SHOWN); if (prevHoverState === HoverState.OUT) { _this._leave(null, _this); } }
Check for Popper dependency Popper - https://popper.js.org
complete
javascript
gxtrobot/bustag
bustag/app/static/js/bootstrap.bundle.js
https://github.com/gxtrobot/bustag/blob/master/bustag/app/static/js/bootstrap.bundle.js
MIT
function makeFailHTML(msg) { return '\n<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>\n<td align="center">\n<div style="display: table-cell; vertical-align: middle;">\n<div style="">' + msg + '</div>\n</div>\n</td></tr></table>\n'; }
Creates the HTLM for a failure message @param {string} canvasContainerId id of container of th canvas. @return {string} The html.
makeFailHTML
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function setupWebGL(canvas, optAttribs, onError) { function showLink(str) { var container = canvas.parentNode; if (container) { container.innerHTML = makeFailHTML(str); } } function handleError(errorCode, msg) { if (typeof onError === 'function') { onError(errorCode); } else { showLink(msg); } } if (!window.WebGLRenderingContext) { handleError(ERROR_BROWSER_SUPPORT, GET_A_WEBGL_BROWSER); return null; } var context = create3DContext(canvas, optAttribs); if (!context) { handleError(ERROR_OTHER, OTHER_PROBLEM); } else { context.getExtension('OES_standard_derivatives'); } return context; }
Creates a webgl context. If creation fails it will change the contents of the container of the <canvas> tag to an error message with the correct links for WebGL, unless `onError` option is defined to a callback, which allows for custom error handling.. @param {Element} canvas. The canvas element to create a context from. @param {WebGLContextCreationAttributes} optAttribs Any creation attributes you want to pass in. @return {WebGLRenderingContext} The created context.
setupWebGL
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function create3DContext(canvas, optAttribs) { var names = ['webgl', 'experimental-webgl']; var context = null; for (var ii = 0; ii < names.length; ++ii) { try { context = canvas.getContext(names[ii], optAttribs); } catch (e) { if (context) { break; } } } return context; }
Creates a webgl context. @param {!Canvas} canvas The canvas tag to get context from. If one is not passed in one will be created. @return {!WebGLContext} The created context.
create3DContext
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
function createProgram(main, shaders, optAttribs, optLocations) { var gl = main.gl; var program = gl.createProgram(); for (var ii = 0; ii < shaders.length; ++ii) { gl.attachShader(program, shaders[ii]); } if (optAttribs) { for (var _ii = 0; _ii < optAttribs.length; ++_ii) { gl.bindAttribLocation(program, optLocations ? optLocations[_ii] : _ii, optAttribs[_ii]); } } gl.linkProgram(program); // Check the link status var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { // something went wrong with the link lastError = gl.getProgramInfoLog(program); console.log('Error in program linking:' + lastError); gl.deleteProgram(program); return null; } return program; }
Loads a shader. @param {!WebGLContext} gl The WebGLContext to use. @param {string} shaderSource The shader source. @param {number} shaderType The type of shader. @param {function(string): void) opt_errorCallback callback for errors. @return {!WebGLShader} The created shader.
createProgram
javascript
patriciogonzalezvivo/glslGallery
build/glslGallery.js
https://github.com/patriciogonzalezvivo/glslGallery/blob/master/build/glslGallery.js
MIT
Point = (x, y, r) => { return { x, y, radius: r }; }
Tests for server/lib/util.js This is mostly a regression suite, to make sure behavior is preserved throughout changes to the server infrastructure.
Point
javascript
owenashurst/agar.io-clone
test/util.js
https://github.com/owenashurst/agar.io-clone/blob/master/test/util.js
MIT
function build () { console.log('Installing node_modules...') rimraf.sync(NODE_MODULES_PATH) cp.execSync('npm ci', { stdio: 'inherit' }) console.log('Nuking dist/ and build/...') rimraf.sync(DIST_PATH) rimraf.sync(BUILD_PATH) console.log('Build: Transpiling to ES5...') cp.execSync('npm run build', { NODE_ENV: 'production', stdio: 'inherit' }) console.log('Build: Transpiled to ES5.') const platform = argv._[0] if (platform === 'darwin') { buildDarwin(printDone) } else if (platform === 'win32') { buildWin32(printDone) } else if (platform === 'linux') { buildLinux(printDone) } else { buildDarwin(function (err) { printDone(err) buildWin32(function (err) { printDone(err) buildLinux(printDone) }) }) } }
Builds app binaries for Mac, Windows, and Linux.
build
javascript
webtorrent/webtorrent-desktop
bin/package.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/bin/package.js
MIT
function packagePortable (filesPath, cb) { console.log('Windows: Creating portable app...') const portablePath = path.join(filesPath, 'Portable Settings') fs.mkdirSync(portablePath, { recursive: true }) const downloadsPath = path.join(portablePath, 'Downloads') fs.mkdirSync(downloadsPath, { recursive: true }) const tempPath = path.join(portablePath, 'Temp') fs.mkdirSync(tempPath, { recursive: true }) const inPath = path.join(DIST_PATH, path.basename(filesPath)) const outPath = path.join(DIST_PATH, BUILD_NAME + '-win.zip') zip.zipSync(inPath, outPath) console.log('Windows: Created portable app.') cb(null) }
Delete extraneous Squirrel files (i.e. *.nupkg delta files for older versions of the app)
packagePortable
javascript
webtorrent/webtorrent-desktop
bin/package.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/bin/package.js
MIT
function init () { const get = require('simple-get') get.concat(ANNOUNCEMENT_URL, onResponse) }
In certain situations, the WebTorrent team may need to show an announcement to all WebTorrent Desktop users. For example: a security notice, or an update notification (if the auto-updater stops working). When there is an announcement, the `ANNOUNCEMENT_URL` endpoint should return an HTTP 200 status code with a JSON object like this: { "title": "WebTorrent Desktop Announcement", "message": "Security Issue in v0.xx", "detail": "Please update to v0.xx as soon as possible..." }
init
javascript
webtorrent/webtorrent-desktop
src/main/announcement.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/announcement.js
MIT
function openSeedFile () { if (!windows.main.win) return log('openSeedFile') const opts = { title: 'Select a file for the torrent.', properties: ['openFile'] } showOpenSeed(opts) }
Show open dialog to create a single-file torrent.
openSeedFile
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function setTitle (title) { if (process.platform === 'darwin') { windows.main.dispatch('setTitle', title) } }
Dialogs on do not show a title on Mac, so the window title is used instead.
setTitle
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function showOpenSeed (opts) { setTitle(opts.title) const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts) resetTitle() if (!Array.isArray(selectedPaths)) return windows.main.dispatch('showCreateTorrent', selectedPaths) }
Pops up an Open File dialog with the given options. After the user selects files / folders, shows the Create Torrent page.
showOpenSeed
javascript
webtorrent/webtorrent-desktop
src/main/dialog.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dialog.js
MIT
function init () { if (!app.dock) return const menu = Menu.buildFromTemplate(getMenuTemplate()) app.dock.setMenu(menu) }
Add a right-click menu to the dock icon. (Mac)
init
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function downloadFinished (path) { if (!app.dock) return log(`downloadFinished: ${path}`) app.dock.downloadFinished(path) }
Bounce the Downloads stack if `path` is inside the Downloads folder. (Mac)
downloadFinished
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function setBadge (count) { if (process.platform === 'darwin' || (process.platform === 'linux' && app.isUnityRunning())) { log(`setBadge: ${count}`) app.badgeCount = Number(count) } }
Display a counter badge for the app. (Mac, Linux)
setBadge
javascript
webtorrent/webtorrent-desktop
src/main/dock.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/dock.js
MIT
function registerProtocolHandlerWin32 (protocol, name, icon, command) { const protocolKey = new Registry({ hive: Registry.HKCU, // HKEY_CURRENT_USER key: '\\Software\\Classes\\' + protocol }) setProtocol() function setProtocol (err) { if (err) return log.error(err.message) protocolKey.set('', Registry.REG_SZ, name, setURLProtocol) } function setURLProtocol (err) { if (err) return log.error(err.message) protocolKey.set('URL Protocol', Registry.REG_SZ, '', setIcon) } function setIcon (err) { if (err) return log.error(err.message) const iconKey = new Registry({ hive: Registry.HKCU, key: `\\Software\\Classes\\${protocol}\\DefaultIcon` }) iconKey.set('', Registry.REG_SZ, icon, setCommand) } function setCommand (err) { if (err) return log.error(err.message) const commandKey = new Registry({ hive: Registry.HKCU, key: `\\Software\\Classes\\${protocol}\\shell\\open\\command` }) commandKey.set('', Registry.REG_SZ, `${commandToArgs(command)} "%1"`, done) } function done (err) { if (err) return log.error(err.message) } }
To add a protocol handler, the following keys must be added to the Windows registry: HKEY_CLASSES_ROOT $PROTOCOL (Default) = "$NAME" URL Protocol = "" DefaultIcon (Default) = "$ICON" shell open command (Default) = "$COMMAND" "%1" Source: https://msdn.microsoft.com/en-us/library/aa767914.aspx However, the "HKEY_CLASSES_ROOT" key can only be written by the Administrator user. So, we instead write to "HKEY_CURRENT_USER\Software\Classes", which is inherited by "HKEY_CLASSES_ROOT" anyway, and can be written by unprivileged users.
registerProtocolHandlerWin32
javascript
webtorrent/webtorrent-desktop
src/main/handlers.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/handlers.js
MIT
function registerFileHandlerWin32 (ext, id, name, icon, command) { setExt() function setExt () { const extKey = new Registry({ hive: Registry.HKCU, // HKEY_CURRENT_USER key: `\\Software\\Classes\\${ext}` }) extKey.set('', Registry.REG_SZ, id, setId) } function setId (err) { if (err) return log.error(err.message) const idKey = new Registry({ hive: Registry.HKCU, key: `\\Software\\Classes\\${id}` }) idKey.set('', Registry.REG_SZ, name, setIcon) } function setIcon (err) { if (err) return log.error(err.message) const iconKey = new Registry({ hive: Registry.HKCU, key: `\\Software\\Classes\\${id}\\DefaultIcon` }) iconKey.set('', Registry.REG_SZ, icon, setCommand) } function setCommand (err) { if (err) return log.error(err.message) const commandKey = new Registry({ hive: Registry.HKCU, key: `\\Software\\Classes\\${id}\\shell\\open\\command` }) commandKey.set('', Registry.REG_SZ, `${commandToArgs(command)} "%1"`, done) } function done (err) { if (err) return log.error(err.message) } }
To add a file handler, the following keys must be added to the Windows registry: HKEY_CLASSES_ROOT $EXTENSION (Default) = "$EXTENSION_ID" $EXTENSION_ID (Default) = "$NAME" DefaultIcon (Default) = "$ICON" shell open command (Default) = "$COMMAND" "%1"
registerFileHandlerWin32
javascript
webtorrent/webtorrent-desktop
src/main/handlers.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/handlers.js
MIT
function log (...args) { if (app.ipcReady) { windows.main.send('log', ...args) } else { app.once('ipcReady', () => windows.main.send('log', ...args)) } }
In the main electron process, we do not use console.log() statements because they do not show up in a convenient location when running the packaged (i.e. production) version of the app. Instead use this module, which sends the logs to the main window where they can be viewed in Developer Tools.
log
javascript
webtorrent/webtorrent-desktop
src/main/log.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/log.js
MIT
function enable () { if (powerSaveBlocker.isStarted(blockId)) { // If a power saver block already exists, do nothing. return } blockId = powerSaveBlocker.start('prevent-display-sleep') log(`powerSaveBlocker.enable: ${blockId}`) }
Block the system from entering low-power (sleep) mode or turning off the display.
enable
javascript
webtorrent/webtorrent-desktop
src/main/power-save-blocker.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/power-save-blocker.js
MIT
function disable () { if (!powerSaveBlocker.isStarted(blockId)) { // If a power saver block does not exist, do nothing. return } powerSaveBlocker.stop(blockId) log(`powerSaveBlocker.disable: ${blockId}`) }
Stop blocking the system from entering low-power mode.
disable
javascript
webtorrent/webtorrent-desktop
src/main/power-save-blocker.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/power-save-blocker.js
MIT
function showItemInFolder (path) { log(`showItemInFolder: ${path}`) shell.showItemInFolder(path) }
Show the given file in a file manager. If possible, select the file.
showItemInFolder
javascript
webtorrent/webtorrent-desktop
src/main/shell.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/shell.js
MIT
function moveItemToTrash (path) { log(`moveItemToTrash: ${path}`) shell.trashItem(path) }
Move the given file to trash and returns a boolean status for the operation.
moveItemToTrash
javascript
webtorrent/webtorrent-desktop
src/main/shell.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/shell.js
MIT
function enable () { buttons = [ { tooltip: 'Previous Track', icon: PREV_ICON, click: () => windows.main.dispatch('previousTrack') }, { tooltip: 'Pause', icon: PAUSE_ICON, click: () => windows.main.dispatch('playPause') }, { tooltip: 'Next Track', icon: NEXT_ICON, click: () => windows.main.dispatch('nextTrack') } ] update() }
Show the Windows thumbnail toolbar buttons.
enable
javascript
webtorrent/webtorrent-desktop
src/main/thumbar.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/thumbar.js
MIT
function disable () { buttons = [] update() }
Hide the Windows thumbnail toolbar buttons.
disable
javascript
webtorrent/webtorrent-desktop
src/main/thumbar.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/thumbar.js
MIT
function hasTray () { return !!tray }
Returns true if there a tray icon is active.
hasTray
javascript
webtorrent/webtorrent-desktop
src/main/tray.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/tray.js
MIT
function checkLinuxTraySupport (cb) { const cp = require('child_process') // Check that libappindicator libraries are installed in system. cp.exec('ldconfig -p | grep libappindicator', (err, stdout) => { if (err) return cb(err) cb(null) }) }
Check for libappindicator support before creating tray icon.
checkLinuxTraySupport
javascript
webtorrent/webtorrent-desktop
src/main/tray.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/tray.js
MIT
function init () { if (process.platform !== 'win32') return app.setUserTasks(getUserTasks()) }
Add a user task menu to the app icon on right-click. (Windows)
init
javascript
webtorrent/webtorrent-desktop
src/main/user-tasks.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/user-tasks.js
MIT
function setAspectRatio (aspectRatio) { if (!main.win) return main.win.setAspectRatio(aspectRatio) }
Enforce window aspect ratio. Remove with 0. (Mac)
setAspectRatio
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function setBounds (bounds, maximize) { // Do nothing in fullscreen if (!main.win || main.win.isFullScreen()) { log('setBounds: not setting bounds because already in full screen mode') return } // Maximize or minimize, if the second argument is present if (maximize === true && !main.win.isMaximized()) { log('setBounds: maximizing') main.win.maximize() } else if (maximize === false && main.win.isMaximized()) { log('setBounds: minimizing') main.win.unmaximize() } const willBeMaximized = typeof maximize === 'boolean' ? maximize : main.win.isMaximized() // Assuming we're not maximized or maximizing, set the window size if (!willBeMaximized) { log(`setBounds: setting bounds to ${JSON.stringify(bounds)}`) if (bounds.x === null && bounds.y === null) { // X and Y not specified? By default, center on current screen const scr = screen.getDisplayMatching(main.win.getBounds()) bounds.x = Math.round(scr.bounds.x + (scr.bounds.width / 2) - (bounds.width / 2)) bounds.y = Math.round(scr.bounds.y + (scr.bounds.height / 2) - (bounds.height / 2)) log(`setBounds: centered to ${JSON.stringify(bounds)}`) } // Resize the window's content area (so window border doesn't need to be taken // into account) if (bounds.contentBounds) { main.win.setContentBounds(bounds, true) } else { main.win.setBounds(bounds, true) } } else { log('setBounds: not setting bounds because of window maximization') } }
Change the size of the window. TODO: Clean this up? Seems overly complicated.
setBounds
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function setProgress (progress) { if (!main.win) return main.win.setProgressBar(progress) }
Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0.
setProgress
javascript
webtorrent/webtorrent-desktop
src/main/windows/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js
MIT
function onState (err, _state) { if (err) return onError(err) // Make available for easier debugging state = window.state = _state window.dispatch = dispatch telemetry.init(state) sound.init(state) // Log uncaught JS errors window.addEventListener( 'error', (e) => telemetry.logUncaughtError('window', e), true /* capture */ ) // Create controllers controllers = { media: createGetter(() => { const MediaController = require('./controllers/media-controller') return new MediaController(state) }), playback: createGetter(() => { const PlaybackController = require('./controllers/playback-controller') return new PlaybackController(state, config, update) }), prefs: createGetter(() => { const PrefsController = require('./controllers/prefs-controller') return new PrefsController(state, config) }), subtitles: createGetter(() => { const SubtitlesController = require('./controllers/subtitles-controller') return new SubtitlesController(state) }), audioTracks: createGetter(() => { const AudioTracksController = require('./controllers/audio-tracks-controller') return new AudioTracksController(state) }), torrent: createGetter(() => { const TorrentController = require('./controllers/torrent-controller') return new TorrentController(state) }), torrentList: createGetter(() => new TorrentListController(state)), update: createGetter(() => { const UpdateController = require('./controllers/update-controller') return new UpdateController(state) }), folderWatcher: createGetter(() => { const FolderWatcherController = require('./controllers/folder-watcher-controller') return new FolderWatcherController() }) } // Add first page to location history state.location.go({ url: 'home', setup: (cb) => { state.window.title = config.APP_WINDOW_TITLE cb(null) } }) // Give global trackers setGlobalTrackers() // Restart everything we were torrenting last time the app ran resumeTorrents() // Initialize ReactDOM ReactDOM.render( <App state={state} ref={elem => { app = elem }} />, document.querySelector('#body') ) // Calling update() updates the UI given the current state // Do this at least once a second to give every file in every torrentSummary // a progress bar and to keep the cursor in sync when playing a video setInterval(update, 1000) // Listen for messages from the main process setupIpc() // Drag and drop files/text to start torrenting or seeding dragDrop('body', { onDrop: onOpen, onDropText: onOpen }) // ...same thing if you paste a torrent document.addEventListener('paste', onPaste) // Add YouTube style hotkey shortcuts window.addEventListener('keydown', onKeydown) const debouncedFullscreenToggle = debounce(() => { dispatch('toggleFullScreen') }, 1000, true) document.addEventListener('wheel', event => { // ctrlKey detects pinch to zoom, http://crbug.com/289887 if (event.ctrlKey) { event.preventDefault() debouncedFullscreenToggle() } }) // ...focus and blur. Needed to show correct dock icon text ('badge') in OSX window.addEventListener('focus', onFocus) window.addEventListener('blur', onBlur) if (electron.remote.getCurrentWindow().isVisible()) { sound.play('STARTUP') } // To keep app startup fast, some code is delayed. window.setTimeout(delayedInit, config.DELAYED_INIT) // Done! Ideally we want to get here < 500ms after the user clicks the app console.timeEnd('init') }
Perf optimization: Hook into require() to modify how certain modules load: - `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not actually used because auto-prefixing is disabled with `darkBaseTheme.userAgent = false`. Return a fake object.
onState
javascript
webtorrent/webtorrent-desktop
src/renderer/main.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js
MIT
function init () { listenToClientEvents() ipcRenderer.on('wt-set-global-trackers', (e, globalTrackers) => setGlobalTrackers(globalTrackers)) ipcRenderer.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) => startTorrenting(torrentKey, torrentID, path, fileModtimes, selections)) ipcRenderer.on('wt-stop-torrenting', (e, infoHash) => stopTorrenting(infoHash)) ipcRenderer.on('wt-create-torrent', (e, torrentKey, options) => createTorrent(torrentKey, options)) ipcRenderer.on('wt-save-torrent-file', (e, torrentKey) => saveTorrentFile(torrentKey)) ipcRenderer.on('wt-generate-torrent-poster', (e, torrentKey) => generateTorrentPoster(torrentKey)) ipcRenderer.on('wt-get-audio-metadata', (e, infoHash, index) => getAudioMetadata(infoHash, index)) ipcRenderer.on('wt-start-server', (e, infoHash) => startServer(infoHash)) ipcRenderer.on('wt-stop-server', () => stopServer()) ipcRenderer.on('wt-select-files', (e, infoHash, selections) => selectFiles(infoHash, selections)) ipcRenderer.send('ipcReadyWebTorrent') window.addEventListener('error', (e) => ipcRenderer.send('wt-uncaught-error', { message: e.error.message, stack: e.error.stack }), true) setInterval(updateTorrentProgress, 1000) console.timeEnd('init') }
Generate an ephemeral peer ID each time.
init
javascript
webtorrent/webtorrent-desktop
src/renderer/webtorrent.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js
MIT
function calculateDataLengthByExtension (torrent, extensions) { const files = filterOnExtension(torrent, extensions) if (files.length === 0) return 0 return files .map(file => file.length) .reduce((a, b) => a + b) }
Calculate the total data size of file matching one of the provided extensions @param torrent @param extensions List of extension to match @returns {number} total size, of matches found (>= 0)
calculateDataLengthByExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function getLargestFileByExtension (torrent, extensions) { const files = filterOnExtension(torrent, extensions) if (files.length === 0) return undefined return files.reduce((a, b) => a.length > b.length ? a : b) }
Get the largest file of a given torrent, filtered by provided extension @param torrent Torrent to search in @param extensions Extension whitelist filter @returns Torrent file object
getLargestFileByExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function filterOnExtension (torrent, extensions) { return torrent.files.filter(file => { const extname = path.extname(file.name).toLowerCase() return extensions.indexOf(extname) !== -1 }) }
Filter file on a list extension, can be used to find al image files @param torrent Torrent to filter files from @param extensions File extensions to filter on @returns {Array} Array of torrent file objects matching one of the given extensions
filterOnExtension
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function scoreAudioCoverFile (imgFile) { const fileName = path.basename(imgFile.name, path.extname(imgFile.name)).toLowerCase() const relevanceScore = { cover: 80, folder: 80, album: 80, front: 80, back: 20, spectrogram: -80 } for (const keyword in relevanceScore) { if (fileName === keyword) { return relevanceScore[keyword] } if (fileName.indexOf(keyword) !== -1) { return relevanceScore[keyword] } } return 0 }
Returns a score how likely the file is suitable as a poster @param imgFile File object of an image @returns {number} Score, higher score is a better match
scoreAudioCoverFile
javascript
webtorrent/webtorrent-desktop
src/renderer/lib/torrent-poster.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js
MIT
function renderTrack (common, key) { // Audio metadata: track-number if (common[key] && common[key].no) { let str = `${common[key].no}` if (common[key].of) { str += ` of ${common[key].of}` } const style = { textTransform: 'capitalize' } return ( <div className={`audio-${key}`}> <label style={style}>{key}</label> {str} </div> ) } }
Render track or disk number string @param common metadata.common part @param key should be either 'track' or 'disk' @return track or disk number metadata as JSX block
renderTrack
javascript
webtorrent/webtorrent-desktop
src/renderer/pages/player-page.js
https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js
MIT
constructor(name, description) { this.description = description || ''; this.variadic = false; this.parseArg = undefined; this.defaultValue = undefined; this.defaultValueDescription = undefined; this.argChoices = undefined; switch (name[0]) { case '<': // e.g. <required> this.required = true; this._name = name.slice(1, -1); break; case '[': // e.g. [optional] this.required = false; this._name = name.slice(1, -1); break; default: this.required = true; this._name = name; break; } if (this._name.length > 3 && this._name.slice(-3) === '...') { this.variadic = true; this._name = this._name.slice(0, -3); } }
Initialize a new command argument with the given name and description. The default is that the argument is required, and you can explicitly indicate this with <> around the name. Put [] around the name for an optional argument. @param {string} name @param {string} [description]
constructor
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; }
Set the default value, and optionally supply the description to be displayed in the help. @param {*} value @param {string} [description] @return {Argument}
default
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
argParser(fn) { this.parseArg = fn; return this; }
Set the custom handler for processing CLI command arguments into argument values. @param {Function} [fn] @return {Argument}
argParser
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError( `Allowed choices are ${this.argChoices.join(', ')}.`, ); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; }
Only allow argument value to be one of choices. @param {string[]} values @return {Argument}
choices
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
function humanReadableArgName(arg) { const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; }
Takes an argument and returns its human readable equivalent for help usage. @param {Argument} arg @return {string} @private
humanReadableArgName
javascript
tj/commander.js
lib/argument.js
https://github.com/tj/commander.js/blob/master/lib/argument.js
MIT
constructor(name) { super(); /** @type {Command[]} */ this.commands = []; /** @type {Option[]} */ this.options = []; this.parent = null; this._allowUnknownOption = false; this._allowExcessArguments = false; /** @type {Argument[]} */ this.registeredArguments = []; this._args = this.registeredArguments; // deprecated old name /** @type {string[]} */ this.args = []; // cli args with options removed this.rawArgs = []; this.processedArgs = []; // like .args but after custom processing and collecting variadic this._scriptPath = null; this._name = name || ''; this._optionValues = {}; this._optionValueSources = {}; // default, env, cli etc this._storeOptionsAsProperties = false; this._actionHandler = null; this._executableHandler = false; this._executableFile = null; // custom name for executable this._executableDir = null; // custom search directory for subcommands this._defaultCommandName = null; this._exitCallback = null; this._aliases = []; this._combineFlagAndOptionalValue = true; this._description = ''; this._summary = ''; this._argsDescription = undefined; // legacy this._enablePositionalOptions = false; this._passThroughOptions = false; this._lifeCycleHooks = {}; // a hash of arrays /** @type {(boolean | string)} */ this._showHelpAfterError = false; this._showSuggestionAfterError = true; this._savedState = null; // used in save/restoreStateBeforeParse // see configureOutput() for docs this._outputConfiguration = { writeOut: (str) => process.stdout.write(str), writeErr: (str) => process.stderr.write(str), outputError: (str, write) => write(str), getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined, getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined, getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()), getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()), stripColor: (str) => stripColor(str), }; this._hidden = false; /** @type {(Option | null | undefined)} */ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled. this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited /** @type {Command} */ this._helpCommand = undefined; // lazy initialised, inherited this._helpConfiguration = {}; /** @type {string | undefined} */ this._helpGroupHeading = undefined; // soft initialised when added to parent /** @type {string | undefined} */ this._defaultCommandGroup = undefined; /** @type {string | undefined} */ this._defaultOptionGroup = undefined; }
Initialize a new `Command`. @param {string} [name]
constructor
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
copyInheritedSettings(sourceCommand) { this._outputConfiguration = sourceCommand._outputConfiguration; this._helpOption = sourceCommand._helpOption; this._helpCommand = sourceCommand._helpCommand; this._helpConfiguration = sourceCommand._helpConfiguration; this._exitCallback = sourceCommand._exitCallback; this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue; this._allowExcessArguments = sourceCommand._allowExcessArguments; this._enablePositionalOptions = sourceCommand._enablePositionalOptions; this._showHelpAfterError = sourceCommand._showHelpAfterError; this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; return this; }
Copy settings that are useful to have in common across root command and subcommands. (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) @param {Command} sourceCommand @return {Command} `this` command for chaining
copyInheritedSettings
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
command(nameAndArgs, actionOptsOrExecDesc, execOpts) { let desc = actionOptsOrExecDesc; let opts = execOpts; if (typeof desc === 'object' && desc !== null) { opts = desc; desc = null; } opts = opts || {}; const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); const cmd = this.createCommand(name); if (desc) { cmd.description(desc); cmd._executableHandler = true; } if (opts.isDefault) this._defaultCommandName = cmd._name; cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor if (args) cmd.arguments(args); this._registerCommand(cmd); cmd.parent = this; cmd.copyInheritedSettings(this); if (desc) return this; return cmd; }
Define a command. There are two styles of command: pay attention to where to put the description. @example // Command implemented using action handler (description is supplied separately to `.command`) program .command('clone <source> [destination]') .description('clone a repository into a newly created directory') .action((source, destination) => { console.log('clone command called'); }); // Command implemented using separate executable file (description is second parameter to `.command`) program .command('start <service>', 'start named service') .command('stop [service]', 'stop named service, or all if no name supplied'); @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) @param {object} [execOpts] - configuration options (for executable) @return {Command} returns new command for action handler, or `this` for executable command
command
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createCommand(name) { return new Command(name); }
Factory routine to create a new unattached command. See .command() for creating an attached subcommand, which uses this routine to create the command. You can override createCommand to customise subcommands. @param {string} [name] @return {Command} new command
createCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createHelp() { return Object.assign(new Help(), this.configureHelp()); }
You can customise the help with a subclass of Help by overriding createHelp, or by overriding Help properties using configureHelp(). @return {Help}
createHelp
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
configureHelp(configuration) { if (configuration === undefined) return this._helpConfiguration; this._helpConfiguration = configuration; return this; }
You can customise the help by overriding Help properties using configureHelp(), or with a subclass of Help by overriding createHelp(). @param {object} [configuration] - configuration options @return {(Command | object)} `this` command for chaining, or stored configuration
configureHelp
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
configureOutput(configuration) { if (configuration === undefined) return this._outputConfiguration; this._outputConfiguration = Object.assign( {}, this._outputConfiguration, configuration, ); return this; }
The default output goes to stdout and stderr. You can customise this for special applications. You can also customise the display of errors by overriding outputError. The configuration properties are all functions: // change how output being written, defaults to stdout and stderr writeOut(str) writeErr(str) // change how output being written for errors, defaults to writeErr outputError(str, write) // used for displaying errors and not used for displaying help // specify width for wrapping help getOutHelpWidth() getErrHelpWidth() // color support, currently only used with Help getOutHasColors() getErrHasColors() stripColor() // used to remove ANSI escape codes if output does not have colors @param {object} [configuration] - configuration options @return {(Command | object)} `this` command for chaining, or stored configuration
configureOutput
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
showHelpAfterError(displayHelp = true) { if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; this._showHelpAfterError = displayHelp; return this; }
Display the help or a custom message after an error occurs. @param {(boolean|string)} [displayHelp] @return {Command} `this` command for chaining
showHelpAfterError
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
showSuggestionAfterError(displaySuggestion = true) { this._showSuggestionAfterError = !!displaySuggestion; return this; }
Display suggestion of similar commands for unknown commands, or options for unknown options. @param {boolean} [displaySuggestion] @return {Command} `this` command for chaining
showSuggestionAfterError
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addCommand(cmd, opts) { if (!cmd._name) { throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); } opts = opts || {}; if (opts.isDefault) this._defaultCommandName = cmd._name; if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation this._registerCommand(cmd); cmd.parent = this; cmd._checkForBrokenPassThrough(); return this; }
Add a prepared subcommand. See .command() for creating an attached subcommand which inherits settings from its parent. @param {Command} cmd - new subcommand @param {object} [opts] - configuration options @return {Command} `this` command for chaining
addCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createArgument(name, description) { return new Argument(name, description); }
Factory routine to create a new unattached argument. See .argument() for creating an attached argument, which uses this routine to create the argument. You can override createArgument to return a custom argument. @param {string} name @param {string} [description] @return {Argument} new argument
createArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
argument(name, description, parseArg, defaultValue) { const argument = this.createArgument(name, description); if (typeof parseArg === 'function') { argument.default(defaultValue).argParser(parseArg); } else { argument.default(parseArg); } this.addArgument(argument); return this; }
Define argument syntax for command. The default is that the argument is required, and you can explicitly indicate this with <> around the name. Put [] around the name for an optional argument. @example program.argument('<input-file>'); program.argument('[output-file]'); @param {string} name @param {string} [description] @param {(Function|*)} [parseArg] - custom argument processing function or default value @param {*} [defaultValue] @return {Command} `this` command for chaining
argument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
arguments(names) { names .trim() .split(/ +/) .forEach((detail) => { this.argument(detail); }); return this; }
Define argument syntax for command, adding multiple at once (without descriptions). See also .argument(). @example program.arguments('<cmd> [env]'); @param {string} names @return {Command} `this` command for chaining
arguments
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addArgument(argument) { const previousArgument = this.registeredArguments.slice(-1)[0]; if (previousArgument && previousArgument.variadic) { throw new Error( `only the last argument can be variadic '${previousArgument.name()}'`, ); } if ( argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined ) { throw new Error( `a default value for a required argument is never used: '${argument.name()}'`, ); } this.registeredArguments.push(argument); return this; }
Define argument syntax for command, adding a prepared argument. @param {Argument} argument @return {Command} `this` command for chaining
addArgument
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
helpCommand(enableOrNameAndArgs, description) { if (typeof enableOrNameAndArgs === 'boolean') { this._addImplicitHelpCommand = enableOrNameAndArgs; if (enableOrNameAndArgs && this._defaultCommandGroup) { // make the command to store the group this._initCommandGroup(this._getHelpCommand()); } return this; } const nameAndArgs = enableOrNameAndArgs ?? 'help [command]'; const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/); const helpDescription = description ?? 'display help for command'; const helpCommand = this.createCommand(helpName); helpCommand.helpOption(false); if (helpArgs) helpCommand.arguments(helpArgs); if (helpDescription) helpCommand.description(helpDescription); this._addImplicitHelpCommand = true; this._helpCommand = helpCommand; // init group unless lazy create if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand); return this; }
Customise or override default help command. By default a help command is automatically added if your command has subcommands. @example program.helpCommand('help [cmd]'); program.helpCommand('help [cmd]', 'show help'); program.helpCommand(false); // suppress default help command program.helpCommand(true); // add help command even if no subcommands @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added @param {string} [description] - custom description @return {Command} `this` command for chaining
helpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addHelpCommand(helpCommand, deprecatedDescription) { // If not passed an object, call through to helpCommand for backwards compatibility, // as addHelpCommand was originally used like helpCommand is now. if (typeof helpCommand !== 'object') { this.helpCommand(helpCommand, deprecatedDescription); return this; } this._addImplicitHelpCommand = true; this._helpCommand = helpCommand; this._initCommandGroup(helpCommand); return this; }
Add prepared custom help command. @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` @param {string} [deprecatedDescription] - deprecated custom description used with custom name only @return {Command} `this` command for chaining
addHelpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_getHelpCommand() { const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand('help')); if (hasImplicitHelpCommand) { if (this._helpCommand === undefined) { this.helpCommand(undefined, undefined); // use default name and description } return this._helpCommand; } return null; }
Lazy create help command. @return {(Command|null)} @package
_getHelpCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
hook(event, listener) { const allowedValues = ['preSubcommand', 'preAction', 'postAction']; if (!allowedValues.includes(event)) { throw new Error(`Unexpected value for event passed to hook : '${event}'. Expecting one of '${allowedValues.join("', '")}'`); } if (this._lifeCycleHooks[event]) { this._lifeCycleHooks[event].push(listener); } else { this._lifeCycleHooks[event] = [listener]; } return this; }
Add hook for life cycle event. @param {string} event @param {Function} listener @return {Command} `this` command for chaining
hook
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
exitOverride(fn) { if (fn) { this._exitCallback = fn; } else { this._exitCallback = (err) => { if (err.code !== 'commander.executeSubCommandAsync') { throw err; } else { // Async callback from spawn events, not useful to throw. } }; } return this; }
Register callback to use as replacement for calling process.exit. @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing @return {Command} `this` command for chaining
exitOverride
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_exit(exitCode, code, message) { if (this._exitCallback) { this._exitCallback(new CommanderError(exitCode, code, message)); // Expecting this line is not reached. } process.exit(exitCode); }
Call process.exit, and _exitCallback if defined. @param {number} exitCode exit code for using with process.exit @param {string} code an id string representing the error @param {string} message human-readable description of the error @return never @private
_exit
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
action(fn) { const listener = (args) => { // The .action callback takes an extra parameter which is the command or options. const expectedArgsCount = this.registeredArguments.length; const actionArgs = args.slice(0, expectedArgsCount); if (this._storeOptionsAsProperties) { actionArgs[expectedArgsCount] = this; // backwards compatible "options" } else { actionArgs[expectedArgsCount] = this.opts(); } actionArgs.push(this); return fn.apply(this, actionArgs); }; this._actionHandler = listener; return this; }
Register callback `fn` for the command. @example program .command('serve') .description('start service') .action(function() { // do work here }); @param {Function} fn @return {Command} `this` command for chaining
action
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
createOption(flags, description) { return new Option(flags, description); }
Factory routine to create a new unattached option. See .option() for creating an attached option, which uses this routine to create the option. You can override createOption to return a custom option. @param {string} flags @param {string} [description] @return {Option} new option
createOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_callParseArg(target, value, previous, invalidArgumentMessage) { try { return target.parseArg(value, previous); } catch (err) { if (err.code === 'commander.invalidArgument') { const message = `${invalidArgumentMessage} ${err.message}`; this.error(message, { exitCode: err.exitCode, code: err.code }); } throw err; } }
Wrap parseArgs to catch 'commander.invalidArgument'. @param {(Option | Argument)} target @param {string} value @param {*} previous @param {string} invalidArgumentMessage @private
_callParseArg
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_registerOption(option) { const matchingOption = (option.short && this._findOption(option.short)) || (option.long && this._findOption(option.long)); if (matchingOption) { const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short; throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}' - already used by option '${matchingOption.flags}'`); } this._initOptionGroup(option); this.options.push(option); }
Check for option flag conflicts. Register option if no conflicts found, or throw on conflict. @param {Option} option @private
_registerOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_registerCommand(command) { const knownBy = (cmd) => { return [cmd.name()].concat(cmd.aliases()); }; const alreadyUsed = knownBy(command).find((name) => this._findCommand(name), ); if (alreadyUsed) { const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|'); const newCmd = knownBy(command).join('|'); throw new Error( `cannot add command '${newCmd}' as already have command '${existingCmd}'`, ); } this._initCommandGroup(command); this.commands.push(command); }
Check for command name and alias conflicts with existing commands. Register command if no conflicts found, or throw on conflict. @param {Command} command @private
_registerCommand
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
addOption(option) { this._registerOption(option); const oname = option.name(); const name = option.attributeName(); // store default value if (option.negate) { // --no-foo is special and defaults foo to true, unless a --foo option is already defined const positiveLongFlag = option.long.replace(/^--no-/, '--'); if (!this._findOption(positiveLongFlag)) { this.setOptionValueWithSource( name, option.defaultValue === undefined ? true : option.defaultValue, 'default', ); } } else if (option.defaultValue !== undefined) { this.setOptionValueWithSource(name, option.defaultValue, 'default'); } // handler for cli and env supplied values const handleOptionValue = (val, invalidValueMessage, valueSource) => { // val is null for optional option used without an optional-argument. // val is undefined for boolean and negated option. if (val == null && option.presetArg !== undefined) { val = option.presetArg; } // custom processing const oldValue = this.getOptionValue(name); if (val !== null && option.parseArg) { val = this._callParseArg(option, val, oldValue, invalidValueMessage); } else if (val !== null && option.variadic) { val = option._concatValue(val, oldValue); } // Fill-in appropriate missing values. Long winded but easy to follow. if (val == null) { if (option.negate) { val = false; } else if (option.isBoolean() || option.optional) { val = true; } else { val = ''; // not normal, parseArg might have failed or be a mock function for testing } } this.setOptionValueWithSource(name, val, valueSource); }; this.on('option:' + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; handleOptionValue(val, invalidValueMessage, 'cli'); }); if (option.envVar) { this.on('optionEnv:' + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; handleOptionValue(val, invalidValueMessage, 'env'); }); } return this; }
Add an option. @param {Option} option @return {Command} `this` command for chaining
addOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_optionEx(config, flags, description, fn, defaultValue) { if (typeof flags === 'object' && flags instanceof Option) { throw new Error( 'To add an Option object use addOption() instead of option() or requiredOption()', ); } const option = this.createOption(flags, description); option.makeOptionMandatory(!!config.mandatory); if (typeof fn === 'function') { option.default(defaultValue).argParser(fn); } else if (fn instanceof RegExp) { // deprecated const regex = fn; fn = (val, def) => { const m = regex.exec(val); return m ? m[0] : def; }; option.default(defaultValue).argParser(fn); } else { option.default(fn); } return this.addOption(option); }
Internal implementation shared by .option() and .requiredOption() @return {Command} `this` command for chaining @private
_optionEx
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
option(flags, description, parseArg, defaultValue) { return this._optionEx({}, flags, description, parseArg, defaultValue); }
Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required option-argument is indicated by `<>` and an optional option-argument by `[]`. See the README for more details, and see also addOption() and requiredOption(). @example program .option('-p, --pepper', 'add pepper') .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function @param {string} flags @param {string} [description] @param {(Function|*)} [parseArg] - custom option processing function or default value @param {*} [defaultValue] @return {Command} `this` command for chaining
option
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
requiredOption(flags, description, parseArg, defaultValue) { return this._optionEx( { mandatory: true }, flags, description, parseArg, defaultValue, ); }
Add a required option which must have a value after parsing. This usually means the option must be specified on the command line. (Otherwise the same as .option().) The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. @param {string} flags @param {string} [description] @param {(Function|*)} [parseArg] - custom option processing function or default value @param {*} [defaultValue] @return {Command} `this` command for chaining
requiredOption
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
enablePositionalOptions(positional = true) { this._enablePositionalOptions = !!positional; return this; }
Enable positional options. Positional means global options are specified before subcommands which lets subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. The default behaviour is non-positional and global options may appear anywhere on the command line. @param {boolean} [positional] @return {Command} `this` command for chaining
enablePositionalOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
passThroughOptions(passThrough = true) { this._passThroughOptions = !!passThrough; this._checkForBrokenPassThrough(); return this; }
Pass through options that come after command-arguments rather than treat them as command-options, so actual command-options come before command-arguments. Turning this on for a subcommand requires positional options to have been enabled on the program (parent commands). The default behaviour is non-positional and options may appear before or after command-arguments. @param {boolean} [passThrough] for unknown options. @return {Command} `this` command for chaining
passThroughOptions
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
storeOptionsAsProperties(storeAsProperties = true) { if (this.options.length) { throw new Error('call .storeOptionsAsProperties() before adding options'); } if (Object.keys(this._optionValues).length) { throw new Error( 'call .storeOptionsAsProperties() before setting option values', ); } this._storeOptionsAsProperties = !!storeAsProperties; return this; }
Whether to store option values as properties on command object, or store separately (specify false). In both cases the option values can be accessed using .opts(). @param {boolean} [storeAsProperties=true] @return {Command} `this` command for chaining
storeOptionsAsProperties
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValue(key) { if (this._storeOptionsAsProperties) { return this[key]; } return this._optionValues[key]; }
Retrieve option value. @param {string} key @return {object} value
getOptionValue
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
setOptionValue(key, value) { return this.setOptionValueWithSource(key, value, undefined); }
Store option value. @param {string} key @param {object} value @return {Command} `this` command for chaining
setOptionValue
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
setOptionValueWithSource(key, value, source) { if (this._storeOptionsAsProperties) { this[key] = value; } else { this._optionValues[key] = value; } this._optionValueSources[key] = source; return this; }
Store option value and where the value came from. @param {string} key @param {object} value @param {string} source - expected values are default/config/env/cli/implied @return {Command} `this` command for chaining
setOptionValueWithSource
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValueSource(key) { return this._optionValueSources[key]; }
Get source of option value. Expected values are default | config | env | cli | implied @param {string} key @return {string}
getOptionValueSource
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
getOptionValueSourceWithGlobals(key) { // global overwrites local, like optsWithGlobals let source; this._getCommandAndAncestors().forEach((cmd) => { if (cmd.getOptionValueSource(key) !== undefined) { source = cmd.getOptionValueSource(key); } }); return source; }
Get source of option value. See also .optsWithGlobals(). Expected values are default | config | env | cli | implied @param {string} key @return {string}
getOptionValueSourceWithGlobals
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
_prepareUserArgs(argv, parseOptions) { if (argv !== undefined && !Array.isArray(argv)) { throw new Error('first parameter to parse must be array or undefined'); } parseOptions = parseOptions || {}; // auto-detect argument conventions if nothing supplied if (argv === undefined && parseOptions.from === undefined) { if (process.versions?.electron) { parseOptions.from = 'electron'; } // check node specific options for scenarios where user CLI args follow executable without scriptname const execArgv = process.execArgv ?? []; if ( execArgv.includes('-e') || execArgv.includes('--eval') || execArgv.includes('-p') || execArgv.includes('--print') ) { parseOptions.from = 'eval'; // internal usage, not documented } } // default to using process.argv if (argv === undefined) { argv = process.argv; } this.rawArgs = argv.slice(); // extract the user args and scriptPath let userArgs; switch (parseOptions.from) { case undefined: case 'node': this._scriptPath = argv[1]; userArgs = argv.slice(2); break; case 'electron': // @ts-ignore: because defaultApp is an unknown property if (process.defaultApp) { this._scriptPath = argv[1]; userArgs = argv.slice(2); } else { userArgs = argv.slice(1); } break; case 'user': userArgs = argv.slice(0); break; case 'eval': userArgs = argv.slice(1); break; default: throw new Error( `unexpected parse option { from: '${parseOptions.from}' }`, ); } // Find default name for program from arguments. if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath); this._name = this._name || 'program'; return userArgs; }
Get user arguments from implied or explicit arguments. Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. @private
_prepareUserArgs
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
parse(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); this._parseCommand([], userArgs); return this; }
Parse `argv`, setting options and invoking commands when defined. Use parseAsync instead of parse if any of your action handlers are async. Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - `'user'`: just user arguments @example program.parse(); // parse process.argv and auto-detect electron and special node flags program.parse(process.argv); // assume argv[0] is app and argv[1] is script program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] @param {string[]} [argv] - optional, defaults to process.argv @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' @return {Command} `this` command for chaining
parse
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT
async parseAsync(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); await this._parseCommand([], userArgs); return this; }
Parse `argv`, setting options and invoking commands when defined. Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - `'user'`: just user arguments @example await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] @param {string[]} [argv] @param {object} [parseOptions] @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' @return {Promise}
parseAsync
javascript
tj/commander.js
lib/command.js
https://github.com/tj/commander.js/blob/master/lib/command.js
MIT