How to use _hasContext method in Puppeteer

Best JavaScript code snippet using puppeteer

promise.js

Source:promise.js Github

copy

Full Screen

1/**2 * Adapted from Medium's kew, and re-released under the BSD License.3 * Medium's kew was originally released under the Apache License, but our understanding is that4 * Apache allows re-licensing of derivative work. We opt to relicense as BSD.5 */6/**7 * An object representing a "promise" for a future value8 *9 * @param {?function(T, ?)=} onSuccess a function to handle successful10 * resolution of this promise11 * @param {?function(!Error, ?)=} onFail a function to handle failed12 * resolution of this promise13 * @constructor14 * @template T15 */16function Promise(onSuccess, onFail) {17 this.promise = this18 this._isPromise = true19 this._successFn = onSuccess20 this._failFn = onFail21 this._scope = this22 this._boundArgs = null23 this._hasContext = false24 this._nextContext = undefined25 this._currentContext = undefined26}27/**28 * @param {function()} callback29 */30function nextTick (callback) {31 callback()32}33if (typeof process !== 'undefined' && typeof process.nextTick === 'function') {34 nextTick = process.nextTick35}36/**37 * All callback execution should go through this function. While the38 * implementation below is simple, it can be replaced with more sophisticated39 * implementations that enforce QoS on the event loop.40 *41 * @param {Promise} defer42 * @param {Function} callback43 * @param {Object|undefined} scope44 * @param {Array} args45 */46function nextTickCallback (defer, callback, scope, args) {47 try {48 defer.resolve(callback.apply(scope, args))49 } catch (thrown) {50 defer.reject(thrown)51 }52}53/**54 * Used for accessing the nextTick function from outside the kew module.55 *56 * @return {Function}57 */58function getNextTickFunction () {59 return nextTick60}61/**62 * Used for overriding the nextTick function from outside the kew module so that63 * the user can plug and play lower level schedulers64 * @param {!Function} fn65 */66function setNextTickFunction (fn) {67 nextTick = fn68}69/**70 * Keep track of the number of promises that are rejected along side71 * the number of rejected promises we call _failFn on so we can look72 * for leaked rejections.73 * @constructor74 */75function PromiseStats() {76 /** @type {number} */77 this.errorsEmitted = 078 /** @type {number} */79 this.errorsHandled = 080}81var stats = new PromiseStats()82Promise.prototype._handleError = function () {83 if (!this._errorHandled) {84 stats.errorsHandled++85 this._errorHandled = true86 }87}88/**89 * Specify that the current promise should have a specified context90 * @param {*} context context91 * @private92 */93Promise.prototype._useContext = function (context) {94 this._nextContext = this._currentContext = context95 this._hasContext = true96 return this97}98Promise.prototype.clearContext = function () {99 this._hasContext = false100 this._nextContext = undefined101 return this102}103/**104 * Set the context for all promise handlers to follow105 *106 * NOTE(dpup): This should be considered deprecated. It does not do what most107 * people would expect. The context will be passed as a second argument to all108 * subsequent callbacks.109 *110 * @param {*} context An arbitrary context111 */112Promise.prototype.setContext = function (context) {113 this._nextContext = context114 this._hasContext = true115 return this116}117/**118 * Get the context for a promise119 * @return {*} the context set by setContext120 */121Promise.prototype.getContext = function () {122 return this._nextContext123}124/**125 * Resolve this promise with a specified value126 *127 * @param {*=} data128 */129Promise.prototype.resolve = function (data) {130 if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")131 var i132 if (data && isPromise(data)) {133 this._child = data134 if (this._promises) {135 for (i = 0; i < this._promises.length; i += 1) {136 data._chainPromise(this._promises[i])137 }138 delete this._promises139 }140 if (this._onComplete) {141 for (i = 0; i < this._onComplete.length; i+= 1) {142 data.fin(this._onComplete[i])143 }144 delete this._onComplete145 }146 } else if (data && isPromiseLike(data)) {147 data.then(148 function(data) { this.resolve(data) }.bind(this),149 function(err) { this.reject(err) }.bind(this)150 )151 } else {152 this._hasData = true153 this._data = data154 if (this._onComplete) {155 for (i = 0; i < this._onComplete.length; i++) {156 this._onComplete[i]()157 }158 }159 if (this._promises) {160 for (i = 0; i < this._promises.length; i += 1) {161 this._promises[i]._useContext(this._nextContext)162 this._promises[i]._withInput(data)163 }164 delete this._promises165 }166 }167}168/**169 * Reject this promise with an error170 *171 * @param {!Error} e172 */173Promise.prototype.reject = function (e) {174 if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")175 var i176 this._error = e177 stats.errorsEmitted++178 if (this._ended) {179 this._handleError()180 process.nextTick(function onPromiseThrow() {181 throw e182 })183 }184 if (this._onComplete) {185 for (i = 0; i < this._onComplete.length; i++) {186 this._onComplete[i]()187 }188 }189 if (this._promises) {190 this._handleError()191 for (i = 0; i < this._promises.length; i += 1) {192 this._promises[i]._useContext(this._nextContext)193 this._promises[i]._withError(e)194 }195 delete this._promises196 }197}198/**199 * Provide a callback to be called whenever this promise successfully200 * resolves. Allows for an optional second callback to handle the failure201 * case.202 *203 * @param {?function(this:void, T, ?): RESULT|undefined} onSuccess204 * @param {?function(this:void, !Error, ?): RESULT=} onFail205 * @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess or206 * onFail handler207 * @template RESULT208 */209Promise.prototype.then = function (onSuccess, onFail) {210 var promise = new Promise(onSuccess, onFail)211 if (this._nextContext) promise._useContext(this._nextContext)212 if (this._child) this._child._chainPromise(promise)213 else this._chainPromise(promise)214 return promise215}216/**217 * Provide a callback to be called whenever this promise successfully218 * resolves. The callback will be executed in the context of the provided scope.219 *220 * @param {function(this:SCOPE, ...): RESULT} onSuccess221 * @param {SCOPE} scope Object whose context callback will be executed in.222 * @param {...*} var_args Additional arguments to be passed to the promise callback.223 * @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess224 * @template SCOPE, RESULT225 */226Promise.prototype.thenBound = function (onSuccess, scope, var_args) {227 var promise = new Promise(onSuccess)228 if (this._nextContext) promise._useContext(this._nextContext)229 promise._scope = scope230 if (arguments.length > 2) {231 promise._boundArgs = Array.prototype.slice.call(arguments, 2)232 }233 // Chaining must happen after setting args and scope since it may fire callback.234 if (this._child) this._child._chainPromise(promise)235 else this._chainPromise(promise)236 return promise237}238/**239 * Provide a callback to be called whenever this promise is rejected240 *241 * @param {function(this:void, !Error, ?)} onFail242 * @return {!Promise.<T>} returns a new promise with the output of the onFail handler243 */244Promise.prototype.fail = function (onFail) {245 return this.then(null, onFail)246}247/**248 * Provide a callback to be called whenever this promise is rejected.249 * The callback will be executed in the context of the provided scope.250 *251 * @param {function(this:SCOPE, ...)} onFail252 * @param {SCOPE} scope Object whose context callback will be executed in.253 * @param {...?} var_args254 * @return {!Promise.<T>} returns a new promise with the output of the onSuccess255 * @template SCOPE256 */257Promise.prototype.failBound = function (onFail, scope, var_args) {258 var promise = new Promise(null, onFail)259 if (this._nextContext) promise._useContext(this._nextContext)260 promise._scope = scope261 if (arguments.length > 2) {262 promise._boundArgs = Array.prototype.slice.call(arguments, 2)263 }264 // Chaining must happen after setting args and scope since it may fire callback.265 if (this._child) this._child._chainPromise(promise)266 else this._chainPromise(promise)267 return promise268}269/**270 * Spread a promises outputs to the functions arguments.271 * @param {?function(this:void, ...): RESULT|undefined} onSuccess272 * @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess or273 * onFail handler274 * @template RESULT275 */276Promise.prototype.spread = function (onSuccess) {277 return this.then(allInternal)278 .then(function (array) {279 return onSuccess.apply(null, array)280 })281}282/**283 * Spread a promises outputs to the functions arguments.284 * @param {function(this:SCOPE, ...): RESULT} onSuccess285 * @param {SCOPE} scope Object whose context callback will be executed in.286 * @param {...*} var_args Additional arguments to be passed to the promise callback.287 * @return {!Promise.<RESULT>} returns a new promise with the output of the onSuccess288 * @template SCOPE, RESULT289 */290Promise.prototype.spreadBound = function (onSuccess, scope, var_args) {291 var args = Array.prototype.slice.call(arguments, 2)292 return this.then(allInternal)293 .then(function (array) {294 return onSuccess.apply(scope, args.concat(array))295 })296}297/**298 * Provide a callback to be called whenever this promise is either resolved299 * or rejected.300 *301 * @param {function()} onComplete302 * @return {!Promise.<T>} returns the current promise303 */304Promise.prototype.fin = function (onComplete) {305 if (this._hasData || this._error) {306 onComplete()307 return this308 }309 if (this._child) {310 this._child.fin(onComplete)311 } else {312 if (!this._onComplete) this._onComplete = [onComplete]313 else this._onComplete.push(onComplete)314 }315 return this316}317/**318 * Mark this promise as "ended". If the promise is rejected, this will throw an319 * error in whatever scope it happens to be in320 *321 * @return {!Promise.<T>} returns the current promise322 * @deprecated Prefer done(), because it's consistent with Q.323 */324Promise.prototype.end = function () {325 this._end()326 return this327}328/**329 * Mark this promise as "ended".330 * @private331 */332Promise.prototype._end = function () {333 if (this._error) {334 this._handleError()335 throw this._error336 }337 this._ended = true338 return this339}340/**341 * Close the promise. Any errors after this completes will be thrown to the global handler.342 *343 * @param {?function(this:void, T, ?)=} onSuccess a function to handle successful344 * resolution of this promise345 * @param {?function(this:void, !Error, ?)=} onFailure a function to handle failed346 * resolution of this promise347 * @return {void}348 */349Promise.prototype.done = function (onSuccess, onFailure) {350 var self = this351 if (onSuccess || onFailure) {352 self = self.then(onSuccess, onFailure)353 }354 self._end()355}356/**357 * Return a new promise that behaves the same as the current promise except358 * that it will be rejected if the current promise does not get fulfilled359 * after a certain amount of time.360 *361 * @param {number} timeoutMs The timeout threshold in msec362 * @param {string=} timeoutMsg error message363 * @return {!Promise.<T>} a new promise with timeout364 */365 Promise.prototype.timeout = function (timeoutMs, timeoutMsg) {366 var deferred = new Promise()367 var isTimeout = false368 var timeout = setTimeout(function() {369 deferred.reject(new Error(timeoutMsg || 'Promise timeout after ' + timeoutMs + ' ms.'))370 isTimeout = true371 }, timeoutMs)372 this.then(function (data) {373 if (!isTimeout) {374 clearTimeout(timeout)375 deferred.resolve(data)376 }377 },378 function (err) {379 if (!isTimeout) {380 clearTimeout(timeout)381 deferred.reject(err)382 }383 })384 return deferred.promise385}386/**387 * Attempt to resolve this promise with the specified input388 *389 * @param {*} data the input390 */391Promise.prototype._withInput = function (data) {392 if (this._successFn) {393 this._nextTick(this._successFn, [data, this._currentContext])394 } else {395 this.resolve(data)396 }397 // context is no longer needed398 delete this._currentContext399}400/**401 * Attempt to reject this promise with the specified error402 *403 * @param {!Error} e404 * @private405 */406Promise.prototype._withError = function (e) {407 if (this._failFn) {408 this._nextTick(this._failFn, [e, this._currentContext])409 } else {410 this.reject(e)411 }412 // context is no longer needed413 delete this._currentContext414}415/**416 * Calls a function in the correct scope, and includes bound arguments.417 * @param {Function} fn418 * @param {Array} args419 * @private420 */421Promise.prototype._nextTick = function (fn, args) {422 if (this._boundArgs) {423 args = this._boundArgs.concat(args)424 }425 nextTick(nextTickCallback.bind(null, this, fn, this._scope, args))426}427/**428 * Chain a promise to the current promise429 *430 * @param {!Promise} promise the promise to chain431 * @private432 */433Promise.prototype._chainPromise = function (promise) {434 var i435 if (this._hasContext) promise._useContext(this._nextContext)436 if (this._child) {437 this._child._chainPromise(promise)438 } else if (this._hasData) {439 promise._withInput(this._data)440 } else if (this._error) {441 // We can't rely on _withError() because it's called on the chained promises442 // and we need to use the source's _errorHandled state443 this._handleError()444 promise._withError(this._error)445 } else if (!this._promises) {446 this._promises = [promise]447 } else {448 this._promises.push(promise)449 }450}451/**452 * Utility function used for creating a node-style resolver453 * for deferreds454 *455 * @param {!Promise} deferred a promise that looks like a deferred456 * @param {Error=} err an optional error457 * @param {*=} data optional data458 */459function resolver(deferred, err, data) {460 if (err) deferred.reject(err)461 else deferred.resolve(data)462}463/**464 * Creates a node-style resolver for a deferred by wrapping465 * resolver()466 *467 * @return {function(?Error, *)} node-style callback468 */469Promise.prototype.makeNodeResolver = function () {470 return resolver.bind(null, this)471}472/**473 * Return true iff the given object is a promise of this library.474 *475 * Because kew's API is slightly different than other promise libraries,476 * it's important that we have a test for its promise type. If you want477 * to test for a more general A+ promise, you should do a cap test for478 * the features you want.479 *480 * @param {*} obj The object to test481 * @return {boolean} Whether the object is a promise482 */483function isPromise(obj) {484 return !!obj._isPromise485}486/**487 * Return true iff the given object is a promise-like object, e.g. appears to488 * implement Promises/A+ specification489 *490 * @param {*} obj The object to test491 * @return {boolean} Whether the object is a promise-like object492 */493function isPromiseLike(obj) {494 return (typeof obj === 'object' || typeof obj === 'function') &&495 typeof obj.then === 'function'496}497/**498 * Static function which creates and resolves a promise immediately499 *500 * @param {T} data data to resolve the promise with501 * @return {!Promise.<T>}502 * @template T503 */504function resolve(data) {505 var promise = new Promise()506 promise.resolve(data)507 return promise508}509/**510 * Static function which creates and rejects a promise immediately511 *512 * @param {!Error} e error to reject the promise with513 * @return {!Promise}514 */515function reject(e) {516 var promise = new Promise()517 promise.reject(e)518 return promise519}520/**521 * Replace an element in an array with a new value. Used by .all() to522 * call from .then()523 *524 * @param {!Array} arr525 * @param {number} idx526 * @param {*} val527 * @return {*} the val that's being injected into the array528 */529function replaceEl(arr, idx, val) {530 arr[idx] = val531 return val532}533/**534 * Replace an element in an array as it is resolved with its value.535 * Used by .allSettled().536 *537 * @param {!Array} arr538 * @param {number} idx539 * @param {*} value The value from a resolved promise.540 * @return {*} the data that's being passed in541 */542function replaceElFulfilled(arr, idx, value) {543 arr[idx] = {544 state: 'fulfilled',545 value: value546 }547 return value548}549/**550 * Replace an element in an array as it is rejected with the reason.551 * Used by .allSettled().552 *553 * @param {!Array} arr554 * @param {number} idx555 * @param {*} reason The reason why the original promise is rejected556 * @return {*} the data that's being passed in557 */558function replaceElRejected(arr, idx, reason) {559 arr[idx] = {560 state: 'rejected',561 reason: reason562 }563 return reason564}565/**566 * Takes in an array of promises or literals and returns a promise which returns567 * an array of values when all have resolved. If any fail, the promise fails.568 *569 * @param {!Array.<!Promise>} promises570 * @return {!Promise.<!Array>}571 */572function all(promises) {573 if (arguments.length != 1 || !Array.isArray(promises)) {574 promises = Array.prototype.slice.call(arguments, 0)575 }576 return allInternal(promises)577}578/**579 * A version of all() that does not accept var_args580 *581 * @param {!Array.<!Promise>} promises582 * @return {!Promise.<!Array>}583 */584function allInternal(promises) {585 if (!promises.length) return resolve([])586 var outputs = []587 var finished = false588 var promise = new Promise()589 var counter = promises.length590 for (var i = 0; i < promises.length; i += 1) {591 if (!promises[i] || !isPromiseLike(promises[i])) {592 outputs[i] = promises[i]593 counter -= 1594 } else {595 promises[i].then(replaceEl.bind(null, outputs, i))596 .then(function decrementAllCounter() {597 counter--598 if (!finished && counter === 0) {599 finished = true600 promise.resolve(outputs)601 }602 }, function onAllError(e) {603 if (!finished) {604 finished = true605 promise.reject(e)606 }607 })608 }609 }610 if (counter === 0 && !finished) {611 finished = true612 promise.resolve(outputs)613 }614 return promise615}616/**617 * Takes in an array of promises or values and returns a promise that is618 * fulfilled with an array of state objects when all have resolved or619 * rejected. If a promise is resolved, its corresponding state object is620 * {state: 'fulfilled', value: Object}; whereas if a promise is rejected, its621 * corresponding state object is {state: 'rejected', reason: Object}.622 *623 * @param {!Array} promises or values624 * @return {!Promise.<!Array>} Promise fulfilled with state objects for each input625 */626function allSettled(promises) {627 if (!Array.isArray(promises)) {628 throw Error('The input to "allSettled()" should be an array of Promise or values')629 }630 if (!promises.length) return resolve([])631 var outputs = []632 var promise = new Promise()633 var counter = promises.length634 for (var i = 0; i < promises.length; i += 1) {635 if (!promises[i] || !isPromiseLike(promises[i])) {636 replaceElFulfilled(outputs, i, promises[i])637 if ((--counter) === 0) promise.resolve(outputs)638 } else {639 promises[i]640 .then(replaceElFulfilled.bind(null, outputs, i), replaceElRejected.bind(null, outputs, i))641 .then(function () {642 if ((--counter) === 0) promise.resolve(outputs)643 })644 }645 }646 return promise647}648/**649 * Takes an array of results and spreads them to the arguments of a function.650 * @param {!Array} array651 * @param {!Function} fn652 */653function spread(array, fn) {654 resolve(array).spread(fn)655}656/**657 * Create a new Promise which looks like a deferred658 *659 * @return {!Promise}660 */661function defer() {662 return new Promise()663}664/**665 * Return a promise which will wait a specified number of ms to resolve666 *667 * @param {*} delayMsOrVal A delay (in ms) if this takes one argument, or ther668 * return value if it takes two.669 * @param {number=} opt_delayMs670 * @return {!Promise}671 */672function delay(delayMsOrVal, opt_delayMs) {673 var returnVal = undefined674 var delayMs = delayMsOrVal675 if (typeof opt_delayMs != 'undefined') {676 delayMs = opt_delayMs677 returnVal = delayMsOrVal678 }679 if (typeof delayMs != 'number') {680 throw new Error('Bad delay value ' + delayMs)681 }682 var defer = new Promise()683 setTimeout(function onDelay() {684 defer.resolve(returnVal)685 }, delayMs)686 return defer687}688/**689 * Returns a promise that has the same result as `this`, but fulfilled690 * after at least ms milliseconds691 * @param {number} ms692 */693Promise.prototype.delay = function (ms) {694 return this.then(function (val) {695 return delay(val, ms)696 })697}698/**699 * Return a promise which will evaluate the function fn in a future turn with700 * the provided args701 *702 * @param {function(...)} fn703 * @param {...*} var_args a variable number of arguments704 * @return {!Promise}705 */706function fcall(fn, var_args) {707 var rootArgs = Array.prototype.slice.call(arguments, 1)708 var defer = new Promise()709 nextTick(nextTickCallback.bind(null, defer, fn, undefined, rootArgs))710 return defer711}712/**713 * Returns a promise that will be invoked with the result of a node style714 * callback. All args to fn should be given except for the final callback arg715 *716 * @param {function(...)} fn717 * @param {...*} var_args a variable number of arguments718 * @return {!Promise}719 */720function nfcall(fn, var_args) {721 // Insert an undefined argument for scope and let bindPromise() do the work.722 var args = Array.prototype.slice.call(arguments, 0)723 args.splice(1, 0, undefined)724 return ncall.apply(undefined, args)725}726/**727 * Like `nfcall`, but permits passing a `this` context for the call.728 *729 * @param {function(...)} fn730 * @param {Object} scope731 * @param {...*} var_args732 * @return {!Promise}733 */734function ncall(fn, scope, var_args) {735 return bindPromise.apply(null, arguments)()736}737/**738 * Binds a function to a scope with an optional number of curried arguments. Attaches739 * a node style callback as the last argument and returns a promise740 *741 * @param {function(...)} fn742 * @param {Object} scope743 * @param {...*} var_args a variable number of arguments744 * @return {function(...)}: !Promise}745 */746function bindPromise(fn, scope, var_args) {747 var rootArgs = Array.prototype.slice.call(arguments, 2)748 return function onBoundPromise(var_args) {749 var defer = new Promise()750 try {751 fn.apply(scope, rootArgs.concat(Array.prototype.slice.call(arguments, 0), defer.makeNodeResolver()))752 } catch (e) {753 defer.reject(e)754 }755 return defer756 }757}758module.exports = {759 all: all,760 bindPromise: bindPromise,761 defer: defer,762 delay: delay,763 fcall: fcall,764 isPromise: isPromise,765 isPromiseLike: isPromiseLike,766 ncall: ncall,767 nfcall: nfcall,768 resolve: resolve,769 reject: reject,770 spread: spread,771 stats: stats,772 allSettled: allSettled,773 Promise: Promise,774 getNextTickFunction: getNextTickFunction,775 setNextTickFunction: setNextTickFunction,...

Full Screen

Full Screen

ContextMenu.js

Source:ContextMenu.js Github

copy

Full Screen

1import ContextMenuOperations from './ContextMenuOperations';2import defaults from '../defaults';3import ContextMenuHtml5Builder from './ContextMenuHtml5Builder';4import ContextMenuEventHandler from './ContextMenuEventHandler';5export default class ContextMenu {6 /**7 * @constructor8 * @constructs ContextMenu9 * @classdesc The ContextMenu is the core class that manages contextmenu's. You can call this class directly and skip going through jQuery.10 * @class ContextMenu11 *12 * @example13 * // You can call this class directly and skip going through jQuery, although it still requires jQuery to run.14 * const manager = new ContextMenu();15 * manager.execute("create", options);16 *17 * @property {ContextMenuOptions|Object} defaults18 * @property {ContextMenuEventHandler} handle19 * @property {ContextMenuOperations} operations20 * @property {Object<string, ContextMenuData>} menus21 * @property {number} counter - Internal counter to keep track of different menu's on the page.22 * @property {boolean} initialized - Flag the menu as initialized.23 */24 constructor() {25 this.html5builder = new ContextMenuHtml5Builder();26 this.defaults = defaults;27 this.handler = new ContextMenuEventHandler();28 this.operations = new ContextMenuOperations();29 this.namespaces = {};30 this.initialized = false;31 this.menus = {};32 this.counter = 0;33 }34 /**35 * @method execute36 * @memberOf ContextMenu37 * @instance38 *39 * @param {(string|ContextMenuOptions)} operation40 * @param {(string|ContextMenuOptions)} options41 * @return {ContextMenu}42 */43 execute(operation, options) {44 const normalizedArguments = this.normalizeArguments(operation, options);45 operation = normalizedArguments.operation;46 options = normalizedArguments.options;47 switch (operation) {48 case 'update':49 // Updates visibility and such50 this.update(options);51 break;52 case 'create':53 // no selector no joy54 this.create(options);55 break;56 case 'destroy':57 this.destroy(options);58 break;59 case 'html5':60 this.html5(options);61 break;62 default:63 throw new Error('Unknown operation "' + operation + '"');64 }65 return this;66 }67 /**68 * if <menuitem> is not handled by the browser, or options was a bool true, initialize $.contextMenu for them.69 * @method html570 * @memberOf ContextMenu71 *72 * @param {ContextMenuOptions|boolean} options73 */74 html5(options) {75 options = this.buildOptions(options);76 const menuItemSupport = ('contextMenu' in document.body && 'HTMLMenuItemElement' in window);77 if (!menuItemSupport || (typeof options === 'boolean' && options === true)) {78 $('menu[type="context"]').each(function () {79 if (this.id) {80 $.contextMenu({81 selector: '[contextmenu=' + this.id + ']',82 items: $.contextMenu.fromMenu(this)83 });84 }85 }).css('display', 'none');86 }87 }88 /**89 * Destroy the ContextMenu90 * @method destroy91 * @memberOf ContextMenu92 *93 * @param {ContextMenuOptions} options94 */95 destroy(options) {96 options = this.buildOptions(options);97 let $visibleMenu;98 if (options._hasContext) {99 // get proper options100 const context = options.context;101 Object.keys(this.menus).forEach((ns) => {102 let o = this.menus[ns];103 if (!o) {104 return true;105 }106 // Is this menu equest to the context called from107 if (!$(context).is(o.selector)) {108 return true;109 }110 $visibleMenu = $('.context-menu-list').filter(':visible');111 if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is($(o.context).find(o.selector))) {112 $visibleMenu.trigger('contextmenu:hide', {force: true});113 }114 if (this.menus[o.ns].$menu) {115 this.menus[o.ns].$menu.remove();116 }117 delete this.menus[o.ns];118 $(o.context).off(o.ns);119 return true;120 });121 } else if (!options.selector) {122 $(document).off('.contextMenu .contextMenuAutoHide');123 Object.keys(this.menus).forEach((ns) => {124 let o = this.menus[ns];125 $(o.context).off(o.ns);126 });127 this.namespaces = {};128 this.menus = {};129 this.counter = 0;130 this.initialized = false;131 $('#context-menu-layer, .context-menu-list').remove();132 } else if (this.namespaces[options.selector]) {133 $visibleMenu = $('.context-menu-list').filter(':visible');134 if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(options.selector)) {135 $visibleMenu.trigger('contextmenu:hide', {force: true});136 }137 if (this.menus[this.namespaces[options.selector]].$menu) {138 this.menus[this.namespaces[options.selector]].$menu.remove();139 }140 delete this.menus[this.namespaces[options.selector]];141 $(document).off(this.namespaces[options.selector]);142 }143 this.handler.$currentTrigger = null;144 }145 /**146 * Create a ContextMenu147 * @method create148 * @memberOf ContextMenu149 *150 * @param {ContextMenuOptions} options151 */152 create(options) {153 options = this.buildOptions(options);154 if (!options.selector) {155 throw new Error('No selector specified');156 }157 // make sure internal classes are not bound to158 if (options.selector.match(/.context-menu-(list|item|input)($|\s)/)) {159 throw new Error('Cannot bind to selector "' + options.selector + '" as it contains a reserved className');160 }161 if (!options.build && (!options.items || $.isEmptyObject(options.items))) {162 throw new Error('No Items specified');163 }164 this.counter++;165 options.ns = '.contextMenu' + this.counter;166 if (!options._hasContext) {167 this.namespaces[options.selector] = options.ns;168 }169 this.menus[options.ns] = options;170 // default to right click171 if (!options.trigger) {172 options.trigger = 'right';173 }174 if (!this.initialized) {175 const itemClick = options.itemClickEvent === 'click' ? 'click.contextMenu' : 'mouseup.contextMenu';176 const contextMenuItemObj = {177 // 'mouseup.contextMenu': this.handler.itemClick,178 // 'click.contextMenu': this.handler.itemClick,179 'contextmenu:focus.contextMenu': this.handler.focusItem,180 'contextmenu:blur.contextMenu': this.handler.blurItem,181 'contextmenu.contextMenu': this.handler.abortevent,182 'mouseenter.contextMenu': this.handler.itemMouseenter,183 'mouseleave.contextMenu': this.handler.itemMouseleave184 };185 contextMenuItemObj[itemClick] = this.handler.itemClick;186 // make sure item click is registered first187 $(document)188 .on({189 'contextmenu:hide.contextMenu': this.handler.hideMenu,190 'prevcommand.contextMenu': this.handler.prevItem,191 'nextcommand.contextMenu': this.handler.nextItem,192 'contextmenu.contextMenu': this.handler.abortevent,193 'mouseenter.contextMenu': this.handler.menuMouseenter,194 'mouseleave.contextMenu': this.handler.menuMouseleave195 }, '.context-menu-list')196 .on('mouseup.contextMenu', '.context-menu-input', this.handler.inputClick)197 .on(contextMenuItemObj, '.context-menu-item');198 this.initialized = true;199 }200 // engage native contextmenu event201 options.context202 .on('contextmenu' + options.ns, options.selector, options, this.handler.contextmenu);203 switch (options.trigger) {204 case 'hover':205 options.context206 .on('mouseenter' + options.ns, options.selector, options, this.handler.mouseenter)207 .on('mouseleave' + options.ns, options.selector, options, this.handler.mouseleave);208 break;209 case 'left':210 options.context.on('click' + options.ns, options.selector, options, this.handler.click);211 break;212 case 'touchstart':213 options.context.on('touchstart' + options.ns, options.selector, options, this.handler.click);214 break;215 /*216 default:217 // http://www.quirksmode.org/dom/events/contextmenu.html218 $document219 .on('mousedown' + o.ns, o.selector, o, this.handler.mousedown)220 .on('mouseup' + o.ns, o.selector, o, this.handler.mouseup);221 break;222 */223 }224 // create menu225 if (!options.build) {226 this.operations.create(null, options);227 }228 }229 /**230 * Update the ContextMenu or all ContextMenu's231 * @method update232 * @memberOf ContextMenu233 *234 * @param {ContextMenuOptions} options235 */236 update(options) {237 options = this.buildOptions(options);238 if (options._hasContext) {239 this.operations.update(null, $(options.context).data('contextMenu'), $(options.context).data('contextMenuRoot'));240 } else {241 Object.keys(this.menus).forEach((menu) => {242 this.operations.update(null, this.menus[menu]);243 });244 }245 }246 /**247 * Build the options, by applying the Manager, defaults, user options and normalizing the context.248 * @method buildOptions249 * @memberOf ContextMenu250 *251 * @param {ContextMenuOptions} userOptions252 * @return {ContextMenuOptions}253 */254 buildOptions(userOptions) {255 if (typeof userOptions === 'string') {256 userOptions = {selector: userOptions};257 }258 const options = $.extend(true, {manager: this}, this.defaults, userOptions);259 if (!options.context || !options.context.length) {260 options.context = $(document);261 options._hasContext = false;262 } else {263 // you never know what they throw at you...264 options.context = $(options.context).first();265 options._hasContext = !$(options.context).is($(document));266 }267 return options;268 }269 /**270 * @method normalizeArguments271 * @memberOf ContextMenu272 *273 * @param {string|Object} operation274 * @param {string|Object|ContextMenuOptions} options275 * @returns {{operation: string, options: ContextMenuOptions}}276 */277 normalizeArguments(operation, options) {278 if (typeof operation !== 'string') {279 options = operation;280 operation = 'create';281 }282 if (typeof options === 'string') {283 options = {selector: options};284 } else if (typeof options === 'undefined') {285 options = {};286 }287 return {operation, options};288 }289 /**290 * import values into `<input>` commands291 *292 * @method setInputValues293 * @memberOf ContextMenu294 * @instance295 *296 * @param {ContextMenuData} contextMenuData - {@link ContextMenuData} object297 * @param {Object} data - Values to set298 * @return {undefined}299 */300 setInputValues(contextMenuData, data) {301 if (typeof data === 'undefined') {302 data = {};303 }304 $.each(contextMenuData.inputs, function (key, item) {305 switch (item.type) {306 case 'text':307 case 'textarea':308 item.value = data[key] || '';309 break;310 case 'checkbox':311 item.selected = !!data[key];312 break;313 case 'radio':314 item.selected = (data[item.radio] || '') === item.value;315 break;316 case 'select':317 item.selected = data[key] || '';318 break;319 }320 });321 }322 /**323 * export values from `<input>` commands324 *325 * @method getInputValues326 * @memberOf ContextMenu327 * @instance328 *329 * @param {ContextMenuData} contextMenuData - {@link ContextMenuData} object330 * @param {Object} data - Values object331 * @return {Object} - Values of input elements332 */333 getInputValues(contextMenuData, data) {334 if (typeof data === 'undefined') {335 data = {};336 }337 $.each(contextMenuData.inputs, function (key, item) {338 switch (item.type) {339 case 'text':340 case 'textarea':341 case 'select':342 data[key] = item.$input.val();343 break;344 case 'checkbox':345 data[key] = item.$input.prop('checked');346 break;347 case 'radio':348 if (item.$input.prop('checked')) {349 data[item.radio] = item.value;350 }351 break;352 }353 });354 return data;355 }...

Full Screen

Full Screen

kew.js

Source:kew.js Github

copy

Full Screen

1/**2 * An object representing a "promise" for a future value3 *4 * @param {function(Object)} onSuccess a function to handle successful5 * resolution of this promise6 * @param {function(Error)} onFail a function to handle failed7 * resolution of this promise8 * @constructor9 */10function Promise(onSuccess, onFail) {11 this.promise = this12 this._isPromise = true13 this._successFn = onSuccess14 this._failFn = onFail15 this._hasContext = false16 this._nextContext = undefined17 this._currentContext = undefined18}19/**20 * Specify that the current promise should have a specified context21 * @param {Object} context context22 */23Promise.prototype._useContext = function (context) {24 this._nextContext = this._currentContext = context25 this._hasContext = true26 return this27}28Promise.prototype.clearContext = function () {29 this._hasContext = false30 this._nextContext = undefined31 return this32}33/**34 * Set the context for all promise handlers to follow35 * @param {context} context An arbitrary context36 */37Promise.prototype.setContext = function (context) {38 this._nextContext = context39 this._hasContext = true40 return this41}42/**43 * Get the context for a promise44 * @return {Object} the context set by setContext45 */46Promise.prototype.getContext = function () {47 return this._nextContext48}49/**50 * Resolve this promise with a specified value51 *52 * @param {Object} data53 */54Promise.prototype.resolve = function (data) {55 if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")56 var i57 if (data && data._isPromise) {58 this._child = data59 if (this._promises) {60 for (var i = 0; i < this._promises.length; i += 1) {61 data._chainPromise(this._promises[i])62 }63 delete this._promises64 }65 if (this._onComplete) {66 for (var i = 0; i < this._onComplete.length; i+= 1) {67 data.fin(this._onComplete[i])68 }69 delete this._onComplete70 }71 return72 }73 this._hasData = true74 this._data = data75 if (this._onComplete) {76 for (i = 0; i < this._onComplete.length; i++) {77 this._onComplete[i]()78 }79 }80 if (this._promises) {81 for (i = 0; i < this._promises.length; i += 1) {82 this._promises[i]._withInput(data)83 }84 delete this._promises85 }86}87/**88 * Reject this promise with an error89 *90 * @param {Error} e91 */92Promise.prototype.reject = function (e) {93 if (this._error || this._hasData) throw new Error("Unable to resolve or reject the same promise twice")94 var i95 this._error = e96 if (this._ended) {97 process.nextTick(function onPromiseThrow() {98 throw e99 })100 }101 if (this._onComplete) {102 for (i = 0; i < this._onComplete.length; i++) {103 this._onComplete[i]()104 }105 }106 if (this._promises) {107 for (i = 0; i < this._promises.length; i += 1) {108 this._promises[i]._withError(e)109 }110 delete this._promises111 }112}113/**114 * Provide a callback to be called whenever this promise successfully115 * resolves. Allows for an optional second callback to handle the failure116 * case.117 *118 * @param {function(Object)} onSuccess119 * @param {?function(Error)} onFail120 * @return {Promise} returns a new promise with the output of the onSuccess or121 * onFail handler122 */123Promise.prototype.then = function (onSuccess, onFail) {124 var promise = new Promise(onSuccess, onFail)125 if (this._nextContext) promise._useContext(this._nextContext)126 if (this._child) this._child._chainPromise(promise)127 else this._chainPromise(promise)128 return promise129}130/**131 * Provide a callback to be called whenever this promise is rejected132 *133 * @param {function(Error)} onFail134 * @return {Promise} returns a new promise with the output of the onFail handler135 */136Promise.prototype.fail = function (onFail) {137 return this.then(null, onFail)138}139/**140 * Provide a callback to be called whenever this promise is either resolved141 * or rejected.142 *143 * @param {function()} onComplete144 * @return {Promise} returns the current promise145 */146Promise.prototype.fin = function (onComplete) {147 if (this._hasData || this._error) {148 onComplete()149 return this150 }151 if (this._child) {152 this._child.fin(onComplete)153 } else {154 if (!this._onComplete) this._onComplete = [onComplete]155 else this._onComplete.push(onComplete)156 }157 return this158}159/**160 * Mark this promise as "ended". If the promise is rejected, this will throw an161 * error in whatever scope it happens to be in162 *163 * @return {Promise} returns the current promise164 */165Promise.prototype.end = function () {166 if (this._error) {167 throw this._error168 }169 this._ended = true170 return this171}172/**173 * Attempt to resolve this promise with the specified input174 *175 * @param {Object} data the input176 */177Promise.prototype._withInput = function (data) {178 if (this._successFn) {179 try {180 this.resolve(this._successFn(data, this._currentContext))181 } catch (e) {182 this.reject(e)183 }184 } else this.resolve(data)185 // context is no longer needed186 delete this._currentContext187}188/**189 * Attempt to reject this promise with the specified error190 *191 * @param {Error} e192 */193Promise.prototype._withError = function (e) {194 if (this._failFn) {195 try {196 this.resolve(this._failFn(e, this._currentContext))197 } catch (e) {198 this.reject(e)199 }200 } else this.reject(e)201 // context is no longer needed202 delete this._currentContext203}204/**205 * Chain a promise to the current promise206 *207 * @param {Promise} the promise to chain208 */209Promise.prototype._chainPromise = function (promise) {210 var i211 if (this._hasContext) promise._useContext(this._nextContext)212 if (this._child) {213 this._child._chainPromise(promise)214 } else if (this._hasData) {215 promise._withInput(this._data)216 } else if (this._error) {217 promise._withError(this._error)218 } else if (!this._promises) {219 this._promises = [promise]220 } else {221 this._promises.push(promise)222 }223}224/**225 * Utility function used for creating a node-style resolver226 * for deferreds227 *228 * @param {Promise} deferred a promise that looks like a deferred229 * @param {Error} err an optional error230 * @param {Object} data optional data231 */232function resolver(deferred, err, data) {233 if (err) deferred.reject(err)234 else deferred.resolve(data)235}236/**237 * Creates a node-style resolver for a deferred by wrapping238 * resolver()239 *240 * @return {function(Error, Object)} node-style callback241 */242Promise.prototype.makeNodeResolver = function () {243 return resolver.bind(null, this)244}245/**246 * Static function which creates and resolves a promise immediately247 *248 * @param {Object} data data to resolve the promise with249 * @return {Promise}250 */251function resolve(data) {252 var promise = new Promise()253 promise.resolve(data)254 return promise255}256/**257 * Static function which creates and rejects a promise immediately258 *259 * @param {Error} e error to reject the promise with260 * @return {Promise}261 */262function reject(e) {263 var promise = new Promise()264 promise.reject(e)265 return promise266}267/**268 * Replace an element in an array with a new value. Used by .all() to269 * call from .then()270 *271 * @param {Array.<Object>} arr272 * @param {number} idx273 * @param {Object} val274 * @return {Object} the val that's being injected into the array275 */276function replaceEl(arr, idx, val) {277 arr[idx] = val278 return val279}280/**281 * Takes in an array of promises or literals and returns a promise which returns282 * an array of values when all have resolved. If any fail, the promise fails.283 *284 * @param {Array.<Promise|Object>} promises285 * @return {Promise.<Array.<Object>>}286 */287function all(promises) {288 if (arguments.length != 1 || !Array.isArray(promises)) {289 promises = Array.prototype.slice.call(arguments, 0)290 }291 if (!promises.length) return resolve([])292 var outputs = []293 var counter = 0294 var finished = false295 var promise = new Promise()296 var counter = promises.length297 for (var i = 0; i < promises.length; i += 1) {298 if (!promises[i] || !promises[i]._isPromise) {299 outputs[i] = promises[i]300 counter -= 1301 } else {302 promises[i].then(replaceEl.bind(null, outputs, i))303 .then(function decrementAllCounter() {304 counter--305 if (!finished && counter === 0) {306 finished = true307 promise.resolve(outputs)308 }309 }, function onAllError(e) {310 if (!finished) {311 finished = true312 promise.reject(e)313 }314 })315 }316 }317 if (counter === 0 && !finished) {318 finished = true319 promise.resolve(outputs)320 }321 return promise322}323/**324 * Create a new Promise which looks like a deferred325 *326 * @return {Promise}327 */328function defer() {329 return new Promise()330}331/**332 * Return a promise which will wait a specified number of ms to resolve333 *334 * @param {number} delayMs335 * @param {Object} returnVal336 * @return {Promise.<Object>} returns returnVal337 */338function delay(delayMs, returnVal) {339 var defer = new Promise()340 setTimeout(function onDelay() {341 defer.resolve(returnVal)342 }, delayMs)343 return defer344}345/**346 * Return a promise which will evaluate the function fn with the provided args347 *348 * @param {function} fn349 * @param {Object} var_args a variable number of arguments350 * @return {Promise}351 */352function fcall(fn, var_args) {353 var defer = new Promise()354 defer.resolve(fn.apply(null, Array.prototype.slice.call(arguments, 1)))355 return defer356}357/**358 * Binds a function to a scope with an optional number of curried arguments. Attaches359 * a node style callback as the last argument and returns a promise360 *361 * @param {function} fn362 * @param {Object} scope363 * @param {Object} var_args a variable number of arguments364 * @return {Promise}365 */366function bindPromise(fn, scope, var_args) {367 var rootArgs = Array.prototype.slice.call(arguments, 2)368 return function onBoundPromise(var_args) {369 var defer = new Promise()370 fn.apply(scope, rootArgs.concat(Array.prototype.slice.call(arguments, 0), defer.makeNodeResolver()))371 return defer372 }373}374module.exports = {375 all: all376 , bindPromise: bindPromise377 , defer: defer378 , delay: delay379 , fcall: fcall380 , resolve: resolve381 , reject: reject...

Full Screen

Full Screen

lifecycle.js

Source:lifecycle.js Github

copy

Full Screen

1import {2 internal_safe_get as safeGet,3 internal_safe_set as safeSet,4 commitAttachRef,5 Current,6 invokeEffects7} from '@tarojs/taro'8import PropTypes from 'prop-types'9import { componentTrigger } from './create-component'10import { shakeFnFromObject, isEmptyObject, diffObjToPath, isFunction, isUndefined, isArray } from './util'11import { enqueueRender } from './render-queue'12const isDEV = typeof process === 'undefined' ||13 !process.env ||14 process.env.NODE_ENV !== 'production'15function hasNewLifecycle (component) {16 const { constructor: { getDerivedStateFromProps }, getSnapshotBeforeUpdate } = component17 return isFunction(getDerivedStateFromProps) || isFunction(getSnapshotBeforeUpdate)18}19function callGetDerivedStateFromProps (component, props, state) {20 const { getDerivedStateFromProps } = component.constructor21 let newState22 if (isFunction(getDerivedStateFromProps)) {23 const partialState = getDerivedStateFromProps(props, state)24 if (!isUndefined(partialState)) {25 newState = Object.assign({}, state, partialState)26 } else {27 console.warn('getDerivedStateFromProps 没有返回任何内容,这个生命周期必须返回 null 或一个新对象。')28 }29 }30 return newState31}32function callGetSnapshotBeforeUpdate (component, props, state) {33 const { getSnapshotBeforeUpdate } = component34 let snapshot35 if (isFunction(getSnapshotBeforeUpdate)) {36 snapshot = getSnapshotBeforeUpdate.call(component, props, state)37 }38 return snapshot39}40export function updateComponent (component) {41 const { props, __propTypes } = component42 // 由 forceUpdate 或者组件自身 setState 发起的 update 可能是没有新的nextProps的43 const nextProps = component.nextProps || props44 const prevProps = props45 if (isDEV && __propTypes) {46 let componentName = component.constructor.name47 if (isUndefined(componentName)) {48 const names = component.constructor.toString().match(/^function\s*([^\s(]+)/)49 componentName = isArray(names) ? names[0] : 'Component'50 }51 PropTypes.checkPropTypes(__propTypes, props, 'prop', componentName)52 }53 if (component.__mounted && component._unsafeCallUpdate === true && !hasNewLifecycle(component) && component.componentWillReceiveProps) {54 component._disable = true55 component.componentWillReceiveProps(nextProps)56 component._disable = false57 }58 let state = component.getState()59 const prevState = component.prevState || state60 const stateFromProps = callGetDerivedStateFromProps(component, nextProps, state)61 if (!isUndefined(stateFromProps)) {62 state = stateFromProps63 }64 let skip = false65 if (component.__mounted) {66 if (typeof component.shouldComponentUpdate === 'function' &&67 !component._isForceUpdate &&68 component.shouldComponentUpdate(nextProps, state) === false) {69 skip = true70 } else if (!hasNewLifecycle(component) && isFunction(component.componentWillUpdate)) {71 component.componentWillUpdate(nextProps, state)72 }73 }74 component.props = nextProps75 component.state = state76 component._dirty = false77 component._isForceUpdate = false78 if (!skip) {79 doUpdate(component, prevProps, prevState)80 }81 delete component.nextProps82 component.prevState = component.state83}84export function mountComponent (component) {85 const { props } = component86 // 在willMount前执行构造函数的副本87 if (!component.__componentWillMountTriggered) {88 component._constructor && component._constructor(props)89 }90 const newState = callGetDerivedStateFromProps(component, props, component.state)91 if (!isUndefined(newState)) {92 component.state = newState93 }94 component._dirty = false95 component._disable = false96 component._isForceUpdate = false97 if (!component.__componentWillMountTriggered) {98 component.__componentWillMountTriggered = true99 if (!hasNewLifecycle(component)) {100 componentTrigger(component, 'componentWillMount')101 }102 }103 doUpdate(component, props, component.state)104 component.prevState = component.state105}106function injectContextType (component) {107 const ctxType = component.constructor.contextType108 if (ctxType) {109 const context = ctxType.context110 const emitter = context.emitter111 if (emitter === null) {112 component.context = context._defaultValue113 return114 }115 if (!component._hasContext) {116 component._hasContext = true117 emitter.on(_ => enqueueRender(component))118 }119 component.context = emitter.value120 }121}122function doUpdate (component, prevProps, prevState) {123 const { state, props = {} } = component124 let data = state || {}125 if (component._createData) {126 if (component.__isReady) {127 injectContextType(component)128 Current.current = component129 Current.index = 0130 invokeEffects(component, true)131 }132 data = component._createData(state, props) || data133 if (component.__isReady) {134 Current.current = null135 }136 }137 data = Object.assign({}, props, data)138 if (component.$usedState && component.$usedState.length) {139 const _data = {}140 component.$usedState.forEach(key => {141 let val = safeGet(data, key)142 if (typeof val === 'undefined') {143 return144 }145 if (typeof val === 'object') {146 if (isEmptyObject(val)) return safeSet(_data, key, {})147 // 避免筛选完 Fn 后产生了空对象还去渲染148 if (!isEmptyObject(val)) safeSet(_data, key, val)149 } else {150 safeSet(_data, key, val)151 }152 })153 data = _data154 }155 data['$taroCompReady'] = true156 const dataDiff = diffObjToPath(data, component.$scope.data)157 const __mounted = component.__mounted158 let snapshot159 if (__mounted) {160 snapshot = callGetSnapshotBeforeUpdate(component, prevProps, prevState)161 }162 // 每次 setData 都独立生成一个 callback 数组163 let cbs = []164 if (component._pendingCallbacks && component._pendingCallbacks.length) {165 cbs = component._pendingCallbacks166 component._pendingCallbacks = []167 }168 const cb = function () {169 if (__mounted) {170 invokeEffects(component)171 if (component['$$refs'] && component['$$refs'].length > 0) {172 component['$$refs'].forEach(ref => {173 // 只有 component 类型能做判断。因为 querySelector 每次调用都一定返回 nodeRefs,无法得知 dom 类型的挂载状态。174 if (ref.type !== 'component') return175 let target = component.$scope.selectComponent(`#${ref.id}`)176 target = target ? (target.$component || target) : null177 const prevRef = ref.target178 if (target !== prevRef) {179 commitAttachRef(ref, target, component, component.refs)180 ref.target = target181 }182 })183 }184 if (component['$$hasLoopRef']) {185 Current.current = component186 component._disableEffect = true187 component._createData(component.state, component.props, true)188 component._disableEffect = false189 Current.current = null190 }191 if (isFunction(component.componentDidUpdate)) {192 component.componentDidUpdate(prevProps, prevState, snapshot)193 }194 }195 if (cbs.length) {196 let i = cbs.length197 while (--i >= 0) {198 typeof cbs[i] === 'function' && cbs[i].call(component)199 }200 }201 }202 if (Object.keys(dataDiff).length === 0) {203 cb()204 } else {205 component.$scope.setData(dataDiff, cb)206 }...

Full Screen

Full Screen

writer.js

Source:writer.js Github

copy

Full Screen

...96 * @param {string} context Context to check.97 * 98 * @return {bool} True on match, else false.99 */100 _hasContext(context)101 {102 for (let item of this.#contexts) {103 if (context.startsWith(item)) {104 return true;105 }106 }107 return false;108 }109 /**110 * See if we can output a message.111 * 112 * @param {int} level Level of this message.113 * @param {string|null} context Context.114 * 115 * @return {bool}116 */117 canOutput(level, context)118 {119 if (level < this.#level) {120 return false;121 }122 if (null !== context && this.#contexts.length > 0) {123 if (!this._hasContext(context)) {124 return false;125 }126 } if (null !== context && 0 === this.#contexts.length) {127 return false;128 }129 return true;130 }131 /**132 * Write the message.133 * 134 * @param {string} msg Message to write.135 * @param {int} level Level of this message.136 * @param {string|null} context Context.137 * @param {any} extra Extra data....

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8var Nightmare = require('nightmare');9var nightmare = Nightmare({ show: true });10 .screenshot('example.png')11 .end()12 .then(function (result) {13 console.log(result);14 })15 .catch(function (error) {16 console.error('Search failed:', error);17 });18var casper = require('casper').create();19 this.capture('example.png');20});21casper.run();22const Browser = require('zombie');23browser = new Browser();24 browser.saveScreenshot('example.png');25});26const jsdom = require("jsdom");27const { JSDOM } = jsdom;28const dom = new JSDOM(`...`);29const document = dom.window.document;30const cheerio = require('cheerio');31const $ = cheerio.load('...');32const request = require('request');33});34const axios = require('axios');35 .then(response => {36 console.log(response.data);37 })38 .catch(error => {39 console.log(error);40 });41const superagent = require('superagent');42 .end((

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitForSelector('input[name="q"]');6 await page.click('input[name="q"]');7 await page.type('input[name="q"]', 'puppeteer');8 await page.keyboard.press('Enter');9 await page.waitForNavigation();10 await page.waitForSelector('div.g');11 const hasContext = await page._hasContext();12 if (hasContext) {13 console.log('Context present');14 } else {15 console.log('Context not present');16 }17 await browser.close();18})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.waitForSelector('input[name="q"]');6 await page.type('input[name="q"]', 'Puppeteer');7 await page.waitForSelector('input[name="btnK"]');8 await page.click('input[name="btnK"]');9 await page.waitForNavigation();10 await page.waitForSelector('div#resultStats');11 const title = await page.title();12 const url = await page.url();13 const html = await page.content();14 const text = await page.evaluate(() => document.body.textContent);15 const hasContext = await page._hasContext();16 console.log('hasContext', hasContext);17 await browser.close();18})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const hasContextMenu = await page._client.send('Page.hasTouchScreen');6 console.log(hasContextMenu);7 await browser.close();8})();9{ hasTouchScreen: false }

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page.screenshot({path: 'example.png'});5 await browser.close();6})();7(async () => {8 const browser = await puppeteer.launch();9 const page = await browser.newPage();10 await page.screenshot({path: 'example.png'});11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1async function test(){2 const browser = await puppeteer.launch({headless: false});3 const page = await browser.newPage();4 console.log(await page._client.send('Page.getResourceTree'));5 await browser.close();6}7test();8{9 frameTree: {10 frame: {11 },12 {13 }14 }15}16Your name to display (optional):17Your name to display (optional):18async function getResourceTree(page) {19 return await page._client.send('Page.getResourceTree');20}21Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2async function run() {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 const isElementPresent = await page._hasContext('input[name="q"]');6 console.log(isElementPresent);7 await browser.close();8}9run();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful