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 onmessage(e) { var source = e.source; var result = e.data.result || { success: true }; var delay = e.data.delay || 2000; var success = function() { source.postMessage( result ); }; setTimeout( success, delay ); }
The worker module needed by promise_test
onmessage ( e )
javascript
ringo/ringojs
test/ringo/promise_worker.js
https://github.com/ringo/ringojs/blob/master/test/ringo/promise_worker.js
Apache-2.0
/******/ /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) /******/ return installedModules[moduleId].exports // Create a new module (and put it into the cache) /******/ /******/ /******/ var module = (installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false, /******/ }) // Execute the module function /******/ /******/ /******/ modules[moduleId].call( module.exports, module, module.exports, __webpack_require__ ) // Flag the module as loaded /******/ /******/ /******/ module.loaded = true // Return the exports of the module /******/ /******/ /******/ return module.exports /******/ } // expose the modules object (__webpack_modules__)
****/ var installedModules = {} // The require function ****/
__webpack_require__ ( moduleId )
javascript
HVF/franchise
src/db/graphql/graphql-docs.js
https://github.com/HVF/franchise/blob/master/src/db/graphql/graphql-docs.js
MIT
var checkParentContainer = function($container) { var styles = window.getComputedStyle($container, null); var position = styles.getPropertyValue('position'); var overflow = styles.getPropertyValue('overflow'); var display = styles.getPropertyValue('display'); if (!position || position === 'static') { $container.style.position = 'relative'; } if (overflow !== 'hidden') { $container.style.overflow = 'hidden'; } // Guesstimating that people want the parent to act like full width/height wrapper here. // Mostly attempts to target <picture> elements, which default to inline. if (!display || display === 'inline') { $container.style.display = 'block'; } if ($container.clientHeight === 0) { $container.style.height = '100%'; } // Add a CSS class hook, in case people need to override styles for any reason. if ($container.className.indexOf('object-fit-polyfill') === -1) { $container.className = $container.className + ' object-fit-polyfill'; } };
Check the container's parent element to make sure it will correctly handle and clip absolutely positioned children @param {node} $container - parent element
checkParentContainer ( $container )
javascript
cee-chen/object-fit-polyfill
src/objectFitPolyfill.js
https://github.com/cee-chen/object-fit-polyfill/blob/master/src/objectFitPolyfill.js
ISC
var checkMediaProperties = function($media) { var styles = window.getComputedStyle($media, null); var constraints = { 'max-width': 'none', 'max-height': 'none', 'min-width': '0px', 'min-height': '0px', top: 'auto', right: 'auto', bottom: 'auto', left: 'auto', 'margin-top': '0px', 'margin-right': '0px', 'margin-bottom': '0px', 'margin-left': '0px', }; for (var property in constraints) { var constraint = styles.getPropertyValue(property); if (constraint !== constraints[property]) { $media.style[property] = constraints[property]; } } };
Check for pre-set max-width/height, min-width/height, positioning, or margins, which can mess up image calculations @param {node} $media - img/video element
checkMediaProperties ( $media )
javascript
cee-chen/object-fit-polyfill
src/objectFitPolyfill.js
https://github.com/cee-chen/object-fit-polyfill/blob/master/src/objectFitPolyfill.js
ISC
var setPosition = function(axis, $media, objectPosition) { var position, other, start, end, side; objectPosition = objectPosition.split(' '); if (objectPosition.length < 2) { objectPosition[1] = objectPosition[0]; } /* istanbul ignore else */ if (axis === 'x') { position = objectPosition[0]; other = objectPosition[1]; start = 'left'; end = 'right'; side = $media.clientWidth; } else if (axis === 'y') { position = objectPosition[1]; other = objectPosition[0]; start = 'top'; end = 'bottom'; side = $media.clientHeight; } else { return; // Neither x or y axis specified } if (position === start || other === start) { $media.style[start] = '0'; return; } if (position === end || other === end) { $media.style[end] = '0'; return; } if (position === 'center' || position === '50%') { $media.style[start] = '50%'; $media.style['margin-' + start] = side / -2 + 'px'; return; } // Percentage values (e.g., 30% 10%) if (position.indexOf('%') >= 0) { position = parseInt(position, 10); if (position < 50) { $media.style[start] = position + '%'; $media.style['margin-' + start] = side * (position / -100) + 'px'; } else { position = 100 - position; $media.style[end] = position + '%'; $media.style['margin-' + end] = side * (position / -100) + 'px'; } return; } // Length-based values (e.g. 10px / 10em) else { $media.style[start] = position; } };
Calculate & set object-position @param {string} axis - either "x" or "y" @param {node} $media - img or video element @param {string} objectPosition - e.g. "50% 50%", "top left"
setPosition ( axis , $media , objectPosition )
javascript
cee-chen/object-fit-polyfill
src/objectFitPolyfill.js
https://github.com/cee-chen/object-fit-polyfill/blob/master/src/objectFitPolyfill.js
ISC
var objectFit = function($media) { // IE 10- data polyfill var fit = $media.dataset ? $media.dataset.objectFit : $media.getAttribute('data-object-fit'); var position = $media.dataset ? $media.dataset.objectPosition : $media.getAttribute('data-object-position'); // Default fallbacks fit = fit || 'cover'; position = position || '50% 50%'; // If necessary, make the parent container work with absolutely positioned elements var $container = $media.parentNode; checkParentContainer($container); // Check for any pre-set CSS which could mess up image calculations checkMediaProperties($media); // Reset any pre-set width/height CSS and handle fit positioning $media.style.position = 'absolute'; $media.style.width = 'auto'; $media.style.height = 'auto'; // `scale-down` chooses either `none` or `contain`, whichever is smaller if (fit === 'scale-down') { if ( $media.clientWidth < $container.clientWidth && $media.clientHeight < $container.clientHeight ) { fit = 'none'; } else { fit = 'contain'; } } // `none` (width/height auto) and `fill` (100%) and are straightforward if (fit === 'none') { setPosition('x', $media, position); setPosition('y', $media, position); return; } if (fit === 'fill') { $media.style.width = '100%'; $media.style.height = '100%'; setPosition('x', $media, position); setPosition('y', $media, position); return; } // `cover` and `contain` must figure out which side needs covering, and add CSS positioning & centering $media.style.height = '100%'; if ( (fit === 'cover' && $media.clientWidth > $container.clientWidth) || (fit === 'contain' && $media.clientWidth < $container.clientWidth) ) { $media.style.top = '0'; $media.style.marginTop = '0'; setPosition('x', $media, position); } else { $media.style.width = '100%'; $media.style.height = 'auto'; $media.style.left = '0'; $media.style.marginLeft = '0'; setPosition('y', $media, position); } };
Calculate & set object-fit @param {node} $media - img/video/picture element
objectFit ( $media )
javascript
cee-chen/object-fit-polyfill
src/objectFitPolyfill.js
https://github.com/cee-chen/object-fit-polyfill/blob/master/src/objectFitPolyfill.js
ISC
var objectFitPolyfill = function(media) { if (typeof media === 'undefined' || media instanceof Event) { // If left blank, or a default event, all media on the page will be polyfilled. media = document.querySelectorAll('[data-object-fit]'); } else if (media && media.nodeName) { // If it's a single node, wrap it in an array so it works. media = [media]; } else if (typeof media === 'object' && media.length && media[0].nodeName) { // If it's an array of DOM nodes (e.g. a jQuery selector), it's fine as-is. media = media; } else { // Otherwise, if it's invalid or an incorrect type, return false to let people know. return false; } for (var i = 0; i < media.length; i++) { if (!media[i].nodeName) continue; var mediaType = media[i].nodeName.toLowerCase(); if (mediaType === 'img') { if (edgePartialSupport) continue; // Edge supports object-fit for images (but nothing else), so no need to polyfill if (media[i].complete) { objectFit(media[i]); } else { media[i].addEventListener('load', function() { objectFit(this); }); } } else if (mediaType === 'video') { if (media[i].readyState > 0) { objectFit(media[i]); } else { media[i].addEventListener('loadedmetadata', function() { objectFit(this); }); } } else { objectFit(media[i]); } } return true; };
Initialize plugin @param {node} media - Optional specific DOM node(s) to be polyfilled
objectFitPolyfill ( media )
javascript
cee-chen/object-fit-polyfill
src/objectFitPolyfill.js
https://github.com/cee-chen/object-fit-polyfill/blob/master/src/objectFitPolyfill.js
ISC
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var SomePromiseArray = Promise._SomePromiseArray; function any(promises) { var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(1); ret.setUnwrap(); ret.init(); return promise; } Promise.any = function (promises) { return any(promises); }; Promise.prototype.any = function () { return any(this); }; }; },{}],2:[function(_dereq_,module,exports){
bluebird build version 3.2.2 Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
1 ( _dereq_ , module , exports )
javascript
ericholiveira/studio
browser/studio-with-dependecies.js
https://github.com/ericholiveira/studio/blob/master/browser/studio-with-dependecies.js
MIT
module:function(moduleName){ "use strict"; logging.instance.log('Created module '+moduleName); var result = function(options,extra){ if(typeof options === 'string'){ return result.ref(options,extra); } return result.service(options,extra); }; copyStudioProperties(result); result.module=function(module2){ logging.instance.log('Created module '+moduleName+'/'+module2); return _Studio.module(moduleName+'/'+module2); }; result._moduleName = moduleName; result.service = function(options,extra){ if(!options.id && !options.name) { logging.instance.error('Throwing error ServiceNameOrIdNotFoundException'); throw exception.ServiceNameOrIdNotFoundException(); } options.id = options.id || options.name; options.id = moduleName+'/'+options.id; return _Studio.service(options,extra); }; result.ref = function(options,extra){ return _Studio.ref(moduleName+'/'+options,extra); }; return result; },
@function @name module @desc Creates (or retrieves if it already exists) a module. Should be used to avoid service name conflict for large systems. The module created have all the same methods and properties of Studio object, but running inside of that namespace. @param {String} moduleName. The module name @return {function} Studio. A function with all methods and properties fo Studio @example var fooModule = Studio.module('foo'); // Create or retrieves a module var barModule = Studio.module('bar'); // Create or retrieves a module // Create a service inside foo module, this service calls a service from bar module fooModule(function fooMethod(){ var barService = barModule('barMethod'); return barservice('Hello'); }); // Creates a service inside bar module barModule(function barMethod(param){ return param = ' bar'; }); var fooService = fooModule('fooMethod');//Retrieves fooMethod from foo module fooService().then(function(result){ console.log(result); // Prints Hello bar' });
module ( moduleName )
javascript
ericholiveira/studio
src/studio.js
https://github.com/ericholiveira/studio/blob/master/src/studio.js
MIT
use : function(plugin,filter){ logging.instance.log('%{nameSpace} use a new plugin'); var self = this; return plugin({ onStart:function(listener){require('./util/listeners').addOnStartListener(listener,filter,self._moduleName);}, onStop:function(listener){require('./util/listeners').addOnStopListener(listener,filter,self._moduleName);}, interceptSend:function(listener){require('./util/listeners').addInterceptSend(listener,filter,self._moduleName);} },Studio); },
@function @name use @desc Enables a plugin @param {function} plugin. The plugin you want to use @param {Object} filter. The filter for this plugin usage @example Studio.use(myPlugin);//Enables myPlugin for all services Studio.use(otherPlugin,'foo'); // Enables otherPlugin only for a service called foo Studio.use(otherPlugin2,/f.+/); // Enables otherPlugin2 only for services which names match the /f.+/ regex Studio.use(otherPlugin3,function(serviceName){ return serviceName.length===3; }); // Enables otherPlugin3 only for services which names satisfies that function Studio.use(otherPlugin4,['foo',/f.+/,function(serviceName){ return serviceName.length===3; }]);// Enables otherPlugin4 only for services which names satisfies ANY filter in the array
use ( plugin , filter )
javascript
ericholiveira/studio
src/studio.js
https://github.com/ericholiveira/studio/blob/master/src/studio.js
MIT
_Studio.services=function(){ return createProxy(this); };
@function @name services @desc Gets a reference for all services available on Studio. This function is available only if Proxy is enabled (node > 6 or older version with --harmony-proxies flag) @example var allServices = Studio.services();// A reference for all services var myServiceRef = Studio('myService');//Returns a reference for a service called myService var myServiceRefFromProxy = allServices.myService;//a reference for a service called myService // For an object inside a module var fooModule = Studio.module('foo'); var barServiceRef = fooModule('bar'); var barServiceRefFromProxy = allServices.foo.bar;
_Studio.services ( )
javascript
ericholiveira/studio
src/studio.js
https://github.com/ericholiveira/studio/blob/master/src/studio.js
MIT
OutputValidationRule.prototype.validateSpec = function validateSpec() { assert(this.spec.body || this.spec.headers, 'output validation key: ' + this.status + ' must have either a body or headers validator specified'); };
Validates it's input values @throws Error
validateSpec ( )
javascript
koajs/joi-router
output-validation-rule.js
https://github.com/koajs/joi-router/blob/master/output-validation-rule.js
MIT
OutputValidationRule.prototype.overlaps = function overlaps(ruleB) { return OutputValidationRule.overlaps(this, ruleB); };
Determines if this rule has overlapping logic with `ruleB`. @returns Boolean
overlaps ( ruleB )
javascript
koajs/joi-router
output-validation-rule.js
https://github.com/koajs/joi-router/blob/master/output-validation-rule.js
MIT
OutputValidationRule.prototype.matches = function matches(ctx) { for (let i = 0; i < this.ranges.length; ++i) { const range = this.ranges[i]; if (ctx.status >= range.lower && ctx.status <= range.upper) { return true; } } return false; };
Checks if this rule should be run against the given `ctx` response data. @returns Boolean
matches ( ctx )
javascript
koajs/joi-router
output-validation-rule.js
https://github.com/koajs/joi-router/blob/master/output-validation-rule.js
MIT
OutputValidationRule.prototype.validateOutput = function validateOutput(ctx) { let result; if (this.spec.headers) { result = Joi.compile(this.spec.headers).validate(ctx.response.headers); if (result.error) return result.error; // use casted values ctx.set(result.value); } if (this.spec.body) { result = Joi.compile(this.spec.body).validate(ctx.body); if (result.error) return result.error; // use casted values ctx.body = result.value; } };
Validates this rule against the given `ctx`.
validateOutput ( ctx )
javascript
koajs/joi-router
output-validation-rule.js
https://github.com/koajs/joi-router/blob/master/output-validation-rule.js
MIT
OutputValidationRule.overlaps = function overlaps(a, b) { /* eslint-disable prefer-arrow-callback */ return a.ranges.some(function checkRangeA(rangeA) { return b.ranges.some(function checkRangeB(rangeB) { if (rangeA.upper >= rangeB.lower && rangeA.lower <= rangeB.upper) { return true; } return false; }); }); /* eslint-enable prefer-arrow-callback */ };
Determines if ruleA has overlapping logic with `ruleB`. @returns Boolean
overlaps ( a , b )
javascript
koajs/joi-router
output-validation-rule.js
https://github.com/koajs/joi-router/blob/master/output-validation-rule.js
MIT
Router.prototype.middleware = function middleware() { return this.router.routes(); };
Return koa middleware @return {Function} @api public
middleware ( )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
Router.prototype.route = function route(spec) { if (Array.isArray(spec)) { for (let i = 0; i < spec.length; i++) { this._addRoute(spec[i]); } } else { this._addRoute(spec); } return this; };
Adds a route or array of routes to this router, storing the route in `this.routes`. Example: var admin = router(); admin.route({ method: 'get', path: '/do/stuff/:id', handler: function *(next){}, validate: { header: Joi object params: Joi object (:id) query: Joi object (validate key/val pairs in the querystring) body: Joi object (the request payload body) (json or form) maxBody: '64kb' // (json, x-www-form-urlencoded only - not stream size) // optional type: 'json|form|multipart' (required when body is specified) failure: 400 // http error code to use }, meta: { // this is ignored but useful for doc generators etc desc: 'We can use this for docs generation.' produces: ['application/json'] model: {} // response object definition } }) @param {Object} spec @return {Router} self @api public
route ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
Router.prototype._addRoute = function addRoute(spec) { this._validateRouteSpec(spec); this.routes.push(spec); debug('add %s "%s"', spec.method, spec.path); const bodyParser = makeBodyParser(spec); const specExposer = makeSpecExposer(spec); const validator = makeValidator(spec); const preHandlers = spec.pre ? flatten(spec.pre) : []; const handlers = flatten(spec.handler); const args = [ spec.path ].concat(preHandlers, [ prepareRequest, specExposer, bodyParser, validator ], handlers); const router = this.router; spec.method.forEach((method) => { router[method].apply(router, args); }); };
Adds a route to this router, storing the route in `this.routes`. @param {Object} spec @api private
addRoute ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
Router.prototype._validateRouteSpec = function validateRouteSpec(spec) { assert(spec, 'missing spec'); const ok = typeof spec.path === 'string' || spec.path instanceof RegExp; assert(ok, 'invalid route path'); checkHandler(spec); checkPreHandler(spec); checkMethods(spec); checkValidators(spec); };
Validate the spec passed to route() @param {Object} spec @api private
validateRouteSpec ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function checkMethods(spec) { assert(spec.method, 'missing route methods'); if (typeof spec.method === 'string') { spec.method = spec.method.split(' '); } if (!Array.isArray(spec.method)) { throw new TypeError('route methods must be an array or string'); } if (spec.method.length === 0) { throw new Error('missing route method'); } spec.method.forEach((method, i) => { assert(typeof method === 'string', 'route method must be a string'); spec.method[i] = method.toLowerCase(); }); }
Validate the spec.method @param {Object} spec @api private
checkMethods ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function checkValidators(spec) { if (!spec.validate) return; let text; if (spec.validate.body) { text = 'validate.type must be declared when using validate.body'; assert(/json|form/.test(spec.validate.type), text); } if (spec.validate.type) { text = 'validate.type must be either json, form, multipart or stream'; assert(/json|form|multipart|stream/i.test(spec.validate.type), text); } if (spec.validate.output) { spec.validate._outputValidator = new OutputValidator(spec.validate.output); } // default HTTP status code for failures if (!spec.validate.failure) { spec.validate.failure = 400; } }
Validate the spec.validators @param {Object} spec @api private
checkValidators ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
async function noopMiddleware(ctx, next) { return await next(); }
Does nothing @param {[type]} ctx [description] @param {Function} next [description] @return {async function} [description] @api private
noopMiddleware ( ctx , next )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function wrapError(spec, parsePayload) { return async function errorHandler(ctx, next) { try { await parsePayload(ctx); } catch (err) { captureError(ctx, 'type', err); if (!spec.validate.continueOnError) { return ctx.throw(err); } } await next(); }; }
Handles parser internal errors @param {Object} spec [description] @param {function} parsePayload [description] @return {async function} [description] @api private
wrapError ( spec , parsePayload )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeJSONBodyParser(spec) { const opts = spec.validate.jsonOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseJSONPayload(ctx) { if (!ctx.request.is('json')) { return ctx.throw(400, 'expected json'); } // eslint-disable-next-line require-atomic-updates ctx.request.body = ctx.request.body || await parse.json(ctx, opts); }; }
Creates JSON body parser middleware. @param {Object} spec @return {async function} @api private
makeJSONBodyParser ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeFormBodyParser(spec) { const opts = spec.validate.formOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseFormBody(ctx) { if (!ctx.request.is('urlencoded')) { return ctx.throw(400, 'expected x-www-form-urlencoded'); } // eslint-disable-next-line require-atomic-updates ctx.request.body = ctx.request.body || await parse.form(ctx, opts); }; }
Creates form body parser middleware. @param {Object} spec @return {async function} @api private
makeFormBodyParser ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeMultipartParser(spec) { const opts = spec.validate.multipartOptions || {}; if (typeof opts.autoFields === 'undefined') { opts.autoFields = true; } return async function parseMultipart(ctx) { if (!ctx.request.is('multipart/*')) { return ctx.throw(400, 'expected multipart'); } ctx.request.parts = busboy(ctx, opts); }; }
Creates stream/multipart-form body parser middleware. @param {Object} spec @return {async function} @api private
makeMultipartParser ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeBodyParser(spec) { if (!(spec.validate && spec.validate.type)) return noopMiddleware; switch (spec.validate.type) { case 'json': return wrapError(spec, makeJSONBodyParser(spec)); case 'form': return wrapError(spec, makeFormBodyParser(spec)); case 'stream': case 'multipart': return wrapError(spec, makeMultipartParser(spec)); default: throw new Error(`unsupported body type: ${spec.validate.type}`); } }
Creates body parser middleware. @param {Object} spec @return {async function} @api private
makeBodyParser ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeValidator(spec) { const props = 'header query params body'.split(' '); return async function validator(ctx, next) { if (!spec.validate) return await next(); let err; for (let i = 0; i < props.length; ++i) { const prop = props[i]; if (spec.validate[prop]) { err = validateInput(prop, ctx, spec.validate); if (err) { captureError(ctx, prop, err); if (!spec.validate.continueOnError) return ctx.throw(err); } } } await next(); if (spec.validate._outputValidator) { debug('validating output'); err = spec.validate._outputValidator.validate(ctx); if (err) { err.status = 500; return ctx.throw(err); } } }; }
Creates validator middleware. @param {Object} spec @return {async function} @api private
makeValidator ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function makeSpecExposer(spec) { const defn = clone(spec); return async function specExposer(ctx, next) { ctx.state.route = defn; await next(); }; }
Exposes route spec @param {Object} spec The route spec @returns {async Function} Middleware @api private
makeSpecExposer ( spec )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
async function prepareRequest(ctx, next) { ctx.request.params = ctx.params; await next(); }
Middleware which creates `request.params`. @api private
prepareRequest ( ctx , next )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
function validateInput(prop, ctx, validate) { debug('validating %s', prop); const request = ctx.request; const res = Joi.compile(validate[prop]).validate(request[prop], validate.validateOptions || {}); if (res.error) { res.error.status = validate.failure; return res.error; } // update our request w/ the casted values switch (prop) { case 'header': // request.header is getter only, cannot set it case 'query': // setting request.query directly causes casting back to strings Object.keys(res.value).forEach((key) => { request[prop][key] = res.value[key]; }); break; case 'params': request.params = ctx.params = res.value; break; default: request[prop] = res.value; } }
Validates request[prop] data with the defined validation schema. @param {String} prop @param {koa.Request} request @param {Object} validate @returns {Error|undefined} @api private
validateInput ( prop , ctx , validate )
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
methods.forEach((method) => { method = method.toLowerCase(); Router.prototype[method] = function(path) { // path, handler1, handler2, ... // path, config, handler1 // path, config, handler1, handler2, ... // path, config, [handler1, handler2], handler3, ... let fns; let config; if (typeof arguments[1] === 'function' || Array.isArray(arguments[1])) { config = {}; fns = slice(arguments, 1); } else if (typeof arguments[1] === 'object') { config = arguments[1]; fns = slice(arguments, 2); } const spec = { path: path, method: method, handler: fns }; Object.assign(spec, config); this.route(spec); return this; }; });
Routing shortcuts for all HTTP methods Example: var admin = router(); admin.get('/user', async function(ctx) { ctx.body = ctx.session.user; }) var validator = Joi().object().keys({ name: Joi.string() }); var config = { validate: { body: validator }}; admin.post('/user', config, async function(ctx){ console.log(ctx.body); }) async function commonHandler(ctx){ // ... } admin.post('/account', [commonHandler, async function(ctx){ // ... }]); @param {String} path @param {Object} [config] optional @param {async function|async function[]} handler(s) @return {App} self
(anonymous)
javascript
koajs/joi-router
joi-router.js
https://github.com/koajs/joi-router/blob/master/joi-router.js
MIT
params(path, captures, params = {}) { for (let len = captures.length, i = 0; i < len; i++) { if (this.paramNames[i]) { const c = captures[i]; if (c && c.length > 0) params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c; } } return params; }
Returns map of URL parameters for given `path` and `paramNames`. @param {String} path @param {Array.<String>} captures @param {Object=} params @returns {Object} @private
params ( path , captures , params = { } )
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
url(params, options) { let args = params; const url = this.path.replace(/\(\.\*\)/g, ''); if (typeof params !== 'object') { args = Array.prototype.slice.call(arguments); if (typeof args[args.length - 1] === 'object') { options = args[args.length - 1]; args = args.slice(0, -1); } } const toPath = compile(url, { encode: encodeURIComponent, ...options }); let replaced; const tokens = parse(url); let replace = {}; if (Array.isArray(args)) { for (let len = tokens.length, i = 0, j = 0; i < len; i++) { if (tokens[i].name) replace[tokens[i].name] = args[j++]; } } else if (tokens.some((token) => token.name)) { replace = params; } else if (!options) { options = params; } replaced = toPath(replace); if (options && options.query) { replaced = parseUrl(replaced); if (typeof options.query === 'string') { replaced.search = options.query; } else { replaced.search = undefined; replaced.query = options.query; } return formatUrl(replaced); } return replaced; }
Generate URL for route using given `params`. @example ```javascript const route = new Layer('/users/:id', ['GET'], fn); route.url({ id: 123 }); // => "/users/123" ``` @param {Object} params url parameters @returns {String} @private
url ( params , options )
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
param(param, fn) { const { stack } = this; const params = this.paramNames; const middleware = function (ctx, next) { return fn.call(this, ctx.params[param], ctx, next); }; middleware.param = param; const names = params.map(function (p) { return p.name; }); const x = names.indexOf(param); if (x > -1) { // iterate through the stack, to figure out where to place the handler fn stack.some((fn, i) => { // param handlers are always first, so when we find an fn w/o a param property, stop here // if the param handler at this part of the stack comes after the one we are adding, stop here if (!fn.param || names.indexOf(fn.param) > x) { // inject this param handler right before the current item stack.splice(i, 0, middleware); return true; // then break the loop } }); } return this; }
Run validations on route named parameters. @example ```javascript router .param('user', function (id, ctx, next) { ctx.user = users[id]; if (!ctx.user) return ctx.status = 404; next(); }) .get('/users/:user', function (ctx, next) { ctx.body = ctx.user; }); ``` @param {String} param @param {Function} middleware @returns {Layer} @private
param ( param , fn )
javascript
koajs/router
lib/layer.js
https://github.com/koajs/router/blob/master/lib/layer.js
MIT
constructor(opts = {}) { if (!(this instanceof Router)) return new Router(opts); // eslint-disable-line no-constructor-return this.opts = opts; this.methods = this.opts.methods || [ 'HEAD', 'OPTIONS', 'GET', 'PUT', 'PATCH', 'POST', 'DELETE' ]; this.exclusive = Boolean(this.opts.exclusive); this.params = {}; this.stack = []; this.host = this.opts.host; }
Create a new router. @example Basic usage: ```javascript const Koa = require('koa'); const Router = require('@koa/router'); const app = new Koa(); const router = new Router(); router.get('/', (ctx, next) => { // ctx.router available }); app .use(router.routes()) .use(router.allowedMethods()); ``` @alias module:koa-router @param {Object=} opts @param {Boolean=false} opts.exclusive only run last matched route's controller when there are multiple matches @param {String=} opts.prefix prefix router paths @param {String|RegExp=} opts.host host for router match @constructor
constructor ( opts = { } )
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
static url(path, ...args) { return Layer.prototype.url.apply({ path }, args); }
Generate URL from url pattern and given `params`. @example ```javascript const url = Router.url('/users/:id', {id: 1}); // => "/users/1" ``` @param {String} path url pattern @param {Object} params url parameters @returns {String}
url ( path , ... args )
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
matchHost(input) { const { host } = this; if (!host) { return true; } if (!input) { return false; } if (typeof host === 'string') { return input === host; } if (typeof host === 'object' && host instanceof RegExp) { return host.test(input); } }
Match given `input` to allowed host @param {String} input @returns {boolean}
matchHost ( input )
javascript
koajs/router
lib/router.js
https://github.com/koajs/router/blob/master/lib/router.js
MIT
export function throttle (func, wait, options = {}) { let context, args, result let timeout = null const leadingDelay = options.leadingDelay === undefined ? false : options.leadingDelay // 上次执行时间点 let previous = 0 // 延迟执行函数 const later = function () { // 若设定了开始边界不执行选项,上次执行时间始终为0 previous = options.leading === false ? 0 : (+new Date()) timeout = null // $flow-disable-line result = func.apply(context, args) if (!timeout) { context = args = null } } return function () { const now = (+new Date()) // 首次执行时,如果设定了开始边界不执行选项,将上次执行时间设定为当前时间。 if (!previous && options.leading === false) { previous = now } // 延迟执行时间间隔 const remaining = wait - (now - previous) context = this args = arguments; // eslint-disable-line // 延迟时间间隔remaining小于等于0,表示上次执行至此所间隔时间已经超过一个时间窗口 // remaining大于时间窗口wait,表示客户端系统时间被调整过 if (remaining <= 0 || remaining > wait) { clearTimeout(timeout) timeout = null previous = now if (leadingDelay === false) { result = func.apply(context, args) } else { setTimeout(() => { result = func.apply(context, args) }, leadingDelay) } if (!timeout) { context = args = null } // 如果延迟执行不存在,且没有设定结尾边界不执行选项 } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining) } return result } };
频率控制 返回函数连续调用时,func 执行频率限定为 次 / wait @param {function} func 传入函数 @param {number} wait 表示时间窗口的间隔 @param {object} [options] 如果想忽略开始边界上的调用,传入{leading: false}。 @param {boolean} [options.leading=true] 如果想忽略开始边界上的调用,传入{leading: false}。 @param {number|boolean} [options.leadingDelay=false] 开始边界上的调用延时,传入{leadingDelay: 0}。 @param {boolean} [options.trailing=true] 如果想忽略结尾边界上的调用,传入{trailing: false} @return {Function} @example const throttleCallback = throttle(callback, 100);
throttle ( func , wait , options = { } )
javascript
kaola-fed/megalo
src/platforms/mp/util/throttle.js
https://github.com/kaola-fed/megalo/blob/master/src/platforms/mp/util/throttle.js
MIT
hasClass (element, className) { return !!element.className.match(className); }
Convenience function to check if an element has a class @param {Node} element Element to check classname on @param {string} className Class name to check for @return {Boolean} true, if class is available on modal
hasClass ( element , className )
javascript
drublic/css-modal
js/Helpers.js
https://github.com/drublic/css-modal/blob/master/js/Helpers.js
MIT
_scale () { // Eject if no active element is set if (!this.activeElement) { return; } this._currentMaxWidth = this.activeElement.getAttribute('data-cssmodal-maxwidth'); this._currentMaxWidth = parseInt(this._currentMaxWidth, 10); if (this._currentMaxWidth) { injectStyles(` [data-cssmodal-maxwidth] .modal-inner { max-width: ${this._currentMaxWidth}px; margin-left: -${this._currentMaxWidth / 2}px; } [data-cssmodal-maxwidth] .modal-close:after { margin-right: -${this._currentMaxWidth / 2}px !important; } `, this.activeElement.id); } }
Scale the modal according to its custom width
_scale ( )
javascript
drublic/css-modal
js/CSSModalMaxwidth.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalMaxwidth.js
MIT
_setPreviousItem () { if (this._currentItem === 0) { this._currentItem = (this._items.length - 1); } else { this._currentItem--; } }
Decreases the counter for the active item regarding the "endless" setting. @return {void}
_setPreviousItem ( )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
showPrevious (event) { event.preventDefault(); event.stopPropagation(); this._setPreviousItem(); this.setActiveItem(this._currentItem); }
Shows the content previous to the current item @param {Object} event The incoming touch/click event @return {void}
showPrevious ( event )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_setNextItem () { if (this._currentItem === (this._items.length - 1)) { this._currentItem = 0; } else { this._currentItem++; } }
Increases the counter for the active item regarding the "endless" setting. @return {void}
_setNextItem ( )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
showNext (event) { event.preventDefault(); event.stopPropagation(); this._setNextItem(); this.setActiveItem(this._currentItem); }
Shows the content next to the current item @param {Object} event The incoming touch/click event @return {void}
showNext ( event )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_getDetailView (element) { let container = element.querySelectorAll('.css-modal_detail')[0]; if (!container) { throw new Error('".css-modal_detail" not found!'); } return container; }
Returns the detail image element @param {Object} element The current CSS Modal instance @return {Object} The detail image
_getDetailView ( element )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_initNavigation (event, eventData) { if (arguments.length === 2) { this._activeElement = eventData.detail.modal; } else { this._activeElement = event.detail.modal; } if (this._activeElement.querySelectorAll('.css-modal_detail').length === 0) { return; } // Bind events on the current modal element and set the currentItem to 0 if (!this._activeElement._galleryEventsBound) { this._bindEvents(this._activeElement); this._activeElement._galleryEventsBound = true; this._activeElement._currentItem = 0; } // If we have an incoming index, override the current item if ('index' in this._activeElement) { this._activeElement._currentItem = this._activeElement.index; } this._detailView = this._getDetailView(this._activeElement); this._currentItem = this._activeElement._currentItem; this._items = this._readContent(this._activeElement); this.setActiveItem(this._currentItem); }
Registers the listerns on the previous / next buttons to enable gallery navigation @return {void}
_initNavigation ( event , eventData )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_onKeyPress (event) { if (event.keyCode === 39) { this.showNext(event); } else if (event.keyCode === 37) { this.showPrevious(event); } }
Reacts to specific keyboard commands to enable viewing a differnt item in the gallery @param {Object} event The incoming keypress event @return {void}
_onKeyPress ( event )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_bindEvents (element) { var events = ['click', 'touch']; // Setup touch / click events this._prev = element.querySelectorAll('.modal--gallery-navigation-prev')[0]; this._next = element.querySelectorAll('.modal--gallery-navigation-next')[0]; for (let i = 0; i < events.length; i++) { this.Helpers.on(events[i], this._prev, this.showPrevious); this.Helpers.on(events[i], this._next, this.showNext); } // Setup keyboard events this.Helpers.on('keydown', document, this._onKeyPress); // Setup swipe events this.Helpers.on('touch:swipe-left', element, this.showPrevious); this.Helpers.on('touch:swipe-right', element, this.showNext); }
Wires the previous / next button to the function to navigation through the gallery @param {Object} element The CSSModal to set up @return {void}
_bindEvents ( element )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_readContent (element) { let contentList = element.querySelectorAll('.css-modal_content-list')[0]; return contentList.getElementsByTagName('li'); }
Gathers information about the gallery content and stores it. @param {Object} element The CSSModal to receive the content from @return {void}
_readContent ( element )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
setCaption (caption) { let captionElement = this._activeElement.querySelectorAll('.css_modal--gallery_caption')[0]; if (!captionElement) { return; } captionElement.innerHTML = ''; if (caption) { captionElement.innerHTML = '<p>' + caption + '</p>'; } }
Set a caption for a given modal @param {String} caption Caption to insert
setCaption ( caption )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
setActiveItem (index) { if (!this._items[index]) { throw new Error('CSS-Modal: Invalid index "' + index + '"!'); } var content = this._items[index].innerHTML; var img = new Image(); var referenceImage; this._detailView.innerHTML = content; // Position for loading indicator and hide content this.Helpers.trigger('cssmodal:resize', this._activeElement); this.Helpers.removeClass(this._detailView, 'is-active'); // Set a caption for the modal this.setCaption(this._items[index].getAttribute('data-caption')); // Load the original image, if we are in a gallery if (this._activeElement.getAttribute('class').indexOf('modal--gallery') !== -1) { referenceImage = this._detailView.getElementsByTagName('img')[0]; if (referenceImage.parentNode.getAttribute('data-iframe') !== null) { img = document.createElement('iframe'); img.src = referenceImage.getAttribute('data-src-fullsize'); img.setAttribute('webkitallowfullscreen', true); img.setAttribute('mozallowfullscreen', true); img.setAttribute('allowfullscreen', true); } else { img.src = referenceImage.getAttribute('data-src-fullsize'); img.alt = referenceImage.getAttribute('alt'); } // Reposition and show this.Helpers.on('load', img, () => { this.Helpers.addClass(this._detailView, 'is-active'); this.Helpers.trigger('cssmodal:resize', this._activeElement); }); referenceImage.parentNode.insertBefore(img, referenceImage); referenceImage.parentNode.removeChild(referenceImage); this._detailView.style.width = 'auto'; this._detailView.style.height = 'auto'; } }
Shows the full content of the designated item @param {Number} index The index of the item to show
setActiveItem ( index )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
_storeActiveItem () { this._activeElement._currentItem = this._currentItem; }
Store the index of the currently active item on the gallery instance @param {Number} item The index to store @return {void}
_storeActiveItem ( )
javascript
drublic/css-modal
js/CSSModalGallery.js
https://github.com/drublic/css-modal/blob/master/js/CSSModalGallery.js
MIT
const _injectStyles = (rule, id) => { id = 'modal__rule--' + (id || ''); let head = document.querySelector('head'); let existingStyleElement = document.getElementById(id); let styleElement = null; if (existingStyleElement) { styleElement = existingStyleElement; } else { styleElement = document.createElement('style'); styleElement.id = id; } styleElement.innerHTML = rule; head.appendChild(styleElement); };
Include styles into the DOM @param {string} rule Styles to inject into the DOM @param {string} id Unique ID for styles
_injectStyles
javascript
drublic/css-modal
js/Helper/injectStyles.js
https://github.com/drublic/css-modal/blob/master/js/Helper/injectStyles.js
MIT