code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. var doc = getEventTargetDocument(nativeEventTarget); if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) { return; } // Only fire when selection has actually changed. var currentSelection = getSelection$1(activeElement$1); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect'); if (listeners.length > 0) { var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); event.target = activeElement$1; } }
Poll selection to see whether it's changed. @param {object} nativeEvent @param {object} nativeEventTarget @return {?SyntheticEvent}
constructSelectEvent ( dispatchQueue , nativeEvent , nativeEventTarget )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; switch (domEventName) { // Track the input node that has focus. case 'focusin': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement$1 = targetNode; activeElementInst$1 = targetInst; lastSelection = null; } break; case 'focusout': activeElement$1 = null; activeElementInst$1 = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'mousedown': mouseDown = true; break; case 'contextmenu': case 'mouseup': case 'dragend': mouseDown = false; constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); break; // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'selectionchange': if (skipSelectionChangeEvent) { break; } // falls through case 'keydown': case 'keyup': constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); }
This plugin creates an `onSelect` event that normalizes select events across form elements. Supported elements are: - input (see `isTextInputElement`) - textarea - contentEditable This differs from native browser implementations in the following ways: - Fires on contentEditable fields as well as inputs. - Fires for collapsed selection. - Fires after user input.
$3 ( dispatchQueue , domEventName , targetInst , nativeEvent , nativeEventTarget , eventSystemFlags , targetContainer )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; return prefixes;
Generate a mapping of standard vendor prefixes using the defined style property and event name. @param {string} styleProp @param {string} eventName @returns {object}
makePrefixMap ( styleProp , eventName )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return eventName;
Attempts to determine the correct vendor prefixed event name. @param {string} eventName @returns {string}
getVendorPrefixedEventName ( eventName )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function getLowestCommonAncestor(instA, instB) { var nodeA = instA; var nodeB = instB; var depthA = 0; for (var tempA = nodeA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = nodeB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { nodeA = getParent(nodeA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { nodeB = getParent(nodeB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) { return nodeA; } nodeA = getParent(nodeA); nodeB = getParent(nodeB); } return null;
Return the lowest common ancestor of A and B, or null if they are in different trees.
getLowestCommonAncestor ( instA , instB )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function getInstanceFromNode(node) { var inst = node[internalInstanceKey] || node[internalContainerInstanceKey]; if (inst) { if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) { return inst; } else { return null; } } return null;
Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent instance, or null if the node was not rendered by this React.
getInstanceFromNode ( node )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function getNodeFromInstance(inst) { if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. throw new Error('getNodeFromInstance: Invalid argument.');
Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding DOM node.
getNodeFromInstance ( inst )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
function warnOnInvalidKey(child, knownKeys, returnFiber) { { if (typeof child !== 'object' || child === null) { return knownKeys; } switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child, returnFiber); var key = child.key; if (typeof key !== 'string') { break; } if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } if (!knownKeys.has(key)) { knownKeys.add(key); break; } error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); break; case REACT_LAZY_TYPE: var payload = child._payload; var init = child._init; warnOnInvalidKey(init(payload), knownKeys, returnFiber); break; } } return knownKeys;
Warns if there is a duplicate or missing key
warnOnInvalidKey ( child , knownKeys , returnFiber )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-dom-v18.dev.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
MIT
(function(){'use strict';(function(c,x){"object"===typeof exports&&"undefined"!==typeof module?x(exports):"function"===typeof define&&define.amd?define(["exports"],x):(c=c||self,x(c.React={}))})(this,function(c){function x(a){if(null===a||"object"!==typeof a)return null;a=V&&a[V]||a["@@iterator"];return"function"===typeof a?a:null}function w(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Y(){}function K(a,b,e){this.props=a;this.context=b;this.refs=W;this.updater=e||X}function Z(a,b,
@license React react.production.min.js Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
(anonymous) ( c , x )
javascript
facebook/memlab
packages/lens/src/tests/lib/react-v18.prod.js
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-v18.prod.js
MIT
Terminal.bindCopy = function(document) { var window = document.defaultView; // if (!('onbeforecopy' in document)) { // // Copies to *only* the clipboard. // on(window, 'copy', function fn(ev) { // var term = Terminal.focus; // if (!term) return; // if (!term._selected) return; // var text = term.grabText( // term._selected.x1, term._selected.x2, // term._selected.y1, term._selected.y2); // term.emit('copy', text); // ev.clipboardData.setData('text/plain', text); // }); // return; // } // Copies to primary selection *and* clipboard. // NOTE: This may work better on capture phase, // or using the `beforecopy` event. on(window, 'copy', function(ev) { var term = Terminal.focus; if (!term) return; if (!term._selected) return; var textarea = term.getCopyTextarea(); var text = term.grabText( term._selected.x1, term._selected.x2, term._selected.y1, term._selected.y2); term.emit('copy', text); textarea.focus(); textarea.textContent = text; textarea.value = text; textarea.setSelectionRange(0, text.length); setTimeout(function() { term.element.focus(); term.focus(); }, 1); }); };
Copy Selection w/ Ctrl-C (Select Mode)
Terminal.bindCopy ( document )
javascript
facebook/memlab
website/src/components/TerminalReplay/lib/Term.js
https://github.com/facebook/memlab/blob/master/website/src/components/TerminalReplay/lib/Term.js
MIT
module.exports = function nomralizeTypeSpeed(events, speedFactor = 1) { const deltas = [0]; for (let i = 1; i < events.length; ++i) { deltas[i] = events[i].time - events[i - 1].time; const content = events[i].content; // if this event has a manually defined time // gap to the previous event if ('timeGapFromPreviousStep' in events[i]) { deltas[i] = events[i].timeGapFromPreviousStep; // if this is an "Enter" hit by user input } else if (content === '\r\n' && events[i - 1].content.length === 1) { // if the "Enter" is ending a comment (starts with a "#") // and the next line is also a comment if (i + 2 < events.length && events[i + 2].content === '#') { deltas[i] = 600; } else { deltas[i] = 1000; } // speed up the empty space, which feel more natural } else if (content === ' ') { deltas[i] = 30; // if repeatedly typing the same letter, it should be faster } else if (content.length === 1 && content === events[i - 1].content) { deltas[i] = 90; // randomize the type speed a little to feel less like a machine } else if (content.length === 1) { // eslint-disable-next-line fb-www/unsafe-math-random deltas[i] = 110 + Math.random(0, 40); // characters that needs more than 1 keystroke to type if (shiftCharacters.has(content)) { // eslint-disable-next-line fb-www/unsafe-math-random deltas[i] += 70 + Math.random(0, 20); } } } for (let i = 1; i < events.length; ++i) { events[i].time = events[i - 1].time + Math.floor(deltas[i] / speedFactor); } return events; };
normalize the typing speed and make the type input feel more natural
nomralizeTypeSpeed ( events , speedFactor = 1 )
javascript
facebook/memlab
website/src/lib/TypeSpeedNormalization.js
https://github.com/facebook/memlab/blob/master/website/src/lib/TypeSpeedNormalization.js
MIT
(function () { let lastTime = 0; const vendors = ['ms', 'moz', 'webkit', 'o']; for (let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function (callback, element) { const currentTime = new Date().getTime(); const timeToCall = Math.max(0, 16 - (currentTime - lastTime)); const id = window.setTimeout(function () { callback(currentTime + timeToCall); }, timeToCall); lastTime = currentTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function (id) { clearTimeout(id); }; } })();
Request Animation Frame Polyfill. @author Paul Irish @see https://gist.github.com/paulirish/1579671
(anonymous) ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Color = function (hex, opacity) { this.rgba = FSS.Vector4.create(); this.hex = hex || '#000000'; this.opacity = FSS.Utils.isNumber(opacity) ? opacity : 1; this.set(this.hex, this.opacity); };
@class Color @author Matthew Wagerfield
FSS.Color ( hex , opacity )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Object = function () { this.position = FSS.Vector3.create(); };
@class Object @author Matthew Wagerfield
FSS.Object ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Light = function (ambient, diffuse) { FSS.Object.call(this); this.ambient = new FSS.Color(ambient || '#FFFFFF'); this.diffuse = new FSS.Color(diffuse || '#FFFFFF'); this.ray = FSS.Vector3.create(); };
@class Light @author Matthew Wagerfield
FSS.Light ( ambient , diffuse )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Vertex = function (x, y, z) { this.position = FSS.Vector3.create(x, y, z); };
@class Vertex @author Matthew Wagerfield
FSS.Vertex ( x , y , z )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Triangle = function (a, b, c) { this.a = a || new FSS.Vertex(); this.b = b || new FSS.Vertex(); this.c = c || new FSS.Vertex(); this.vertices = [this.a, this.b, this.c]; this.u = FSS.Vector3.create(); this.v = FSS.Vector3.create(); this.centroid = FSS.Vector3.create(); this.normal = FSS.Vector3.create(); this.color = new FSS.Color(); this.polygon = document.createElementNS(FSS.SVGNS, 'polygon'); this.polygon.setAttributeNS(null, 'stroke-linejoin', 'round'); this.polygon.setAttributeNS(null, 'stroke-miterlimit', '1'); this.polygon.setAttributeNS(null, 'stroke-width', '1'); this.computeCentroid(); this.computeNormal(); };
@class Triangle @author Matthew Wagerfield
FSS.Triangle ( a , b , c )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Geometry = function () { this.vertices = []; this.triangles = []; this.dirty = false; };
@class Geometry @author Matthew Wagerfield
FSS.Geometry ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Plane = function (width, height, segments, slices) { FSS.Geometry.call(this); this.width = width || 100; this.height = height || 100; this.segments = segments || 4; this.slices = slices || 4; this.segmentWidth = this.width / this.segments; this.sliceHeight = this.height / this.slices; // Cache Variables let x, y, v0, v1, v2, v3, vertex, triangle, vertices = [], offsetX = this.width * -0.5, offsetY = this.height * 0.5; // Add Vertices for (x = 0; x <= this.segments; x++) { vertices.push([]); for (y = 0; y <= this.slices; y++) { vertex = new FSS.Vertex( offsetX + x * this.segmentWidth, offsetY - y * this.sliceHeight, ); vertices[x].push(vertex); this.vertices.push(vertex); } } // Add Triangles for (x = 0; x < this.segments; x++) { for (y = 0; y < this.slices; y++) { v0 = vertices[x + 0][y + 0]; v1 = vertices[x + 0][y + 1]; v2 = vertices[x + 1][y + 0]; v3 = vertices[x + 1][y + 1]; const t0 = new FSS.Triangle(v0, v1, v2); const t1 = new FSS.Triangle(v2, v1, v3); this.triangles.push(t0, t1); } } };
@class Plane @author Matthew Wagerfield
FSS.Plane ( width , height , segments , slices )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Material = function (ambient, diffuse) { this.ambient = new FSS.Color(ambient || '#444444'); this.diffuse = new FSS.Color(diffuse || '#FFFFFF'); this.slave = new FSS.Color(); };
@class Material @author Matthew Wagerfield
FSS.Material ( ambient , diffuse )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Mesh = function (geometry, material) { FSS.Object.call(this); this.geometry = geometry || new FSS.Geometry(); this.material = material || new FSS.Material(); this.side = FSS.FRONT; this.visible = true; };
@class Mesh @author Matthew Wagerfield
FSS.Mesh ( geometry , material )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Scene = function () { this.meshes = []; this.lights = []; };
@class Scene @author Matthew Wagerfield
FSS.Scene ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.Renderer = function () { this.width = 0; this.height = 0; this.halfWidth = 0; this.halfHeight = 0; };
@class Renderer @author Matthew Wagerfield
FSS.Renderer ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.CanvasRenderer = function () { FSS.Renderer.call(this); canvas = this.element = document.createElement('canvas'); this.element.style.display = 'block'; this.element.setAttribute('id', 'header-animation-canvas'); this.context = this.element.getContext('2d'); this.setSize(this.element.width, this.element.height); };
@class Canvas Renderer @author Matthew Wagerfield
FSS.CanvasRenderer ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.WebGLRenderer = function () { FSS.Renderer.call(this); this.element = document.createElement('canvas'); this.element.style.display = 'block'; // Set initial vertex and light count this.vertices = null; this.lights = null; // Create parameters object const parameters = { preserveDrawingBuffer: false, premultipliedAlpha: true, antialias: true, stencil: true, alpha: true, }; // Create and configure the gl context this.gl = this.getContext(this.element, parameters); // Set the internal support flag this.unsupported = !this.gl; // Setup renderer if (this.unsupported) { return 'WebGL is not supported by your browser.'; } else { this.gl.clearColor(0.0, 0.0, 0.0, 0.0); this.gl.enable(this.gl.DEPTH_TEST); this.setSize(this.element.width, this.element.height); } };
@class WebGL Renderer @author Matthew Wagerfield
FSS.WebGLRenderer ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
FSS.SVGRenderer = function () { FSS.Renderer.call(this); this.element = document.createElementNS(FSS.SVGNS, 'svg'); this.element.setAttribute('xmlns', FSS.SVGNS); this.element.setAttribute('version', '1.1'); this.element.style.display = 'block'; this.setSize(300, 150); };
@class SVG Renderer @author Matthew Wagerfield
FSS.SVGRenderer ( )
javascript
facebook/memlab
website/src/lib/ContainerAnimation.js
https://github.com/facebook/memlab/blob/master/website/src/lib/ContainerAnimation.js
MIT
WPAPI.prototype.transport = function( transport ) { // Local reference to avoid need to reference via `this` inside forEach const _options = this._options; // Attempt to use the default transport if no override was provided if ( ! _options.transport ) { _options.transport = this.constructor.transport ? Object.create( this.constructor.transport ) : {}; } // Whitelist the methods that may be applied [ 'get', 'head', 'post', 'put', 'delete' ].forEach( ( key ) => { if ( transport && transport[ key ] ) { _options.transport[ key ] = transport[ key ]; } } ); return this; };
Set custom transport methods to use when making HTTP requests against the API Pass an object with a function for one or many of "get", "post", "put", "delete" and "head" and that function will be called when making that type of request. The provided transport functions should take a WPRequest handler instance (_e.g._ the result of a `wp.posts()...` chain or any other chaining request handler) as their first argument; a `data` object as their second argument (for POST, PUT and DELETE requests); and an optional callback as their final argument. Transport methods should invoke the callback with the response data (or error, as appropriate), and should also return a Promise. @example <caption>showing how a cache hit (keyed by URI) could short-circuit a get request</caption> var site = new WPAPI({ endpoint: 'http://my-site.com/wp-json' }); // Overwrite the GET behavior to inject a caching layer site.transport({ get: function( wpreq ) { var result = cache[ wpreq ]; // If a cache hit is found, return it via the same promise // signature as that of the default transport method if ( result ) { return Promise.resolve( result ); } // Delegate to default transport if no cached data was found return this.constructor.transport.get( wpreq ).then(function( result ) { cache[ wpreq ] = result; return result; }); } }); This is advanced behavior; you will only need to utilize this functionality if your application has very specific HTTP handling or caching requirements. Refer to the "http-transport" module within this application for the code implementing the built-in transport methods. @memberof! WPAPI @method transport @chainable @param {Object} transport A dictionary of HTTP transport methods @param {Function} [transport.get] The function to use for GET requests @param {Function} [transport.post] The function to use for POST requests @param {Function} [transport.put] The function to use for PUT requests @param {Function} [transport.delete] The function to use for DELETE requests @param {Function} [transport.head] The function to use for HEAD requests @returns {WPAPI} The WPAPI instance, for chaining
WPAPI.prototype.transport ( transport )
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
WPAPI.prototype.url = function( url ) { return new WPRequest( { ...this._options, endpoint: url, } ); };
Generate a request against a completely arbitrary endpoint, with no assumptions about or mutation of path, filtering, or query parameters. This request is not restricted to the endpoint specified during WPAPI object instantiation. @example Generate a request to the explicit URL "http://your.website.com/wp-json/some/custom/path" wp.url( 'http://your.website.com/wp-json/some/custom/path' ).get()... @memberof! WPAPI @param {String} url The URL to request @returns {WPRequest} A WPRequest object bound to the provided URL
WPAPI.prototype.url ( url )
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
WPAPI.prototype.root = function( relativePath ) { relativePath = relativePath || ''; const options = { ...this._options, }; // Request should be const request = new WPRequest( options ); // Set the path template to the string passed in request._path = { '0': relativePath }; return request; };
Generate a query against an arbitrary path on the current endpoint. This is useful for requesting resources at custom WP-API endpoints, such as WooCommerce's `/products`. @memberof! WPAPI @param {String} [relativePath] An endpoint-relative path to which to bind the request @returns {WPRequest} A request object
WPAPI.prototype.root ( relativePath )
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
WPAPI.prototype.bootstrap = function( routes ) { let routesByNamespace; let endpointFactoriesByNamespace; if ( ! routes ) { // Auto-generate default endpoint factories if they are not already available if ( ! defaultEndpointFactories ) { routesByNamespace = buildRouteTree( defaultRoutes ); defaultEndpointFactories = generateEndpointFactories( routesByNamespace ); } endpointFactoriesByNamespace = defaultEndpointFactories; } else { routesByNamespace = buildRouteTree( routes ); endpointFactoriesByNamespace = generateEndpointFactories( routesByNamespace ); } // For each namespace for which routes were identified, store the generated // route handlers on the WPAPI instance's private _ns dictionary. These namespaced // handler methods can be accessed by calling `.namespace( str )` on the // client instance and passing a registered namespace string. // Handlers for default (wp/v2) routes will also be assigned to the WPAPI // client instance object itself, for brevity. return objectReduce( endpointFactoriesByNamespace, ( wpInstance, endpointFactories, namespace ) => { // Set (or augment) the route handler factories for this namespace. wpInstance._ns[ namespace ] = objectReduce( endpointFactories, ( nsHandlers, handlerFn, methodName ) => { nsHandlers[ methodName ] = handlerFn; return nsHandlers; }, wpInstance._ns[ namespace ] || { // Create all namespace dictionaries with a direct reference to the main WPAPI // instance's _options property so that things like auth propagate properly _options: wpInstance._options, } ); // For the default namespace, e.g. "wp/v2" at the time this comment was // written, ensure all methods are assigned to the root client object itself // in addition to the private _ns dictionary: this is done so that these // methods can be called with e.g. `wp.posts()` and not the more verbose // `wp.namespace( 'wp/v2' ).posts()`. if ( namespace === apiDefaultNamespace ) { Object.keys( wpInstance._ns[ namespace ] ).forEach( ( methodName ) => { wpInstance[ methodName ] = wpInstance._ns[ namespace ][ methodName ]; } ); } return wpInstance; }, this ); };
Deduce request methods from a provided API root JSON response object's routes dictionary, and assign those methods to the current instance. If no routes dictionary is provided then the instance will be bootstrapped with route handlers for the default API endpoints only. This method is called automatically during WPAPI instance creation. @memberof! WPAPI @chainable @param {Object} routes The "routes" object from the JSON object returned from the root API endpoint of a WP site, which should be a dictionary of route definition objects keyed by the route's regex pattern @returns {WPAPI} The bootstrapped WPAPI client instance (for chaining or assignment)
WPAPI.prototype.bootstrap ( routes )
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
WPAPI.prototype.namespace = function( namespace ) { if ( ! this._ns[ namespace ] ) { throw new Error( 'Error: namespace ' + namespace + ' is not recognized' ); } return this._ns[ namespace ]; };
Access API endpoint handlers from a particular API namespace object @example wp.namespace( 'myplugin/v1' ).author()... // Default WP endpoint handlers are assigned to the wp instance itself. // These are equivalent: wp.namespace( 'wp/v2' ).posts()... wp.posts()... @memberof! WPAPI @param {string} namespace A namespace string @returns {Object} An object of route endpoint handler methods for the routes within the specified namespace
WPAPI.prototype.namespace ( namespace )
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
WPAPI.site = ( endpoint, routes ) => { return new WPAPI( { endpoint: endpoint, routes: routes, } ); };
Convenience method for making a new WPAPI instance for a given API root @example These are equivalent: var wp = new WPAPI({ endpoint: 'http://my.blog.url/wp-json' }); var wp = WPAPI.site( 'http://my.blog.url/wp-json' ); `WPAPI.site` can take an optional API root response JSON object to use when bootstrapping the client's endpoint handler methods: if no second parameter is provided, the client instance is assumed to be using the default API with no additional plugins and is initialized with handlers for only those default API routes. @example These are equivalent: // {...} means the JSON output of http://my.blog.url/wp-json var wp = new WPAPI({ endpoint: 'http://my.blog.url/wp-json', json: {...} }); var wp = WPAPI.site( 'http://my.blog.url/wp-json', {...} ); @memberof! WPAPI @static @param {String} endpoint The URI for a WP-API endpoint @param {Object} routes The "routes" object from the JSON object returned from the root API endpoint of a WP site, which should be a dictionary of route definition objects keyed by the route's regex pattern @returns {WPAPI} A new WPAPI instance, bound to the provided endpoint
WPAPI.site
javascript
WP-API/node-wpapi
wpapi.js
https://github.com/WP-API/node-wpapi/blob/master/wpapi.js
MIT
function _setHeaders( request, options ) { // If there's no headers, do nothing if ( ! options.headers ) { return request; } return objectReduce( options.headers, ( request, value, key ) => request.set( key, value ), request ); }
Set any provided headers on the outgoing request object. Runs after _auth. @method _setHeaders @private @param {Object} request A superagent request object @param {Object} options A WPRequest _options object @param {Object} A superagent request object, with any available headers set
_setHeaders ( request , options )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _auth( request, options, forceAuthentication ) { // If we're not supposed to authenticate, don't even start if ( ! forceAuthentication && ! options.auth && ! options.nonce ) { return request; } // Enable nonce in options for Cookie authentication http://wp-api.org/guides/authentication.html if ( options.nonce ) { request.set( 'X-WP-Nonce', options.nonce ); return request; } // Retrieve the username & password from the request options if they weren't provided const username = options.username; const password = options.password; // If no username or no password, can't authenticate if ( ! username || ! password ) { return request; } // Can authenticate: set basic auth parameters on the request return request.auth( username, password ); }
Conditionally set basic authentication on a server request object. @method _auth @private @param {Object} request A superagent request object @param {Object} options A WPRequest _options object @param {Boolean} forceAuthentication whether to force authentication on the request @param {Object} A superagent request object, conditionally configured to use basic auth
_auth ( request , options , forceAuthentication )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function extractResponseBody( response ) { let responseBody = response.body; if ( isEmptyObject( responseBody ) && response.type === 'text/html' ) { // Response may have come back as HTML due to caching plugin; try to parse // the response text into JSON try { responseBody = JSON.parse( response.text ); } catch ( e ) { // Swallow errors, it's OK to fall back to returning the body } } return responseBody; }
Extract the body property from the superagent response, or else try to parse the response text to get a JSON object. @private @param {Object} response The response object from the HTTP request @param {String} response.text The response content as text @param {Object} response.body The response content as a JS object @returns {Object} The response content as a JS object
extractResponseBody ( response )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function invokeAndPromisify( request, transform ) { return new Promise( ( resolve, reject ) => { // Fire off the result request.end( ( err, result ) => { // Return the results as a promise if ( err || result.error ) { reject( err || result.error ); } else { resolve( result ); } } ); } ).then( transform ).catch( ( err ) => { // If the API provided an error object, it will be available within the // superagent response object as response.body (containing the response // JSON). If that object exists, it will have a .code property if it is // truly an API error (non-API errors will not have a .code). if ( err.response && err.response.body && err.response.body.code ) { // Forward API error response JSON on to the calling method: omit // all transport-specific (superagent-specific) properties err = err.response.body; } // Re-throw the error so that it can be handled by a Promise .catch or .then throw err; } ); }
Submit the provided superagent request object and return a promise which resolves to the response from the HTTP request. @private @param {Object} request A superagent request object @param {Function} transform A function to transform the result data @returns {Promise} A promise to the superagent request
invokeAndPromisify ( request , transform )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function returnBody( wpreq, result ) { const body = extractResponseBody( result ); const _paging = createPaginationObject( result, wpreq._options, wpreq.transport ); if ( _paging ) { body._paging = _paging; } return body; }
Return the body of the request, augmented with pagination information if the result is a paged collection. @private @param {WPRequest} wpreq The WPRequest representing the returned HTTP response @param {Object} result The results from the HTTP request @returns {Object} The "body" property of the result, conditionally augmented with pagination information if the result is a partial collection.
returnBody ( wpreq , result )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function returnHeaders( result ) { return result.headers; }
Extract and return the headers property from a superagent response object @private @param {Object} result The results from the HTTP request @returns {Object} The "headers" property of the result
returnHeaders ( result )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _httpGet( wpreq ) { checkMethodSupport( 'get', wpreq ); const url = wpreq.toString(); let request = _auth( agent.get( url ), wpreq._options ); request = _setHeaders( request, wpreq._options ); return invokeAndPromisify( request, returnBody.bind( null, wpreq ) ); }
@method get @async @param {WPRequest} wpreq A WPRequest query object @returns {Promise} A promise to the results of the HTTP request
_httpGet ( wpreq )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _httpPost( wpreq, data ) { checkMethodSupport( 'post', wpreq ); const url = wpreq.toString(); data = data || {}; let request = _auth( agent.post( url ), wpreq._options, true ); request = _setHeaders( request, wpreq._options ); if ( wpreq._attachment ) { // Data must be form-encoded alongside image attachment request = objectReduce( data, ( req, value, key ) => req.field( key, value ), request.attach( 'file', wpreq._attachment, wpreq._attachmentName ) ); } else { request = request.send( data ); } return invokeAndPromisify( request, returnBody.bind( null, wpreq ) ); }
Invoke an HTTP "POST" request against the provided endpoint @method post @async @param {WPRequest} wpreq A WPRequest query object @param {Object} data The data for the POST request @returns {Promise} A promise to the results of the HTTP request
_httpPost ( wpreq , data )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _httpPut( wpreq, data ) { checkMethodSupport( 'put', wpreq ); const url = wpreq.toString(); data = data || {}; let request = _auth( agent.put( url ), wpreq._options, true ).send( data ); request = _setHeaders( request, wpreq._options ); return invokeAndPromisify( request, returnBody.bind( null, wpreq ) ); }
@method put @async @param {WPRequest} wpreq A WPRequest query object @param {Object} data The data for the PUT request @returns {Promise} A promise to the results of the HTTP request
_httpPut ( wpreq , data )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _httpDelete( wpreq, data ) { checkMethodSupport( 'delete', wpreq ); const url = wpreq.toString(); let request = _auth( agent.del( url ), wpreq._options, true ).send( data ); request = _setHeaders( request, wpreq._options ); return invokeAndPromisify( request, returnBody.bind( null, wpreq ) ); }
@method delete @async @param {WPRequest} wpreq A WPRequest query object @param {Object} [data] Data to send along with the DELETE request @returns {Promise} A promise to the results of the HTTP request
_httpDelete ( wpreq , data )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
function _httpHead( wpreq ) { checkMethodSupport( 'head', wpreq ); const url = wpreq.toString(); let request = _auth( agent.head( url ), wpreq._options ); request = _setHeaders( request, wpreq._options ); return invokeAndPromisify( request, returnHeaders ); }
@method head @async @param {WPRequest} wpreq A WPRequest query object @returns {Promise} A promise to the header results of the HTTP request
_httpHead ( wpreq )
javascript
WP-API/node-wpapi
superagent/superagent-transport.js
https://github.com/WP-API/node-wpapi/blob/master/superagent/superagent-transport.js
MIT
module.exports = ( property, collection ) => collection .map( item => item[ property ].rendered );
This method is a super-pluck capable of grabbing the rendered version of a nested property on a WP API response object. Inspecting a collection of human-readable properties is usually a more comprehensible way to validate that the right results were returned than using IDs or arbitrary values. @example <caption>Pluck the rendered titles from the post</caption> const titles = getRenderedProp( collection, 'title' ); @example <caption>Create a bound variant that always plucks titles</caption> const getTitles = getRenderedProp.bind( null, 'title' ); const titles = getTitles( collection ); @private @param {String} property The name of the rendered property to pluck @param {Object[]} collection An array of response objects whence to pluck @returns {String[]} The collection of values for the rendered variants of the specified response object property
module.exports
javascript
WP-API/node-wpapi
tests/helpers/get-rendered-prop.js
https://github.com/WP-API/node-wpapi/blob/master/tests/helpers/get-rendered-prop.js
MIT
module.exports = ( property, collection ) => collection .map( item => item[ property ] );
This is a curry-able pluck function, that is all. Inspecting a collection of human-readable strings is usually a more comprehensible way to validate the right results were returned than using arbitrary values. @example <caption>Pluck the slugs titles from a collection of terms</caption> const slugs = getProp( collection, 'slug' ); @example <caption>Create a bound variant that always plucks .name</caption> const getNames = getProp.bind( null, 'name' ); const names = getNames( collection ); @private @param {String} property The name of the property to pluck @param {Object[]} collection An array of response objects whence to pluck @returns {String[]} The values of that property from each collection member
module.exports
javascript
WP-API/node-wpapi
tests/helpers/get-prop.js
https://github.com/WP-API/node-wpapi/blob/master/tests/helpers/get-prop.js
MIT
function _setHeaders( config, options ) { // If there's no headers, do nothing if ( ! options.headers ) { return config; } return objectReduce( options.headers, ( config, value, key ) => _setHeader( config, key, value ), config, ); }
Set any provided headers on the outgoing request object. Runs after _auth. @method _setHeaders @private @param {Object} config A fetch request configuration object @param {Object} options A WPRequest _options object @param {Object} A fetch config object, with any available headers set
_setHeaders ( config , options )
javascript
WP-API/node-wpapi
fetch/fetch-transport.js
https://github.com/WP-API/node-wpapi/blob/master/fetch/fetch-transport.js
MIT
function _auth( config, options, forceAuthentication ) { // If we're not supposed to authenticate, don't even start if ( ! forceAuthentication && ! options.auth && ! options.nonce ) { return config; } // Enable nonce in options for Cookie authentication http://wp-api.org/guides/authentication.html if ( options.nonce ) { config.credentials = 'same-origin'; return _setHeader( config, 'X-WP-Nonce', options.nonce ); } // If no username or no password, can't authenticate if ( ! options.username || ! options.password ) { return config; } // Can authenticate: set basic auth parameters on the config let authorization = `${ options.username }:${ options.password }`; if ( global.Buffer ) { authorization = global.Buffer.from( authorization ).toString( 'base64' ); } else if ( global.btoa ) { authorization = global.btoa( authorization ); } return _setHeader( config, 'Authorization', `Basic ${ authorization }` ); }
Conditionally set basic or nonce authentication on a server request object. @method _auth @private @param {Object} config A fetch request configuration object @param {Object} options A WPRequest _options object @param {Boolean} forceAuthentication whether to force authentication on the request @param {Object} A fetch request object, conditionally configured to use basic auth
_auth ( config , options , forceAuthentication )
javascript
WP-API/node-wpapi
fetch/fetch-transport.js
https://github.com/WP-API/node-wpapi/blob/master/fetch/fetch-transport.js
MIT
function getHeaders( response ) { const headers = {}; response.headers.forEach( ( value, key ) => { headers[ key ] = value; } ); return headers; }
Get the response headers as a regular JavaScript object. @param {Object} response Fetch response object.
getHeaders ( response )
javascript
WP-API/node-wpapi
fetch/fetch-transport.js
https://github.com/WP-API/node-wpapi/blob/master/fetch/fetch-transport.js
MIT
const promptYN = () => new Promise( ( resolve, reject ) => { prompt.message = ''; prompt.start(); prompt.get( [ 'y/n' ], ( err, result ) => { if ( err ) { return reject( err ); } resolve( AFFIRMATIVE_RE.test( result[ 'y/n' ] ) ); } ); } );
Helper method to request yes/no confirmation from the user, with some @private @returns {Promise} A promise that will resolve with a boolean true/false indicating whether assent was given
(anonymous)
javascript
WP-API/node-wpapi
build/scripts/release-docs.js
https://github.com/WP-API/node-wpapi/blob/master/build/scripts/release-docs.js
MIT
const ls = ( inputDir ) => { return new Promise( ( resolve, reject ) => { fs.readdir( inputDir, ( err, list ) => { if ( err ) { return reject( err ); } resolve( list ); } ); } ); };
Get the list of files in a directory, either as a list of file and subdir names or a list of absolute file system paths @private @param {string} inputDir The file system path to the directory to read @returns {Promise} A promise to the string array of file names
ls
javascript
WP-API/node-wpapi
build/scripts/release-docs.js
https://github.com/WP-API/node-wpapi/blob/master/build/scripts/release-docs.js
MIT
const runCommand = ( commandStr, otherArgs ) => { return new Promise( ( resolve, reject ) => { const commandArgs = commandStr.split( ' ' ); if ( Array.isArray( otherArgs ) ) { otherArgs.forEach( arg => commandArgs.push( arg ) ); } const command = commandArgs.shift(); const spawnedCommand = spawn( command, commandArgs, { cwd: projectRoot, stdio: 'inherit', } ); spawnedCommand.on( 'error', ( err ) => { reject( err ); } ); spawnedCommand.on( 'close', ( code ) => { return code ? reject( code ) : resolve(); } ); } ); };
Spawn a shell command, pipe its output to the parent process's stdio, and return a promise that will resolve or reject when the subprocess completes @private @param {string} commandStr A string containing a shell command to run @param {string[]} [otherArgs] Array of additional string arguments, so that quoted arguments with spaces like github commit messages will not be broken @returns {Promise} A promise that will resolve if the command executes successfully or reject if it errors
runCommand
javascript
WP-API/node-wpapi
build/scripts/release-docs.js
https://github.com/WP-API/node-wpapi/blob/master/build/scripts/release-docs.js
MIT
const runInSequence = ( arrOfFnsReturningPromises ) => { return arrOfFnsReturningPromises.reduce( ( lastStep, startNextStep ) => lastStep.then( startNextStep ), Promise.resolve() ); };
Helper function that takes in an array of functions that return promises, then executes those functions sequentially to execute each action @param {function[]} arrOfFnsReturningPromises An array of functions @returns {Promise} A promise that will resolve once all the promises returned by that function successfully complete
runInSequence
javascript
WP-API/node-wpapi
build/scripts/release-docs.js
https://github.com/WP-API/node-wpapi/blob/master/build/scripts/release-docs.js
MIT
const simplifyObject = ( obj ) => { // Pass through falsy values, Dates and RegExp values without modification if ( ! obj || obj instanceof Date || obj instanceof RegExp ) { return obj; } if ( obj.methods && obj.args ) { // If the key is an object with "methods" and "args" properties, only // include the full "args" object if "methods" contains GET. if ( ! obj.methods.map( str => str.toLowerCase() ).includes( 'get' ) ) { obj.args = {}; } } // Map arrays through simplifyObject if ( Array.isArray( obj ) ) { return obj.map( simplifyObject ); } // Reduce through objects to run each property through simplifyObject if ( typeof obj === 'object' ) { return objectReduce( obj, ( newObj, val, key ) => { // Omit _links objects entirely if ( key === '_links' ) { return newObj; } // If the key is "args", omit all keys of second-level descendants if ( key === 'args' ) { newObj.args = objectReduce( val, ( slimArgs, argVal, argKey ) => { slimArgs[ argKey ] = {}; return slimArgs; }, {} ); } else { // Pass all other objects through simplifyObject newObj[ key ] = simplifyObject( obj[ key ] ); } return newObj; }, {} ); } // All other types pass through without modification return obj; };
Walk through the keys and values of a provided object, removing any properties which would be inessential to the generation of the route tree used to deduce route handlers from a `wp-json/` root API endpoint. This module is not used by the wpapi module itself, but is rather a dependency of the script that is used to create the `endpoint-response.json` file that is shipped along with this module for use in generating the "default" routes. @param {*} obj An arbitrary JS value, probably an object @returns {*} The passed-in value, with non-essential args properties and all _links properties removes.
simplifyObject
javascript
WP-API/node-wpapi
build/scripts/simplify-object.js
https://github.com/WP-API/node-wpapi/blob/master/build/scripts/simplify-object.js
MIT
function reduceRouteTree( namespaces, routeObj, route ) { const nsForRoute = routeObj.namespace; const routeString = route // Strip the namespace from the route string (all routes should have the // format `/namespace/other/stuff`) @TODO: Validate this assumption .replace( '/' + nsForRoute + '/', '' ) // Also strip any trailing "/?": the slash is already optional and a single // question mark would break the regex parser .replace( /\/\?$/, '' ); // Split the routes up into hierarchical route components const routeComponents = splitPath( routeString ); // Do not make a namespace group for the API root // Do not add the namespace root to its own group // Do not take any action if routeString is empty if ( ! nsForRoute || '/' + nsForRoute === route || ! routeString ) { return namespaces; } // Ensure that the namespace object for this namespace exists ensure( namespaces, nsForRoute, {} ); // Get a local reference to namespace object const ns = namespaces[ nsForRoute ]; // The first element of the route tells us what type of resource this route // is for, e.g. "posts" or "comments": we build one handler per resource // type, so we group like resource paths together. const resource = routeComponents[0]; // @TODO: This code above currently precludes baseless routes, e.g. // myplugin/v2/(?P<resource>\w+) -- should those be supported? // Create an array to represent this resource, and ensure it is assigned // to the namespace object. The array will structure the "levels" (path // components and subresource types) of this resource's endpoint handler. ensure( ns, resource, {} ); const levels = ns[ resource ]; // Recurse through the route components, mutating levels with information about // each child node encountered while walking through the routes tree and what // arguments (parameters) are available for GET requests to this endpoint. routeComponents.reduce( reduceRouteComponents.bind( null, routeObj, levels ), levels ); return namespaces; }
@private @param {object} namespaces The memo object that becomes a dictionary mapping API namespaces to an object of the namespace's routes @param {object} routeObj A route definition object @param {string} route The string key of the `routeObj` route object @returns {object} The namespaces dictionary memo object
reduceRouteTree ( namespaces , routeObj , route )
javascript
WP-API/node-wpapi
lib/route-tree.js
https://github.com/WP-API/node-wpapi/blob/master/lib/route-tree.js
MIT
function buildRouteTree( routes ) { return objectReduce( routes, reduceRouteTree, {} ); }
Build a route tree by reducing over a routes definition object from the API root endpoint response object @method build @param {object} routes A dictionary of routes keyed by route regex strings @returns {object} A dictionary, keyed by namespace, of resource handler factory methods for each namespace's resources
buildRouteTree ( routes )
javascript
WP-API/node-wpapi
lib/route-tree.js
https://github.com/WP-API/node-wpapi/blob/master/lib/route-tree.js
MIT
function createEndpointRequest( handlerSpec, resource, namespace ) { // Create the constructor function for this endpoint class EndpointRequest extends WPRequest { constructor( options ) { super( options ); /** * Semi-private instance property specifying the available URL path options * for this endpoint request handler, keyed by ascending whole numbers. * * @property _levels * @type {object} * @private */ this._levels = handlerSpec._levels; // Configure handler for this endpoint's root URL path & set namespace this .setPathPart( 0, resource ) .namespace( namespace ); } } // Mix in all available shortcut methods for GET request query parameters that // are valid within this endpoint tree if ( typeof handlerSpec._getArgs === 'object' ) { Object.keys( handlerSpec._getArgs ).forEach( ( supportedQueryParam ) => { const mixinsForParam = mixins[ supportedQueryParam ]; // Only proceed if there is a mixin available AND the specified mixins will // not overwrite any previously-set prototype method if ( typeof mixinsForParam === 'object' ) { Object.keys( mixinsForParam ).forEach( ( methodName ) => { applyMixin( EndpointRequest.prototype, methodName, mixinsForParam[ methodName ] ); } ); } } ); } Object.keys( handlerSpec._setters ).forEach( ( setterFnName ) => { // Only assign setter functions if they do not overwrite preexisting methods if ( ! EndpointRequest.prototype[ setterFnName ] ) { EndpointRequest.prototype[ setterFnName ] = handlerSpec._setters[ setterFnName ]; } } ); return EndpointRequest; }
Create an endpoint request handler constructor for a specific resource tree @method create @param {Object} handlerSpec A resource handler specification object @param {String} resource The root resource of requests created from the returned factory @param {String} namespace The namespace string for the returned factory's handlers @returns {Function} A constructor inheriting from {@link WPRequest}
createEndpointRequest ( handlerSpec , resource , namespace )
javascript
WP-API/node-wpapi
lib/endpoint-request.js
https://github.com/WP-API/node-wpapi/blob/master/lib/endpoint-request.js
MIT
return function( val ) { this.setPathPart( nodeLevel, val ); if ( supportedMethods.length ) { this._supportedMethods = supportedMethods; } return this; };
Set a dymanic (named-group) path part of a query URL. @example // id() is a dynamic path part setter: wp.posts().id( 7 ); // Get posts/7 @chainable @param {String|Number} val The path part value to set @returns {Object} The handler instance (for chaining)
(anonymous) ( val )
javascript
WP-API/node-wpapi
lib/path-part-setter.js
https://github.com/WP-API/node-wpapi/blob/master/lib/path-part-setter.js
MIT
return function( val ) { // If the path part is not a namedGroup, it should have exactly one // entry in the names array: use that as the value for this setter, // as it will usually correspond to a collection endpoint. this.setPathPart( nodeLevel, nodeName ); // If this node has exactly one dynamic child, this method may act as // a setter for that child node. `dynamicChildLevel` will be falsy if the // node does not have a child or has multiple children. if ( val !== undefined && dynamicChildLevel ) { this.setPathPart( dynamicChildLevel, val ); } return this; };
Set a non-dymanic (non-named-group) path part of a query URL, and set the value of a subresource if an input value is provided and exactly one named-group child node exists. @example // revisions() is a non-dynamic path part setter: wp.posts().id( 4 ).revisions(); // Get posts/4/revisions wp.posts().id( 4 ).revisions( 1372 ); // Get posts/4/revisions/1372 @chainable @param {String|Number} [val] The path part value to set (if provided) for a subresource within this resource @returns {Object} The handler instance (for chaining)
(anonymous) ( val )
javascript
WP-API/node-wpapi
lib/path-part-setter.js
https://github.com/WP-API/node-wpapi/blob/master/lib/path-part-setter.js
MIT
function createPathPartSetter( node ) { // Local references to `node` properties used by returned functions const nodeLevel = node.level; const nodeName = node.names[ 0 ]; const supportedMethods = node.methods || []; const dynamicChildren = node.children ? Object.keys( node.children ) .map( key => node.children[ key ] ) .filter( childNode => ( childNode.namedGroup === true ) ) : []; const dynamicChild = dynamicChildren.length === 1 && dynamicChildren[ 0 ]; const dynamicChildLevel = dynamicChild && dynamicChild.level; if ( node.namedGroup ) { /** * Set a dymanic (named-group) path part of a query URL. * * @example * * // id() is a dynamic path part setter: * wp.posts().id( 7 ); // Get posts/7 * * @chainable * @param {String|Number} val The path part value to set * @returns {Object} The handler instance (for chaining) */ return function( val ) { this.setPathPart( nodeLevel, val ); if ( supportedMethods.length ) { this._supportedMethods = supportedMethods; } return this; }; } else { /** * Set a non-dymanic (non-named-group) path part of a query URL, and * set the value of a subresource if an input value is provided and * exactly one named-group child node exists. * * @example * * // revisions() is a non-dynamic path part setter: * wp.posts().id( 4 ).revisions(); // Get posts/4/revisions * wp.posts().id( 4 ).revisions( 1372 ); // Get posts/4/revisions/1372 * * @chainable * @param {String|Number} [val] The path part value to set (if provided) * for a subresource within this resource * @returns {Object} The handler instance (for chaining) */ return function( val ) { // If the path part is not a namedGroup, it should have exactly one // entry in the names array: use that as the value for this setter, // as it will usually correspond to a collection endpoint. this.setPathPart( nodeLevel, nodeName ); // If this node has exactly one dynamic child, this method may act as // a setter for that child node. `dynamicChildLevel` will be falsy if the // node does not have a child or has multiple children. if ( val !== undefined && dynamicChildLevel ) { this.setPathPart( dynamicChildLevel, val ); } return this; }; } }
Return a function to set part of the request URL path. Path part setter methods may be either dynamic (*i.e.* may represent a "named group") or non-dynamic (representing a static part of the URL, which is usually a collection endpoint of some sort). Which type of function is returned depends on whether a given route has one or many sub-resources. @alias module:lib/path-part-setter.create @param {Object} node An object representing a level of an endpoint path hierarchy @returns {Function} A path part setter function
createPathPartSetter ( node )
javascript
WP-API/node-wpapi
lib/path-part-setter.js
https://github.com/WP-API/node-wpapi/blob/master/lib/path-part-setter.js
MIT
function generateEndpointFactories( routesByNamespace ) { return objectReduce( routesByNamespace, ( namespaces, routeDefinitions, namespace ) => { // Create namespaces[ namespace ] = objectReduce( routeDefinitions, ( handlers, routeDef, resource ) => { const handlerSpec = createResourceHandlerSpec( routeDef, resource ); const EndpointRequest = createEndpointRequest( handlerSpec, resource, namespace ); // "handler" object is now fully prepared; create the factory method that // will instantiate and return a handler instance handlers[ resource ] = function( options ) { return new EndpointRequest( { ...this._options, ...options, } ); }; // Expose the constructor as a property on the factory function, so that // auto-generated endpoint request constructors may be further customized // when needed handlers[ resource ].Ctor = EndpointRequest; return handlers; }, {} ); return namespaces; }, {} ); }
Given an array of route definitions and a specific namespace for those routes, recurse through the node tree representing all possible routes within the provided namespace to define path value setters (and corresponding property validators) for all possible variants of each resource's API endpoints. @method generate @param {string} namespace The namespace string for these routes @param {object} routesByNamespace A dictionary of namespace - route definition object pairs as generated from buildRouteTree, where each route definition object is a dictionary keyed by route definition strings @returns {object} A dictionary of endpoint request handler factories
generateEndpointFactories ( routesByNamespace )
javascript
WP-API/node-wpapi
lib/endpoint-factories.js
https://github.com/WP-API/node-wpapi/blob/master/lib/endpoint-factories.js
MIT
function assignSetterFnForNode( handler, node ) { let setterFn; // For each node, add its handler to the relevant "level" representation addLevelOption( handler._levels, node.level, { component: node.component, validate: node.validate, methods: node.methods, } ); // First level is set implicitly, no dedicated setter needed if ( node.level > 0 ) { setterFn = createPathPartSetter( node ); node.names.forEach( ( name ) => { // Convert from snake_case to camelCase const setterFnName = name.replace( /[_-]+\w/g, match => match.replace( /[_-]+/, '' ).toUpperCase() ); // Don't overwrite previously-set methods if ( ! handler._setters[ setterFnName ] ) { handler._setters[ setterFnName ] = setterFn; } } ); } }
Assign a setter function for the provided node to the provided route handler object setters dictionary (mutates handler by reference). @private @param {Object} handler A route handler definition object @param {Object} node A route hierarchy level node object
assignSetterFnForNode ( handler , node )
javascript
WP-API/node-wpapi
lib/resource-handler-spec.js
https://github.com/WP-API/node-wpapi/blob/master/lib/resource-handler-spec.js
MIT
function extractSetterFromNode( handler, node ) { assignSetterFnForNode( handler, node ); if ( node.children ) { // Recurse down to this node's children Object.keys( node.children ).forEach( ( key ) => { extractSetterFromNode( handler, node.children[ key ] ); } ); } }
Walk the tree of a specific resource node to create the setter methods The API we want to produce from the node tree looks like this: wp.posts(); /wp/v2/posts wp.posts().id( 7 ); /wp/v2/posts/7 wp.posts().id( 7 ).revisions(); /wp/v2/posts/7/revisions wp.posts().id( 7 ).revisions( 8 ); /wp/v2/posts/7/revisions/8 ^ That last one's the tricky one: we can deduce that this parameter is "id", but that param will already be taken by the post ID, so sub-collections have to be set up as `.revisions()` to get the collection, and `.revisions( id )` to get a specific resource. @private @param {Object} node A node object @param {Object} [node.children] An object of child nodes // @returns {isLeaf} A boolean indicating whether the processed node is a leaf
extractSetterFromNode ( handler , node )
javascript
WP-API/node-wpapi
lib/resource-handler-spec.js
https://github.com/WP-API/node-wpapi/blob/master/lib/resource-handler-spec.js
MIT
function createNodeHandlerSpec( routeDefinition, resource ) { const handler = { // A "path" is an ordered (by key) set of values composed into the final URL _path: { '0': resource, }, // A "level" is a level-keyed object representing the valid options for // one level of the resource URL _levels: {}, // Objects that hold methods and properties which will be copied to // instances of this endpoint's handler _setters: {}, // Arguments (query parameters) that may be set in GET requests to endpoints // nested within this resource route tree, used to determine the mixins to // add to the request handler _getArgs: routeDefinition._getArgs, }; // Walk the tree Object.keys( routeDefinition ).forEach( ( routeDefProp ) => { if ( routeDefProp !== '_getArgs' ) { extractSetterFromNode( handler, routeDefinition[ routeDefProp ] ); } } ); return handler; }
Create a node handler specification object from a route definition object @name create @param {object} routeDefinition A route definition object @param {string} resource The string key of the resource for which to create a handler @returns {object} A handler spec object with _path, _levels and _setters properties
createNodeHandlerSpec ( routeDefinition , resource )
javascript
WP-API/node-wpapi
lib/resource-handler-spec.js
https://github.com/WP-API/node-wpapi/blob/master/lib/resource-handler-spec.js
MIT
function createPaginationObject( result, options, httpTransport ) { let _paging = null; if ( ! result.headers ) { // No headers: return as-is return _paging; } // Guard against capitalization inconsistencies in returned headers Object.keys( result.headers ).forEach( ( header ) => { result.headers[ header.toLowerCase() ] = result.headers[ header ]; } ); if ( ! result.headers[ 'x-wp-totalpages' ] ) { // No paging: return as-is return _paging; } const totalPages = +result.headers[ 'x-wp-totalpages' ]; if ( ! totalPages || totalPages === 0 ) { // No paging: return as-is return _paging; } // Decode the link header object const links = result.headers.link ? parseLinkHeader( result.headers.link ) : {}; // Store pagination data from response headers on the response collection _paging = { total: +result.headers[ 'x-wp-total' ], totalPages: totalPages, links: links, }; // Create a WPRequest instance pre-bound to the "next" page, if available if ( links.next ) { _paging.next = new WPRequest( { ...options, transport: httpTransport, endpoint: links.next, } ); } // Create a WPRequest instance pre-bound to the "prev" page, if available if ( links.prev ) { _paging.prev = new WPRequest( { ...options, transport: httpTransport, endpoint: links.prev, } ); } return _paging; }
If the response is not paged, return the body as-is. If pagination information is present in the response headers, parse those headers into a custom `_paging` property on the response body. `_paging` contains links to the previous and next pages in the collection, as well as metadata about the size and number of pages in the collection. The structure of the `_paging` property is as follows: - `total` {Integer} The total number of records in the collection - `totalPages` {Integer} The number of pages available - `links` {Object} The parsed "links" headers, separated into individual URI strings - `next` {WPRequest} A WPRequest object bound to the "next" page (if page exists) - `prev` {WPRequest} A WPRequest object bound to the "previous" page (if page exists) @private @param {Object} result The response object from the HTTP request @param {Object} options The options hash from the original request @param {String} options.endpoint The base URL of the requested API endpoint @param {Object} httpTransport The HTTP transport object used by the original request @returns {Object} The pagination metadata object for this HTTP request, or else null
createPaginationObject ( result , options , httpTransport )
javascript
WP-API/node-wpapi
lib/pagination.js
https://github.com/WP-API/node-wpapi/blob/master/lib/pagination.js
MIT
WPAPI.discover = ( url ) => { // Use WPAPI.site to make a request using the defined transport const req = WPAPI.site( url ).root().param( 'rest_route', '/' ); return req.get().then( ( apiRootJSON ) => { const routes = apiRootJSON.routes; return new WPAPI( { // Derive the endpoint from the self link for the / root endpoint: routes['/']._links.self, // Bootstrap returned WPAPI instance with the discovered routes routes: routes, } ); } ); };
Take an arbitrary WordPress site, deduce the WP REST API root endpoint, query that endpoint, and parse the response JSON. Use the returned JSON response to instantiate a WPAPI instance bound to the provided site. @memberof! WPAPI @static @param {string} url A URL within a REST API-enabled WordPress website @returns {Promise} A promise that resolves to a configured WPAPI instance bound to the deduced endpoint, or rejected if an endpoint is not found or the library is unable to parse the provided endpoint.
WPAPI.discover
javascript
WP-API/node-wpapi
lib/bind-transport.js
https://github.com/WP-API/node-wpapi/blob/master/lib/bind-transport.js
MIT
module.exports = ( a, b ) => { if ( a > b ) { return 1; } if ( a < b ) { return -1; } return 0; };
Utility function for sorting arrays of numbers or strings. @module util/alphanumeric-sort @param {String|Number} a The first comparator operand @param {String|Number} a The second comparator operand @returns -1 if the values are backwards, 1 if they're ordered, and 0 if they're the same
module.exports
javascript
WP-API/node-wpapi
lib/util/alphanumeric-sort.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/alphanumeric-sort.js
MIT
module.exports = ( obj ) => { // eslint-disable-next-line no-console console.log( inspect( obj, { colors: true, depth: null, } ) ); };
Helper method for debugging only: use util.inspect to log a full object @module util/log-obj @private @param {object} obj The object to log @returns {void}
module.exports
javascript
WP-API/node-wpapi
lib/util/log-obj.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/log-obj.js
MIT
module.exports = ( method, request ) => { if ( request._supportedMethods.indexOf( method.toLowerCase() ) === -1 ) { throw new Error( 'Unsupported method; supported methods are: ' + request._supportedMethods.join( ', ' ) ); } return true; };
Verify that a specific HTTP method is supported by the provided WPRequest @module util/check-method-support @param {String} method An HTTP method to check ('get', 'post', etc) @param {WPRequest} request A WPRequest object with a _supportedMethods array @returns true iff the method is within request._supportedMethods
module.exports
javascript
WP-API/node-wpapi
lib/util/check-method-support.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/check-method-support.js
MIT
module.exports = ( obj, iterator, initialState ) => Object .keys( obj ) .reduce( ( memo, key ) => iterator( memo, obj[ key ], key ), initialState );
Utility method to permit Array#reduce-like operations over objects This is likely to be slightly more inefficient than using lodash.reduce, but results in ~50kb less size in the resulting bundled code before minification and ~12kb of savings with minification. Unlike lodash.reduce(), the iterator and initial value properties are NOT optional: this is done to simplify the code. This module is not intended to be a full replacement for lodash.reduce and instead prioritizes simplicity for a specific common case. @module util/object-reduce @private @param {Object} obj An object of key-value pairs @param {Function} iterator A function to use to reduce the object @param {*} initialState The initial value to pass to the reducer function @returns The result of the reduction operation
module.exports
javascript
WP-API/node-wpapi
lib/util/object-reduce.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/object-reduce.js
MIT
module.exports = ( value ) => { // If the value is not object-like, then it is certainly not an empty object if ( typeof value !== 'object' ) { return false; } // For our purposes an empty array should not be treated as an empty object // (Since this is used to process invalid content-type responses, ) if ( Array.isArray( value ) ) { return false; } for ( const key in value ) { if ( value.hasOwnProperty( key ) ) { return false; } } return true; };
Determine whether an provided value is an empty object @module util/is-empty-object @param {} value A value to test for empty-object-ness @returns {boolean} Whether the provided value is an empty object
module.exports
javascript
WP-API/node-wpapi
lib/util/is-empty-object.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/is-empty-object.js
MIT
module.exports = ( key, value ) => { const obj = {}; obj[ key ] = value; return obj; };
Convert a (key, value) pair to a { key: value } object @module util/key-val-to-obj @param {string} key The key to use in the returned object @param {} value The value to assign to the provided key @returns {object} A dictionary object containing the key-value pair
module.exports
javascript
WP-API/node-wpapi
lib/util/key-val-to-obj.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/key-val-to-obj.js
MIT
module.exports = pathStr => pathStr // Divide a string like "/some/path/(?P<with_named_groups>)/etc" into an // array `[ "/some/path/", "(?P<with_named_groups>)", "/etc" ]`. .split( namedGroupRE ) // Then, reduce through the array of parts, splitting any non-capture-group // parts on forward slashes and discarding empty strings to create the final // array of path components. .reduce( ( components, part ) => { if ( ! part ) { // Ignore empty strings parts return components; } if ( namedGroupRE.test( part ) ) { // Include named capture groups as-is return components.concat( part ); } // Split the part on / and filter out empty strings return components.concat( part.split( '/' ).filter( Boolean ) ); }, [] );
Divide a route string up into hierarchical components by breaking it apart on forward slash characters. There are plugins (including Jetpack) that register routes with regex capture groups which also contain forward slashes, so those groups have to be pulled out first before the remainder of the string can be .split() as normal. @param {String} pathStr A route path string to break into components @returns {String[]} An array of route component strings
module.exports
javascript
WP-API/node-wpapi
lib/util/split-path.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/split-path.js
MIT
module.exports = ( obj, prop, propDefaultValue ) => { if ( obj && obj[ prop ] === undefined ) { obj[ prop ] = propDefaultValue; } };
Ensure that a property is present in an object, initializing it to a default value if it is not already defined. Modifies the provided object by reference. @module util/ensure @param {object} obj The object in which to ensure a property exists @param {string} prop The property key to ensure @param {} propDefaultValue The default value for the property @returns {void}
module.exports
javascript
WP-API/node-wpapi
lib/util/ensure.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/ensure.js
MIT
module.exports = arr => Array.from( new Set( arr ) );
Return an array with all duplicate items removed. This functionality was previously provided by lodash.uniq, but this modern JS solution yields a smaller bundle size. @param {Array} arr An array to de-duplicate @returns {Array} A de-duplicated array
module.exports
javascript
WP-API/node-wpapi
lib/util/unique.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/unique.js
MIT
return function( val ) { return this.param( param, val ); };
A setter for a specific parameter @chainable @param {*} val The value to set for the the parameter @returns The request instance on which this method was called (for chaining)
(anonymous) ( val )
javascript
WP-API/node-wpapi
lib/util/parameter-setter.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/parameter-setter.js
MIT
module.exports = ( param ) => { /** * A setter for a specific parameter * * @chainable * @param {*} val The value to set for the the parameter * @returns The request instance on which this method was called (for chaining) */ return function( val ) { return this.param( param, val ); }; };
Helper to create a simple parameter setter convenience method @module util/parameter-setter @param {String} param The string key of the parameter this method will set @returns {Function} A setter method that can be assigned to a request instance
module.exports
javascript
WP-API/node-wpapi
lib/util/parameter-setter.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/parameter-setter.js
MIT
module.exports = ( obj, key, mixin ) => { // Will not overwrite existing methods if ( typeof mixin === 'function' && ! obj[ key ] ) { obj[ key ] = mixin; } };
Augment an object (specifically a prototype) with a mixin method (the provided object is mutated by reference) @module util/apply-mixin @param {Object} obj The object (usually a prototype) to augment @param {String} key The property to which the mixin method should be assigned @param {Function} mixin The mixin method @returns {void}
module.exports
javascript
WP-API/node-wpapi
lib/util/apply-mixin.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/apply-mixin.js
MIT
const argumentIsNumeric = ( val ) => { if ( typeof val === 'number' ) { return true; } if ( typeof val === 'string' ) { return /^\d+$/.test( val ); } if ( Array.isArray( val ) ) { for ( let i = 0; i < val.length; i++ ) { // Fail early if any argument isn't determined to be numeric if ( ! argumentIsNumeric( val[ i ] ) ) { return false; } } return true; } // If it's not an array, and not a string, and not a number, we don't // know what to do with it return false; };
Return true if the provided argument is a number, a numeric string, or an array of numbers or numeric strings @module util/argument-is-numeric @param {Number|String|Number[]|String[]} val The value to inspect @param {String} key The property to which the mixin method should be assigned @param {Function} mixin The mixin method @returns {void}
argumentIsNumeric
javascript
WP-API/node-wpapi
lib/util/argument-is-numeric.js
https://github.com/WP-API/node-wpapi/blob/master/lib/util/argument-is-numeric.js
MIT
filterMixins.filter = function( props, value ) { if ( ! props || typeof props === 'string' && value === undefined ) { // We have no filter to set, or no value to set for that filter return this; } // convert the property name string `props` and value `value` into an object if ( typeof props === 'string' ) { props = keyValToObj( props, value ); } this._filters = { ...this._filters, ...props, }; return this; };
Specify key-value pairs by which to filter the API results (commonly used to retrieve only posts meeting certain criteria, such as posts within a particular category or by a particular author). @example // Set a single property: wp.filter( 'post_type', 'cpt_event' )... // Set multiple properties at once: wp.filter({ post_status: 'publish', category_name: 'news' })... // Chain calls to .filter(): wp.filter( 'post_status', 'publish' ).filter( 'category_name', 'news' )... @method filter @chainable @param {String|Object} props A filter property name string, or object of name/value pairs @param {String|Number|Array} [value] The value(s) corresponding to the provided filter property @returns The request instance (for chaining)
filterMixins.filter ( props , value )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
filterMixins.taxonomy = function( taxonomy, term ) { const termIsArray = Array.isArray( term ); const termIsNumber = termIsArray ? term.reduce( ( allAreNumbers, term ) => allAreNumbers && typeof term === 'number', true ) : typeof term === 'number'; const termIsString = termIsArray ? term.reduce( ( allAreStrings, term ) => allAreStrings && typeof term === 'string', true ) : typeof term === 'string'; if ( ! termIsString && ! termIsNumber ) { throw new Error( 'term must be a number, string, or array of numbers or strings' ); } if ( taxonomy === 'category' ) { if ( termIsString ) { // Query param for filtering by category slug is "category_name" taxonomy = 'category_name'; } else { // The boolean check above ensures that if taxonomy === 'category' and // term is not a string, then term must be a number and therefore an ID: // Query param for filtering by category ID is "cat" taxonomy = 'cat'; } } else if ( taxonomy === 'post_tag' ) { // tag is used in place of post_tag in the public query variables taxonomy = 'tag'; } // Ensure the taxonomy filters object is available this._taxonomyFilters = this._taxonomyFilters || {}; // Ensure there's an array of terms available for this taxonomy const taxonomyTerms = ( this._taxonomyFilters[ taxonomy ] || [] ) // Insert the provided terms into the specified taxonomy's terms array .concat( term ) // Sort array .sort( alphaNumericSort ); // De-dupe this._taxonomyFilters[ taxonomy ] = unique( taxonomyTerms, true ); return this; };
Restrict the query results to posts matching one or more taxonomy terms. @method taxonomy @chainable @param {String} taxonomy The name of the taxonomy to filter by @param {String|Number|Array} term A string or integer, or array thereof, representing terms @returns The request instance (for chaining)
filterMixins.taxonomy ( taxonomy , term )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
filterMixins.year = function( year ) { return filterMixins.filter.call( this, 'year', year ); };
Query for posts published in a given year. @method year @chainable @param {Number} year integer representation of year requested @returns The request instance (for chaining)
filterMixins.year ( year )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
filterMixins.month = function( month ) { let monthDate; if ( typeof month === 'string' ) { // Append a arbitrary day and year to the month to parse the string into a Date monthDate = new Date( Date.parse( month + ' 1, 2012' ) ); // If the generated Date is NaN, then the passed string is not a valid month if ( isNaN( monthDate ) ) { return this; } // JS Dates are 0 indexed, but the WP API requires a 1-indexed integer month = monthDate.getMonth() + 1; } // If month is a Number, add the monthnum filter to the request if ( typeof month === 'number' ) { return filterMixins.filter.call( this, 'monthnum', month ); } return this; };
Query for posts published in a given month, either by providing the number of the requested month (e.g. 3), or the month's name as a string (e.g. "March") @method month @chainable @param {Number|String} month Integer for month (1) or month string ("January") @returns The request instance (for chaining)
filterMixins.month ( month )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
filterMixins.day = function( day ) { return filterMixins.filter.call( this, 'day', day ); };
Add the day filter into the request to retrieve posts for a given day @method day @chainable @param {Number} day Integer representation of the day requested @returns The request instance (for chaining)
filterMixins.day ( day )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
filterMixins.path = function( path ) { return filterMixins.filter.call( this, 'pagename', path ); };
Specify that we are requesting a page by its path (specific to Page resources) @method path @chainable @param {String} path The root-relative URL path for a page @returns The request instance (for chaining)
filterMixins.path ( path )
javascript
WP-API/node-wpapi
lib/mixins/filters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/filters.js
MIT
parameterMixins.author = function( author ) { if ( author === undefined ) { return this; } if ( typeof author === 'string' ) { this.param( 'author', null ); return filter.call( this, 'author_name', author ); } if ( typeof author === 'number' ) { filter.call( this, 'author_name', null ); return this.param( 'author', author ); } if ( author === null ) { filter.call( this, 'author_name', null ); return this.param( 'author', null ); } throw new Error( 'author must be either a nicename string or numeric ID' ); };
Query for posts by a specific author. This method will replace any previous 'author' query parameters that had been set. Note that this method will either set the "author" top-level query parameter, or else the "author_name" filter parameter (when querying by nicename): this is irregular as most parameter helper methods either set a top level parameter or a filter, not both. _Usage with the author nicename string is deprecated._ Query by author ID instead. If the "rest-filter" plugin is not installed, the name query will have no effect. @method author @chainable @param {String|Number} author The nicename or ID for a particular author @returns The request instance (for chaining)
parameterMixins.author ( author )
javascript
WP-API/node-wpapi
lib/mixins/parameters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/parameters.js
MIT
parameterMixins.category = function( category ) { if ( argumentIsNumeric( category ) ) { return parameterMixins.categories.call( this, category ); } return taxonomy.call( this, 'category', category ); };
Legacy wrapper for `.categories()` that uses `?filter` to query by slug if available @method tag @deprecated Use `.categories()` and query by category IDs @chainable @param {String|Number|Array} tag A category term slug string, numeric ID, or array of numeric IDs @returns The request instance (for chaining)
parameterMixins.category ( category )
javascript
WP-API/node-wpapi
lib/mixins/parameters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/parameters.js
MIT
parameterMixins.tag = function( tag ) { if ( argumentIsNumeric( tag ) ) { return parameterMixins.tags.call( this, tag ); } return taxonomy.call( this, 'tag', tag ); };
Legacy wrapper for `.tags()` that uses `?filter` to query by slug if available @method tag @deprecated Use `.tags()` and query by term IDs @chainable @param {String|Number|Array} tag A tag term slug string, numeric ID, or array of numeric IDs @returns The request instance (for chaining)
parameterMixins.tag ( tag )
javascript
WP-API/node-wpapi
lib/mixins/parameters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/parameters.js
MIT
parameterMixins.before = function( date ) { return this.param( 'before', new Date( date ).toISOString() ); };
Retrieve only records published before a specified date @example <caption>Provide an ISO 8601-compliant date string</caption> wp.posts().before('2016-03-22')... @example <caption>Provide a JavaScript Date object</caption> wp.posts().before( new Date( 2016, 03, 22 ) )... @method before @chainable @param {String|Date} date An ISO 8601-compliant date string, or Date object @returns The request instance (for chaining)
parameterMixins.before ( date )
javascript
WP-API/node-wpapi
lib/mixins/parameters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/parameters.js
MIT
parameterMixins.after = function( date ) { return this.param( 'after', new Date( date ).toISOString() ); };
Retrieve only records published after a specified date @example <caption>Provide an ISO 8601-compliant date string</caption> wp.posts().after('1986-03-22')... @example <caption>Provide a JavaScript Date object</caption> wp.posts().after( new Date( 1986, 03, 22 ) )... @method after @chainable @param {String|Date} date An ISO 8601-compliant date string, or Date object @returns The request instance (for chaining)
parameterMixins.after ( date )
javascript
WP-API/node-wpapi
lib/mixins/parameters.js
https://github.com/WP-API/node-wpapi/blob/master/lib/mixins/parameters.js
MIT
function WPRequest( options ) { /** * Configuration options for the request * * @property _options * @type Object * @private * @default {} */ this._options = [ // Whitelisted options keys 'auth', 'endpoint', 'headers', 'username', 'password', 'nonce', ].reduce( ( localOptions, key ) => { if ( options && options[ key ] ) { localOptions[ key ] = options[ key ]; } return localOptions; }, {} ); /** * The HTTP transport methods (.get, .post, .put, .delete, .head) to use for this request * * @property transport * @type {Object} * @private */ this.transport = options && options.transport; /** * A hash of query parameters * This is used to store the values for supported query parameters like ?_embed * * @property _params * @type Object * @private * @default {} */ this._params = {}; /** * Methods supported by this API request instance: * Individual endpoint handlers specify their own subset of supported methods * * @property _supportedMethods * @type Array * @private * @default [ 'head', 'get', 'put', 'post', 'delete' ] */ this._supportedMethods = [ 'head', 'get', 'put', 'post', 'delete' ]; /** * A hash of values to assemble into the API request path * (This will be overwritten by each specific endpoint handler constructor) * * @property _path * @type Object * @private * @default {} */ this._path = {}; }
WPRequest is the base API request object constructor @constructor WPRequest @param {Object} options A hash of options for the WPRequest instance @param {String} options.endpoint The endpoint URI for the invoking WPAPI instance @param {Object} options.transport An object of http transport methods (get, post, etc) @param {String} [options.username] A username for authenticating API requests @param {String} [options.password] A password for authenticating API requests @param {String} [options.nonce] A WP nonce for use with cookie authentication
WPRequest ( options )
javascript
WP-API/node-wpapi
lib/constructors/wp-request.js
https://github.com/WP-API/node-wpapi/blob/master/lib/constructors/wp-request.js
MIT
const identity = value => value;
Identity function for use within invokeAndPromisify() @private
identity
javascript
WP-API/node-wpapi
lib/constructors/wp-request.js
https://github.com/WP-API/node-wpapi/blob/master/lib/constructors/wp-request.js
MIT
function prepareTaxonomies( taxonomyFilters ) { if ( ! taxonomyFilters ) { return {}; } return objectReduce( taxonomyFilters, ( result, terms, key ) => { // Trim whitespace and concatenate multiple terms with + result[ key ] = terms // Coerce term into a string so that trim() won't fail .map( term => ( term + '' ).trim().toLowerCase() ) .join( '+' ); return result; }, {} ); }
Process arrays of taxonomy terms into query parameters. All terms listed in the arrays will be required (AND behavior). This method will not be called with any values unless we are handling an endpoint with the filter mixin; however, since parameter handling (and therefore `_renderQuery()`) are part of WPRequest itself, this helper method lives here alongside the code where it is used. @example prepareTaxonomies({ tag: [ 'tag1 ', 'tag2' ], // by term slug cat: [ 7 ] // by term ID }) === { tag: 'tag1+tag2', cat: '7' } @private @param {Object} taxonomyFilters An object of taxonomy term arrays, keyed by taxonomy name @returns {Object} An object of prepareFilters-ready query arg and query param value pairs
prepareTaxonomies ( taxonomyFilters )
javascript
WP-API/node-wpapi
lib/constructors/wp-request.js
https://github.com/WP-API/node-wpapi/blob/master/lib/constructors/wp-request.js
MIT
const populated = ( obj ) => { if ( ! obj ) { return obj; } return objectReduce( obj, ( values, val, key ) => { if ( val !== undefined && val !== null && val !== '' ) { values[ key ] = val; } return values; }, {} ); };
Return an object with any properties with undefined, null or empty string values removed. @example populated({ a: 'a', b: '', c: null }); // { a: 'a' } @private @param {Object} obj An object of key/value pairs @returns {Object} That object with all empty values removed
populated
javascript
WP-API/node-wpapi
lib/constructors/wp-request.js
https://github.com/WP-API/node-wpapi/blob/master/lib/constructors/wp-request.js
MIT
constructor(options = {}) { const defaults = { content: options.viewport.children[0], direction: 'all', // 'vertical', 'horizontal' pointerMode: 'all', // 'touch', 'mouse' scrollMode: undefined, // 'transform', 'native' bounce: true, bounceForce: 0.1, friction: 0.05, textSelection: false, inputsFocus: true, emulateScroll: false, preventDefaultOnEmulateScroll: false, // 'vertical', 'horizontal' preventPointerMoveDefault: true, lockScrollOnDragDirection: false, // 'vertical', 'horizontal', 'all' pointerDownPreventDefault: true, dragDirectionTolerance: 40, onPointerDown() {}, onPointerUp() {}, onPointerMove() {}, onClick() {}, onUpdate() {}, onWheel() {}, shouldScroll() { return true; }, }; this.props = { ...defaults, ...options }; if (!this.props.viewport || !(this.props.viewport instanceof Element)) { console.error(`ScrollBooster init error: "viewport" config property must be present and must be Element`); return; } if (!this.props.content) { console.error(`ScrollBooster init error: Viewport does not have any content`); return; } this.isDragging = false; this.isTargetScroll = false; this.isScrolling = false; this.isRunning = false; const START_COORDINATES = { x: 0, y: 0 }; this.position = { ...START_COORDINATES }; this.velocity = { ...START_COORDINATES }; this.dragStartPosition = { ...START_COORDINATES }; this.dragOffset = { ...START_COORDINATES }; this.clientOffset = { ...START_COORDINATES }; this.dragPosition = { ...START_COORDINATES }; this.targetPosition = { ...START_COORDINATES }; this.scrollOffset = { ...START_COORDINATES }; this.rafID = null; this.events = {}; this.updateMetrics(); this.handleEvents(); }
Create ScrollBooster instance @param {Object} options - options object @param {Element} options.viewport - container element @param {Element} options.content - scrollable content element @param {String} options.direction - scroll direction @param {String} options.pointerMode - mouse or touch support @param {String} options.scrollMode - predefined scrolling technique @param {Boolean} options.bounce - bounce effect @param {Number} options.bounceForce - bounce effect factor @param {Number} options.friction - scroll friction factor @param {Boolean} options.textSelection - enables text selection @param {Boolean} options.inputsFocus - enables focus on input elements @param {Boolean} options.emulateScroll - enables mousewheel emulation @param {Function} options.onClick - click handler @param {Function} options.onUpdate - state update handler @param {Function} options.onWheel - wheel handler @param {Function} options.shouldScroll - predicate to allow or disable scroll
constructor ( options = { } )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
updateOptions(options = {}) { this.props = { ...this.props, ...options }; this.props.onUpdate(this.getState()); this.startAnimationLoop(); }
Update options object with new given values
updateOptions ( options = { } )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
updateScrollPosition() { this.applyEdgeForce(); this.applyDragForce(); this.applyScrollForce(); this.applyTargetForce(); const inverseFriction = 1 - this.props.friction; this.velocity.x *= inverseFriction; this.velocity.y *= inverseFriction; if (this.props.direction !== 'vertical') { this.position.x += this.velocity.x; } if (this.props.direction !== 'horizontal') { this.position.y += this.velocity.y; } // disable bounce effect if ((!this.props.bounce || this.isScrolling) && !this.isTargetScroll) { this.position.x = Math.max(Math.min(this.position.x, this.edgeX.to), this.edgeX.from); this.position.y = Math.max(Math.min(this.position.y, this.edgeY.to), this.edgeY.from); } }
Calculate and set new scroll position
updateScrollPosition ( )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
applyForce(force) { this.velocity.x += force.x; this.velocity.y += force.y; }
Increase general scroll velocity by given force amount
applyForce ( force )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
applyDragForce() { if (!this.isDragging) { return; } const dragVelocity = { x: this.dragPosition.x - this.position.x, y: this.dragPosition.y - this.position.y, }; this.applyForce({ x: dragVelocity.x - this.velocity.x, y: dragVelocity.y - this.velocity.y, }); }
Apply force to move content while dragging with mouse/touch
applyDragForce ( )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
applyScrollForce() { if (!this.isScrolling) { return; } this.applyForce({ x: this.scrollOffset.x - this.velocity.x, y: this.scrollOffset.y - this.velocity.y, }); this.scrollOffset.x = 0; this.scrollOffset.y = 0; }
Apply force to emulate mouse wheel or trackpad
applyScrollForce ( )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT
scrollTo(position = {}) { this.isTargetScroll = true; this.targetPosition.x = -position.x || 0; this.targetPosition.y = -position.y || 0; this.startAnimationLoop(); }
Set scroll target coordinate for smooth scroll
scrollTo ( position = { } )
javascript
ilyashubin/scrollbooster
src/index.js
https://github.com/ilyashubin/scrollbooster/blob/master/src/index.js
MIT