Best JavaScript code snippet using puppeteer
mediaControlsiOS.js
Source:mediaControlsiOS.js
...38 var startPlaybackGlyph = document.createElement('div');39 startPlaybackGlyph.setAttribute('pseudo', '-webkit-media-controls-start-playback-glyph');40 startPlaybackGlyph.classList.add('webkit-media-controls-start-playback-glyph');41 startPlaybackButton.appendChild(startPlaybackGlyph);42 this.listenFor(this.base, 'gesturestart', this.handleBaseGestureStart);43 this.listenFor(this.base, 'gesturechange', this.handleBaseGestureChange);44 this.listenFor(this.base, 'gestureend', this.handleBaseGestureEnd);45 this.listenFor(this.base, 'touchstart', this.handleWrapperTouchStart);46 this.stopListeningFor(this.base, 'mousemove', this.handleWrapperMouseMove);47 this.stopListeningFor(this.base, 'mouseout', this.handleWrapperMouseOut);48 this.listenFor(document, 'visibilitychange', this.handleVisibilityChange);49 },50 shouldHaveStartPlaybackButton: function() {51 var allowsInline = this.host.allowsInlineMediaPlayback;52 if (this.isPlaying || (this.hasPlayed && allowsInline))53 return false;54 if (this.isAudio() && allowsInline)55 return false;56 if (this.doingSetup)57 return true;58 if (this.isFullScreen())59 return false;60 if (!this.video.currentSrc && this.video.error)61 return false;62 if (!this.video.controls && allowsInline)63 return false;64 if (this.video.currentSrc && this.video.error)65 return true;66 return true;67 },68 shouldHaveControls: function() {69 if (this.shouldHaveStartPlaybackButton())70 return false;71 return Controller.prototype.shouldHaveControls.call(this);72 },73 shouldHaveAnyUI: function() {74 return this.shouldHaveStartPlaybackButton() || Controller.prototype.shouldHaveAnyUI.call(this) || this.currentPlaybackTargetIsWireless();75 },76 createControls: function() {77 Controller.prototype.createControls.call(this);78 var panelContainer = this.controls.panelContainer = document.createElement('div');79 panelContainer.setAttribute('pseudo', '-webkit-media-controls-panel-container');80 var wirelessTargetPicker = this.controls.wirelessTargetPicker;81 this.listenFor(wirelessTargetPicker, 'touchstart', this.handleWirelessPickerButtonTouchStart);82 this.listenFor(wirelessTargetPicker, 'touchend', this.handleWirelessPickerButtonTouchEnd);83 this.listenFor(wirelessTargetPicker, 'touchcancel', this.handleWirelessPickerButtonTouchCancel);84 this.listenFor(this.controls.startPlaybackButton, 'touchstart', this.handleStartPlaybackButtonTouchStart);85 this.listenFor(this.controls.startPlaybackButton, 'touchend', this.handleStartPlaybackButtonTouchEnd);86 this.listenFor(this.controls.startPlaybackButton, 'touchcancel', this.handleStartPlaybackButtonTouchCancel);87 this.listenFor(this.controls.panel, 'touchstart', this.handlePanelTouchStart);88 this.listenFor(this.controls.panel, 'touchend', this.handlePanelTouchEnd);89 this.listenFor(this.controls.panel, 'touchcancel', this.handlePanelTouchCancel);90 this.listenFor(this.controls.playButton, 'touchstart', this.handlePlayButtonTouchStart);91 this.listenFor(this.controls.playButton, 'touchend', this.handlePlayButtonTouchEnd);92 this.listenFor(this.controls.playButton, 'touchcancel', this.handlePlayButtonTouchCancel);93 this.listenFor(this.controls.fullscreenButton, 'touchstart', this.handleFullscreenTouchStart);94 this.listenFor(this.controls.fullscreenButton, 'touchend', this.handleFullscreenTouchEnd);95 this.listenFor(this.controls.fullscreenButton, 'touchcancel', this.handleFullscreenTouchCancel);96 this.listenFor(this.controls.pictureInPictureButton, 'touchstart', this.handlePictureInPictureTouchStart);97 this.listenFor(this.controls.pictureInPictureButton, 'touchend', this.handlePictureInPictureTouchEnd);98 this.listenFor(this.controls.pictureInPictureButton, 'touchcancel', this.handlePictureInPictureTouchCancel);99 this.listenFor(this.controls.timeline, 'touchstart', this.handleTimelineTouchStart);100 this.stopListeningFor(this.controls.playButton, 'click', this.handlePlayButtonClicked);101 this.controls.timeline.style.backgroundImage = '-webkit-canvas(' + this.timelineContextName + ')';102 },103 setControlsType: function(type) {104 if (type === this.controlsType)105 return;106 Controller.prototype.setControlsType.call(this, type);107 if (type === ControllerIOS.StartPlaybackControls)108 this.addStartPlaybackControls();109 else110 this.removeStartPlaybackControls();111 },112 addStartPlaybackControls: function() {113 this.base.appendChild(this.controls.startPlaybackButton);114 this.showShowControlsButton(false);115 },116 removeStartPlaybackControls: function() {117 if (this.controls.startPlaybackButton.parentNode)118 this.controls.startPlaybackButton.parentNode.removeChild(this.controls.startPlaybackButton);119 },120 reconnectControls: function()121 {122 Controller.prototype.reconnectControls.call(this);123 if (this.controlsType === ControllerIOS.StartPlaybackControls)124 this.addStartPlaybackControls();125 },126 configureInlineControls: function() {127 this.controls.inlinePlaybackPlaceholder.appendChild(this.controls.inlinePlaybackPlaceholderText);128 this.controls.inlinePlaybackPlaceholderText.appendChild(this.controls.inlinePlaybackPlaceholderTextTop);129 this.controls.inlinePlaybackPlaceholderText.appendChild(this.controls.inlinePlaybackPlaceholderTextBottom);130 this.controls.panel.appendChild(this.controls.playButton);131 this.controls.panel.appendChild(this.controls.statusDisplay);132 this.controls.panel.appendChild(this.controls.timelineBox);133 this.controls.panel.appendChild(this.controls.wirelessTargetPicker);134 if (!this.isLive) {135 this.controls.timelineBox.appendChild(this.controls.currentTime);136 this.controls.timelineBox.appendChild(this.controls.timeline);137 this.controls.timelineBox.appendChild(this.controls.remainingTime);138 }139 if (this.isAudio()) {140 // Hide the scrubber on audio until the user starts playing.141 this.controls.timelineBox.classList.add(this.ClassNames.hidden);142 } else {143 this.updatePictureInPictureButton();144 this.controls.panel.appendChild(this.controls.fullscreenButton);145 }146 },147 configureFullScreenControls: function() {148 // Explicitly do nothing to override base-class behavior.149 },150 controlsAreHidden: function()151 {152 // Controls are only ever actually hidden when they are removed from the tree153 return !this.controls.panelContainer.parentElement;154 },155 addControls: function() {156 this.base.appendChild(this.controls.inlinePlaybackPlaceholder);157 this.base.appendChild(this.controls.panelContainer);158 this.controls.panelContainer.appendChild(this.controls.panelBackground);159 this.controls.panelContainer.appendChild(this.controls.panel);160 this.setNeedsTimelineMetricsUpdate();161 },162 updateControls: function() {163 if (this.shouldHaveStartPlaybackButton())164 this.setControlsType(ControllerIOS.StartPlaybackControls);165 else if (this.presentationMode() === "fullscreen")166 this.setControlsType(Controller.FullScreenControls);167 else168 this.setControlsType(Controller.InlineControls);169 this.updateLayoutForDisplayedWidth();170 this.setNeedsTimelineMetricsUpdate();171 },172 drawTimelineBackground: function() {173 var width = this.timelineWidth * window.devicePixelRatio;174 var height = this.timelineHeight * window.devicePixelRatio;175 if (!width || !height)176 return;177 var played = this.video.currentTime / this.video.duration;178 var buffered = 0;179 var bufferedRanges = this.video.buffered;180 if (bufferedRanges && bufferedRanges.length)181 buffered = Math.max(bufferedRanges.end(bufferedRanges.length - 1), buffered);182 buffered /= this.video.duration;183 buffered = Math.max(buffered, played);184 var ctx = document.getCSSCanvasContext('2d', this.timelineContextName, width, height);185 ctx.clearRect(0, 0, width, height);186 var midY = height / 2;187 // 1. Draw the buffered part and played parts, using188 // solid rectangles that are clipped to the outside of189 // the lozenge.190 ctx.save();191 ctx.beginPath();192 this.addRoundedRect(ctx, 1, midY - 3, width - 2, 6, 3);193 ctx.closePath();194 ctx.clip();195 ctx.fillStyle = "white";196 ctx.fillRect(0, 0, Math.round(width * played) + 2, height);197 ctx.fillStyle = "rgba(0, 0, 0, 0.55)";198 ctx.fillRect(Math.round(width * played) + 2, 0, Math.round(width * (buffered - played)) + 2, height);199 ctx.restore();200 // 2. Draw the outline with a clip path that subtracts the201 // middle of a lozenge. This produces a better result than202 // stroking.203 ctx.save();204 ctx.beginPath();205 this.addRoundedRect(ctx, 1, midY - 3, width - 2, 6, 3);206 this.addRoundedRect(ctx, 2, midY - 2, width - 4, 4, 2);207 ctx.closePath();208 ctx.clip("evenodd");209 ctx.fillStyle = "rgba(0, 0, 0, 0.55)";210 ctx.fillRect(Math.round(width * buffered) + 2, 0, width, height);211 ctx.restore();212 },213 formatTime: function(time) {214 if (isNaN(time))215 time = 0;216 var absTime = Math.abs(time);217 var intSeconds = Math.floor(absTime % 60).toFixed(0);218 var intMinutes = Math.floor((absTime / 60) % 60).toFixed(0);219 var intHours = Math.floor(absTime / (60 * 60)).toFixed(0);220 var sign = time < 0 ? '-' : String();221 if (intHours > 0)222 return sign + intHours + ':' + String('0' + intMinutes).slice(-2) + ":" + String('0' + intSeconds).slice(-2);223 return sign + String('0' + intMinutes).slice(intMinutes >= 10 ? -2 : -1) + ":" + String('0' + intSeconds).slice(-2);224 },225 handlePlayButtonTouchStart: function() {226 this.controls.playButton.classList.add('active');227 },228 handlePlayButtonTouchEnd: function(event) {229 this.controls.playButton.classList.remove('active');230 if (this.canPlay()) {231 this.video.play();232 this.showControls();233 } else234 this.video.pause();235 return true;236 },237 handlePlayButtonTouchCancel: function(event) {238 this.controls.playButton.classList.remove('active');239 return true;240 },241 handleBaseGestureStart: function(event) {242 this.gestureStartTime = new Date();243 // If this gesture started with two fingers inside the video, then244 // don't treat it as a potential zoom, unless we're still waiting245 // to play.246 if (this.mostRecentNumberOfTargettedTouches == 2 && this.controlsType != ControllerIOS.StartPlaybackControls)247 event.preventDefault();248 },249 handleBaseGestureChange: function(event) {250 if (!this.video.controls || this.isAudio() || this.isFullScreen() || this.gestureStartTime === undefined || this.controlsType == ControllerIOS.StartPlaybackControls)251 return;252 var scaleDetectionThreshold = 0.2;253 if (event.scale > 1 + scaleDetectionThreshold || event.scale < 1 - scaleDetectionThreshold)254 delete this.lastDoubleTouchTime;255 if (this.mostRecentNumberOfTargettedTouches == 2 && event.scale >= 1.0)256 event.preventDefault();257 var currentGestureTime = new Date();258 var duration = (currentGestureTime - this.gestureStartTime) / 1000;259 if (!duration)260 return;261 var velocity = Math.abs(event.scale - 1) / duration;262 var pinchOutVelocityThreshold = 2;263 var pinchOutGestureScaleThreshold = 1.25;264 if (velocity < pinchOutVelocityThreshold || event.scale < pinchOutGestureScaleThreshold)265 return;266 delete this.gestureStartTime;267 this.video.webkitEnterFullscreen();268 },269 handleBaseGestureEnd: function(event) {270 delete this.gestureStartTime;271 },272 handleWrapperTouchStart: function(event) {273 if (event.target != this.base && event.target != this.controls.inlinePlaybackPlaceholder)274 return;275 this.mostRecentNumberOfTargettedTouches = event.targetTouches.length;276 if (this.controlsAreHidden() || !this.controls.panel.classList.contains(this.ClassNames.show)) {277 this.showControls();278 this.resetHideControlsTimer();279 } else if (!this.canPlay())280 this.hideControls();281 },282 handlePanelTouchStart: function(event) {283 this.video.style.webkitUserSelect = 'none';284 },285 handlePanelTouchEnd: function(event) {286 this.video.style.removeProperty('-webkit-user-select');287 },288 handlePanelTouchCancel: function(event) {289 this.video.style.removeProperty('-webkit-user-select');290 },291 handleVisibilityChange: function(event) {292 this.updateShouldListenForPlaybackTargetAvailabilityEvent();293 },294 handlePanelTransitionEnd: function(event)295 {296 var opacity = window.getComputedStyle(this.controls.panel).opacity;297 if (!parseInt(opacity) && !this.controlsAlwaysVisible()) {298 this.base.removeChild(this.controls.inlinePlaybackPlaceholder);299 this.base.removeChild(this.controls.panelContainer);300 }301 },302 handleFullscreenButtonClicked: function(event) {303 if ('webkitSetPresentationMode' in this.video) {304 if (this.presentationMode() === 'fullscreen')305 this.video.webkitSetPresentationMode('inline');306 else307 this.video.webkitSetPresentationMode('fullscreen');308 return;309 }310 if (this.isFullScreen())311 this.video.webkitExitFullscreen();312 else313 this.video.webkitEnterFullscreen();314 },315 handleFullscreenTouchStart: function() {316 this.controls.fullscreenButton.classList.add('active');317 },318 handleFullscreenTouchEnd: function(event) {319 this.controls.fullscreenButton.classList.remove('active');320 this.handleFullscreenButtonClicked();321 return true;322 },323 handleFullscreenTouchCancel: function(event) {324 this.controls.fullscreenButton.classList.remove('active');325 return true;326 },327 handlePictureInPictureTouchStart: function() {328 this.controls.pictureInPictureButton.classList.add('active');329 },330 handlePictureInPictureTouchEnd: function(event) {331 this.controls.pictureInPictureButton.classList.remove('active');332 this.handlePictureInPictureButtonClicked();333 return true;334 },335 handlePictureInPictureTouchCancel: function(event) {336 this.controls.pictureInPictureButton.classList.remove('active');337 return true;338 },339 handleStartPlaybackButtonTouchStart: function(event) {340 this.controls.startPlaybackButton.classList.add('active');341 this.controls.startPlaybackButton.querySelector('.webkit-media-controls-start-playback-glyph').classList.add('active');342 },343 handleStartPlaybackButtonTouchEnd: function(event) {344 this.controls.startPlaybackButton.classList.remove('active');345 this.controls.startPlaybackButton.querySelector('.webkit-media-controls-start-playback-glyph').classList.remove('active');346 if (this.video.error)347 return true;348 this.video.play();349 this.canToggleShowControlsButton = true;350 this.updateControls();351 return true;352 },353 handleStartPlaybackButtonTouchCancel: function(event) {354 this.controls.startPlaybackButton.classList.remove('active');355 return true;356 },357 handleTimelineTouchStart: function(event) {358 this.scrubbing = true;359 this.listenFor(this.controls.timeline, 'touchend', this.handleTimelineTouchEnd);360 this.listenFor(this.controls.timeline, 'touchcancel', this.handleTimelineTouchEnd);361 },362 handleTimelineTouchEnd: function(event) {363 this.stopListeningFor(this.controls.timeline, 'touchend', this.handleTimelineTouchEnd);364 this.stopListeningFor(this.controls.timeline, 'touchcancel', this.handleTimelineTouchEnd);365 this.scrubbing = false;366 },367 handleWirelessPickerButtonTouchStart: function() {368 if (!this.video.error)369 this.controls.wirelessTargetPicker.classList.add('active');370 },371 handleWirelessPickerButtonTouchEnd: function(event) {372 this.controls.wirelessTargetPicker.classList.remove('active');373 return this.handleWirelessPickerButtonClicked();374 },...
keyboard-test.js
Source:keyboard-test.js
...18moduleFor('service:keyboard', 'Unit | Service | keyboard');19test('it listens for key down presses', function(assert) {20 assert.expect(3);21 const service = this.subject();22 service.listenFor('f', this, function() { assert.ok(true); });23 service.listenFor('o', this, function() { assert.ok(true); });24 // Types 'foo'25 $(document.body).trigger($.Event('keydown', { key: 'f' }));26 $(document.body).trigger($.Event('keydown', { key: 'o' }));27 $(document.body).trigger($.Event('keydown', { key: 'o' }));28});29test('listener can be a function name', function(assert) {30 assert.expect(1);31 const service = this.subject();32 const context = {33 foo() { assert.ok(true); }34 };35 service.listenFor('x', context, 'foo');36 $(document.body).trigger($.Event('keydown', { key: 'x' }));37});38test('the first argument to the callback is the event object', function(assert) {39 const service = this.subject();40 const event = { key: 'x' };41 service.listenFor('x', this, function(e) { assert.equal(e.key, event.key); });42 $(document.body).trigger($.Event('keydown', event));43});44test('it can handle an array of static arguments as option', function(assert) {45 assert.expect(1);46 const service = this.subject();47 service.listenFor('x', this, function(e, n) { assert.equal(n, 42); }, {48 arguments: [42]49 });50 $(document.body).trigger($.Event('keydown', { key: 'x' }));51});52test('it throws when no key is given', function(assert) {53 assert.expect(1);54 const service = this.subject();55 assert.throws(() => {56 service.listenFor();57 });58});59test('it can handle ctrl modifier', function(assert) {60 assert.expect(1);61 const service = this.subject();62 service.listenFor('x', this, function() { assert.ok(false, 'should not run with ctrl pressed'); });63 service.listenFor('x', this, function() { assert.ok(true); }, {64 requireCtrl: true65 });66 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));67});68test('it can handle alt key modifier', function(assert) {69 assert.expect(1);70 const service = this.subject();71 service.listenFor('x', this, function() { assert.ok(false, 'should not run with alt pressed'); });72 service.listenFor('x', this, function() { assert.ok(true); }, {73 requireAlt: true74 });75 $(document.body).trigger($.Event('keydown', { key: 'x', altKey: true }));76});77test('it can handle shift key modifier', function(assert) {78 assert.expect(1);79 const service = this.subject();80 service.listenFor('x', this, function() { assert.ok(false, 'should not run with shift pressed'); });81 service.listenFor('x', this, function() { assert.ok(true); }, {82 requireShift: true83 });84 $(document.body).trigger($.Event('keydown', { key: 'x', shiftKey: true }));85});86test('it can handle meta key modifier', function(assert) {87 assert.expect(1);88 const service = this.subject();89 service.listenFor('x', this, function() { assert.ok(false, 'should not run with meta pressed'); });90 service.listenFor('x', this, function() { assert.ok(true); }, {91 requireMeta: true92 });93 $(document.body).trigger($.Event('keydown', { key: 'x', metaKey: true }));94});95// Haven't found a reliable way of spoofing user agent on phantom js.96if (!/PhantomJS/i.test(window.navigator.userAgent)) {97 test('it can handle meta as ctrl key modifier on Mac OS X when useCmdOnMac is enabled', function(assert) {98 setUserAgent('Mac OS X');99 const service = this.subject();100 let cmdTriggered = 0;101 let ctrlTriggered = 0;102 service.listenFor('ctrl+x', this, function() {103 ctrlTriggered += 1;104 });105 service.listenFor('ctrl+x', this, function() {106 cmdTriggered += 1;107 }, {108 useCmdOnMac: true109 });110 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));111 assert.equal(ctrlTriggered, 1, 'ctrl hit on mac - ctrl count is 1');112 assert.equal(cmdTriggered, 0, 'ctrl hit on mac - cmd count is 0');113 $(document.body).trigger($.Event('keydown', { key: 'x', metaKey: true }));114 assert.equal(ctrlTriggered, 1, 'cmd hit on mac - ctrl count is 1');115 assert.equal(cmdTriggered, 1, 'cmd hit on mac - cmd count is 1');116 setUserAgent('Windows NT');117 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));118 assert.equal(ctrlTriggered, 2, 'ctrl hit on win - ctrl count is 2');119 assert.equal(cmdTriggered, 2, 'ctrl hit on win - cmd count is 2');120 $(document.body).trigger($.Event('keydown', { key: 'x', metaKey: true }));121 assert.equal(ctrlTriggered, 2, 'cmd hit on win - ctrl count is 2');122 assert.equal(cmdTriggered, 2, 'cmd hit on win - cmd count is 2');123 resetUserAgent();124 });125}126test('it can handle a combination of key modifiers', function(assert) {127 assert.expect(1);128 const service = this.subject();129 service.listenFor('Del', this, function() { assert.ok(false, 'should not run'); });130 service.listenFor('Del', this, function() { assert.ok(false, 'should not run'); }, {131 requireAlt: true132 });133 service.listenFor('Del', this, function() { assert.ok(true); }, {134 requireCtrl: true,135 requireAlt: true136 });137 $(document.body).trigger($.Event('keydown', { key: 'Del', ctrlKey: true, altKey: true }));138});139test('it can handle a combination shorthand', function(assert) {140 assert.expect(1);141 const service = this.subject();142 service.listenFor('x', this, function() { assert.ok(false, 'should not run with ctrl pressed'); });143 service.listenFor('ctrl+x', this, function() { assert.ok(true); });144 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));145});146test('stopListeningFor removes the keyboard handler', function(assert) {147 assert.expect(3);148 const service = this.subject();149 const listener = function() { assert.ok(true); };150 service.listenFor('ctrl+x', this, listener);151 service.listenFor('ctrl+x', this, function() { assert.ok(true); });152 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));153 service.stopListeningFor('ctrl+x', this, listener);154 $(document.body).trigger($.Event('keydown', { key: 'x', ctrlKey: true }));155});156test('listenForOnce only gets called once', function(assert) {157 assert.expect(1);158 const service = this.subject();159 service.listenForOnce('x', this, function() { assert.ok(true); });160 $(document.body).trigger($.Event('keydown', { key: 'x' }));161 $(document.body).trigger($.Event('keydown', { key: 'x' }));162});163test('it falls back to event.keyCode if event.key is not set', function(assert) {164 assert.expect(1);165 const service = this.subject();166 service.listenFor('x', this, function() { assert.ok(true); });167 $(document.body).trigger($.Event('keydown', { keyCode: 88 }));168});169test('it can handle the space key', function(assert) {170 assert.expect(1);171 const service = this.subject();172 service.listenFor(' ', this, function() { assert.ok(true); });173 $(document.body).trigger($.Event('keydown', { key: ' ' }));174});175test('multiple shortcuts can be specified at once', function(assert) {176 assert.expect(2);177 const service = this.subject();178 service.listenFor(['a', 'b'], this, function() { assert.ok(true); });179 $(document.body).trigger($.Event('keydown', { key: 'a' }));180 $(document.body).trigger($.Event('keydown', { key: 'b' }));181});182test('multiple shortcuts can be specified at once - with modifiers', function(assert) {183 assert.expect(2);184 const service = this.subject();185 service.listenFor(['ctrl+a', 'shift+b'], this, function() { assert.ok(true); });186 $(document.body).trigger($.Event('keydown', { key: 'a', ctrlKey: true }));187 $(document.body).trigger($.Event('keydown', { key: 'b', ctrlKey: true }));188 $(document.body).trigger($.Event('keydown', { key: 'b', shiftKey: true }));189});190test('stopListingFor also support multiple shortcuts', function(assert) {191 assert.expect(0);192 const service = this.subject();193 const callback = function() { assert.ok(false); };194 service.listenFor(['ctrl+a', 'shift+b'], this, callback);195 service.stopListeningFor(['ctrl+a', 'shift+b'], this, callback);196 $(document.body).trigger($.Event('keydown', { key: 'a', ctrlKey: true }));197 $(document.body).trigger($.Event('keydown', { key: 'b', shiftKey: true }));198});199test('if event.target is an input ignore by default', function(assert) {200 assert.expect(0);201 const service = this.subject();202 service.listenFor('x', this, function() { assert.ok(true); });203 const input = document.createElement('input');204 const textarea = document.createElement('textarea');205 $(document.body).trigger($.Event('keydown', { key: 'x', target: input }));206 $(document.body).trigger($.Event('keydown', { key: 'x', target: textarea }));207});208test('if event.target is an input handle if option is set', function(assert) {209 assert.expect(2);210 const service = this.subject();211 service.listenFor('x', this, function() { assert.ok(true); }, {212 actOnInputElement: true213 });214 const input = document.createElement('input');215 const textarea = document.createElement('textarea');216 $(document.body).trigger($.Event('keydown', { key: 'x', target: input }));217 $(document.body).trigger($.Event('keydown', { key: 'x', target: textarea }));218});219test('options.debounce wraps callback in run.debounce with specified time', function(assert) {220 assert.expect(1);221 const done = assert.async();222 const service = this.subject();223 service.listenFor('x', this, function() { assert.ok(true); done(); }, {224 debounce: 1,225 });226 $(document.body).trigger($.Event('keydown', { key: 'x' }));227 $(document.body).trigger($.Event('keydown', { key: 'x' }));228});229test('options.throttle wraps callback in run.throttle with specified time', function(assert) {230 assert.expect(2);231 const done = assert.async();232 const service = this.subject();233 service.listenFor('x', this, function() { assert.ok(true); }, {234 throttle: 1,235 });236 $(document.body).trigger($.Event('keydown', { key: 'x' }));237 $(document.body).trigger($.Event('keydown', { key: 'x' }));238 setTimeout(() => {239 $(document.body).trigger($.Event('keydown', { key: 'x' }));240 done();241 }, 1);242});243test('options.scheduleOnce wraps callback in run.once', function(assert) {244 assert.expect(1);245 const service = this.subject();246 service.listenFor('x', this, function() { assert.ok(true); }, {247 scheduleOnce: true,248 });249 run(() => {250 $(document.body).trigger($.Event('keydown', { key: 'x' }));251 $(document.body).trigger($.Event('keydown', { key: 'x' }));252 $(document.body).trigger($.Event('keydown', { key: 'x' }));253 });254});255// regressions256test('listening for "." works', function(assert) {257 assert.expect(1);258 const service = this.subject();259 service.listenFor('.', this, function() { assert.ok(true); });260 run(() => {261 $(document.body).trigger($.Event('keydown', { key: '.' }));262 });...
index.js
Source:index.js
1import './style.css';2import { lists, todos } from './data';3import listenFor from './eventlistener'4import { domManipulation, undoModal, todoInput, listInput } from './dom';5import statistics from './statistics';6const main = (function () {7 //define event listeners8 let selectedList = undefined;9 function _getCookies() {10 const objectJSON = localStorage.getItem('listsObject');11 return JSON.parse(objectJSON); //convert json to object and return it12 };13 14 function _setCookies() {15 const listsObject = lists.getListsArray();16 const objectJSON = JSON.stringify(listsObject);17 localStorage.setItem('listsObject', objectJSON);18 };19 20 function _removeTodo(title) {21 todos.removeTodo(selectedList, title);22 statistics.removeOpen();23 statistics.addCompleted();24 _displayItems();25 _setCookies();26 undoModal.setTitle(title); 27 undoModal.show();28 };29 listenFor.undoButton(() => {30 undoModal.hide();31 todos.backToBackupList();32 _setCookies();33 _displayItems();34 });35 function _selectList(listTitle) {36 selectedList = listTitle;37 }38 39 function _removeList(e) {40 const listTitle = (e.target.parentNode).getAttribute('data-title');41 lists.deleteList(listTitle);42 const currentList = lists.getListsArray();43 if (!(currentList.length === 0)) _selectList(currentList[0].title);44 _displayItems();45 _setCookies();46 window.location.reload();47 };48 function _addTodoFromModal() {49 if (selectedList === undefined) {50 alert('Please create a list before adding a todo!');51 return;52 }53 todoInput.toggle();54 const data = todoInput.getData();55 const title = data.title;56 const description = data.description;57 const date = data.date;58 const priority = data.priority;59 todoInput.resetForm();60 statistics.addOpen();61 todos.addTodo(selectedList, title);62 todos.setParameters(selectedList, title, description, date, priority);63 64 _displayItems();65 _setCookies();66 };67 function _addListFromModal() {68 let firstListEntry = false;69 if (lists.getListsArray().length === 0) firstListEntry = true;70 listInput.toggle();71 const data = listInput.getData();72 const listTitle = data.title;73 const listDescription = data.description;74 lists.createList(listTitle);75 lists.setDescription(listTitle, listDescription);76 listInput.resetForm();77 if (firstListEntry === true) _selectList(listTitle);78 _displayItems();79 _setCookies();80 };81 function _addTodoEventListeners() {82 listenFor.deleteTodoButton((e) => _removeTodo(e.currentTarget.parentNode.parentNode.dataset.title));83 };84 _addTodoEventListeners();85 function _addListEventListeners() {86 //If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.87 listenFor.deleteListButton(_removeList);88 listenFor.clickOnList((e) => {89 _selectList(e.currentTarget.dataset.title)90 _displayItems();91 });92 };93 _addListEventListeners();94 //addButtons95 listenFor.addListButton(listInput.toggle);96 listenFor.addTodoButton(todoInput.toggle);97 //close addButtons98 listenFor.closeListButton(listInput.toggle);99 listenFor.closeTodoButton(todoInput.toggle);100 //sumbit forms buttons101 listenFor.submitListButton(_addListFromModal);102 listenFor.submitTodoButton(_addTodoFromModal);103 function _displayItems() {104 const currentLists = lists.getListsArray();105 if (currentLists.length === 0) {106 selectedList = undefined;107 return;108 };109 domManipulation.displayLists(currentLists);110 const currentTodoArray = lists.getTodoArray(selectedList);111 domManipulation.removeAllTodos();112 if (!(currentTodoArray.length === 0)) {113 domManipulation.displayAllTodos(currentTodoArray);114 _addTodoEventListeners();115 }116 _addListEventListeners();117 domManipulation.selectList(selectedList);118 };119 //deletes wrong list120 function run() {121 const listsCookie = _getCookies()122 //checks for cookies and sets them if there are some,123 //if there are none creates a default list and selects it124 if (listsCookie != null) {125 let cookie = _getCookies();126 lists.setListsArray(cookie);127 const currentLists = lists.getListsArray();128 if (currentLists.length === 0) return;129 _selectList(currentLists[0].title);130 _displayItems();131 } else {132 const defaultListTitle = 'Default List';133 lists.createList(defaultListTitle);134 lists.setDescription(defaultListTitle, 'This is the default list. You can delete me, if you want to. :(');135 _selectList(defaultListTitle);136 _displayItems();137 };138 };139 return {run};140})();...
config.js
Source:config.js
1report({2 "testSuite": "BackstopJS",3 "tests": [4 {5 "pair": {6 "reference": "../bitmaps_reference/backstop_default_listenfor_login_0_document_0_phone.png",7 "test": "../bitmaps_test/20181013-112353/backstop_default_listenfor_login_0_document_0_phone.png",8 "selector": "document",9 "fileName": "backstop_default_listenfor_login_0_document_0_phone.png",10 "label": "listenfor_login",11 "requireSameDimensions": true,12 "misMatchThreshold": 0.1,13 "url": "http://listenfor.jerryonlyzrj.com/",14 "referenceUrl": "",15 "expect": 0,16 "viewportLabel": "phone",17 "diff": {18 "isSameDimensions": true,19 "dimensionDifference": {20 "width": 0,21 "height": 022 },23 "misMatchPercentage": "2.09",24 "analysisTime": 3825 },26 "diffImage": "../bitmaps_test/20181013-112353/failed_diff_backstop_default_listenfor_login_0_document_0_phone.png"27 },28 "status": "fail"29 },30 {31 "pair": {32 "reference": "../bitmaps_reference/backstop_default_listenfor_editor_0_document_0_phone.png",33 "test": "../bitmaps_test/20181013-112353/backstop_default_listenfor_editor_0_document_0_phone.png",34 "selector": "document",35 "fileName": "backstop_default_listenfor_editor_0_document_0_phone.png",36 "label": "listenfor_editor",37 "requireSameDimensions": true,38 "misMatchThreshold": 0.1,39 "url": "http://listenfor.jerryonlyzrj.com/editor",40 "referenceUrl": "",41 "expect": 0,42 "viewportLabel": "phone",43 "diff": {44 "isSameDimensions": true,45 "dimensionDifference": {46 "width": 0,47 "height": 048 },49 "misMatchPercentage": "0.69",50 "analysisTime": 3751 },52 "diffImage": "../bitmaps_test/20181013-112353/failed_diff_backstop_default_listenfor_editor_0_document_0_phone.png"53 },54 "status": "fail"55 },56 {57 "pair": {58 "reference": "../bitmaps_reference/backstop_default_listenfor_dashboard_0_document_0_phone.png",59 "test": "../bitmaps_test/20181013-112353/backstop_default_listenfor_dashboard_0_document_0_phone.png",60 "selector": "document",61 "fileName": "backstop_default_listenfor_dashboard_0_document_0_phone.png",62 "label": "listenfor_dashboard",63 "requireSameDimensions": true,64 "misMatchThreshold": 0.1,65 "url": "http://listenfor.jerryonlyzrj.com/dashboard",66 "referenceUrl": "",67 "expect": 0,68 "viewportLabel": "phone",69 "diff": {70 "isSameDimensions": true,71 "dimensionDifference": {72 "width": 0,73 "height": 074 },75 "misMatchPercentage": "1.81",76 "analysisTime": 3877 },78 "diffImage": "../bitmaps_test/20181013-112353/failed_diff_backstop_default_listenfor_dashboard_0_document_0_phone.png"79 },80 "status": "fail"81 },82 {83 "pair": {84 "reference": "../bitmaps_reference/backstop_default_listenfor_register_0_document_0_phone.png",85 "test": "../bitmaps_test/20181013-112353/backstop_default_listenfor_register_0_document_0_phone.png",86 "selector": "document",87 "fileName": "backstop_default_listenfor_register_0_document_0_phone.png",88 "label": "listenfor_register",89 "requireSameDimensions": true,90 "misMatchThreshold": 0.1,91 "url": "http://listenfor.jerryonlyzrj.com/register",92 "referenceUrl": "",93 "expect": 0,94 "viewportLabel": "phone",95 "diff": {96 "isSameDimensions": true,97 "dimensionDifference": {98 "width": 0,99 "height": 0100 },101 "misMatchPercentage": "1.98",102 "analysisTime": 38103 },104 "diffImage": "../bitmaps_test/20181013-112353/failed_diff_backstop_default_listenfor_register_0_document_0_phone.png"105 },106 "status": "fail"107 }108 ],109 "id": "backstop_default"...
admin.js
Source:admin.js
1jQuery(document).ready(function () {2 if (jQuery('#srzfbappid').length) {3 jQuery.ajaxSetup({cache: true});4 jQuery.getScript('//connect.facebook.net/en_US/sdk.js', function () {5 FB.init({6 appId: jQuery('#srzfbappid').val(),7 version: 'v2.5'8 });9 jQuery('#srzFBloginbutton').click(srzFacebookLogin);10 if (jQuery('#srzfbaccesstoken').val().length) {11 jQuery('#srzFBloginbutton').html('Renew Token');12 }13 else {14 jQuery('#srzFBloginbutton').html('Login and Get Token');15 }16 function srzFacebookLogin() {17 FB.login(function () {18 FB.getLoginStatus(function (response) {19 if (response.status === 'connected') {20 jQuery('#srzfbaccesstoken').val(response.authResponse.accessToken);21 jQuery('#srzFBloginbutton').fadeOut();22 }23 });24 }, {scope: 'user_photos, user_videos, user_events'});25 }26 });27 }28 jQuery('h3.hndle2, div.handlediv').click(function () {29 jQuery(this).parent().toggleClass('closed');30 });31 jQuery('.srz-cond').srz_conditionize();32});33(function ($) {34 $.fn.srz_conditionize = function (options) {35 var settings = $.extend({36 hideJS: true37 }, options);38 $.fn.showOrHide = function (listenTo, listenFor, $section) {39 var listenForArray = listenFor.toString().split(',');40 for (var i = 0; i < listenForArray.length; i++) {41 listenForArray[i] = listenForArray[i].trim();42 }43 if ($(listenTo).is(':hidden')) {44 $section.slideUp(50, triggernext);45 }46 else if ($(listenTo).is('select, input[type=text]') && listenForArray.indexOf($(listenTo).val()) != -1) {47 $section.slideDown(50, triggernext);48 }49 else if (listenForArray.indexOf($(listenTo + ":checked").val()) != -1) {50 $section.slideDown(50, triggernext);51 }52 else {53 $section.slideUp(50, triggernext);54 }55 function triggernext() {56 if ($section.data('cond-option')) {57 $section.find('input').trigger('change');58 }59 }60 };61 return this.each(function () {62 var listenTo = "[class=" + $(this).data('cond-option') + "]";63 var listenFor = $(this).data('cond-value');64 var $section = $(this);65 //Set up event listener66 $(listenTo).on('change', function () {67 $.fn.showOrHide(listenTo, listenFor, $section);68 });69 //If setting was chosen, hide everything first...70 if (settings.hideJS) {71 $(this).hide();72 }73 //Show based on current value on page load74 $.fn.showOrHide(listenTo, listenFor, $section);75 });76 }...
upbot.js
Source:upbot.js
1#!/usr/bin/env node2'use strict';3var Botkit = require('botkit');4var fs = require('fs');5var path = require('path');6var util = require('util');7var yaml = require('js-yaml');8// import topic controllers9var utilities = require('./topics/utilities')10var status = require('./topics/status')11var chat = require('./topics/chat')12try {13 var config = yaml.safeLoad(fs.readFileSync('config.yaml', 'utf8'));14 var intent = config.intent;15 var slack_token = process.env.HODQ_SLACK_API_TOKEN;16 var redis_host = process.env.UPBOT_REDIS_HOST.trim();17 var redis_port = process.env.UPBOT_REDIS_PORT.trim();18 var listenFor = 'direct_message,direct_mention,mention'19 var redisConfig = {20 "host": redis_host,21 "port": redis_port,22 "db": 0,23 "namespace": "upbot",24 "methods": ["services", "permissions"],25 };26 var redisStorage = require('botkit-storage-redis')(redisConfig);27 var controller = Botkit.slackbot({28 debug: true,29 storage: redisStorage30 })31 var bot = controller.spawn({32 token: slack_token33 }).startRTM();34} catch (e) {35 console.log(e);36};37// chat controllers38controller.hears(intent.hello, listenFor, function(bot, message) {39 chat.hello(bot, message, controller);40});41controller.hears(intent.callMe, listenFor, function(bot, message) {42 chat.callMe(bot, message, controller);43});44controller.hears(intent.whoAmI, listenFor, function(bot, message) {45 chat.whoAmI(bot, message, controller);46});47// status controllers48controller.hears(intent.getStatus, listenFor, function(bot, message) {49 status.getStatus(bot, message, controller);50});51controller.hears(intent.list, listenFor, function(bot, message) {52 status.list(bot, message, controller);53});54controller.hears(intent.addService, listenFor, function(bot, message) {55 status.addService(bot, message, controller);56});57controller.hears(intent.setStatus, listenFor, function(bot, message) {58 status.setStatus(bot, message, controller);59});60// utlity controllers61controller.hears(intent.help, listenFor, function(bot, message) {62 utilities.help(bot, message);63});64controller.hears(intent.shutdown, listenFor, function(bot, message) {65 utilities.shutdown(bot, message);66});67controller.hears(intent.uptime, listenFor, function(bot, message) {68 utilities.uptime(bot, message);...
conditional.js
Source:conditional.js
1/* * * * * * * * * * * * * * * * * *2* Show/hide fields conditionally3* * * * * * * * * * * * * * * * * */4(function($) {5 $.fn.conditionize = function(options){ 6 7 var settings = $.extend({8 hideJS: true9 }, options );10 11 $.fn.showOrHide = function(listenTo, listenFor, $section) {12 if ($(listenTo).is('select, input[type=text]') && $(listenTo).val() == listenFor ) {13 $section.slideDown();14 }15 else if ($(listenTo + ":checked").val() == listenFor) {16 $section.slideDown();17 }18 else {19 $section.slideUp();20 }21 } 22 return this.each( function() {23 var listenTo = "[name=" + $(this).data('cond-option') + "]";24 var listenFor = $(this).data('cond-value');25 var $section = $(this);26 27 //Set up event listener28 $(listenTo).on('change', function() {29 $.fn.showOrHide(listenTo, listenFor, $section);30 });31 //If setting was chosen, hide everything first...32 if (settings.hideJS) {33 $(this).hide();34 }35 //Show based on current value on page load36 $.fn.showOrHide(listenTo, listenFor, $section);37 });38 }39}(jQuery));40 ...
conditionize.jquery.js
Source:conditionize.jquery.js
1(function($) {2 $.fn.conditionize = function(options){ 3 4 var settings = $.extend({5 hideJS: true6 }, options );7 8 $.fn.showOrHide = function(listenTo, listenFor, $section) {9 if ($(listenTo).is('select, input[type=text]') && $(listenTo).val() == listenFor ) {10 $section.slideDown();11 }12 else if ($(listenTo + ":checked").val() == listenFor) {13 $section.slideDown();14 }15 else {16 $section.slideUp();17 }18 } 19 return this.each( function() {20 var listenTo = "[name=" + $(this).data('cond-option') + "]";21 var listenFor = $(this).data('cond-value');22 var $section = $(this);23 24 //Set up event listener25 $(listenTo).on('change', function() {26 $.fn.showOrHide(listenTo, listenFor, $section);27 });28 //If setting was chosen, hide everything first...29 if (settings.hideJS) {30 $(this).hide();31 }32 //Show based on current value on page load33 $.fn.showOrHide(listenTo, listenFor, $section);34 });35 }...
Using AI Code Generation
1const puppeteer = require('puppeteer');2const {listenFor} = require('puppeteer-listen-for');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.type('#lst-ib', 'Puppeteer');7 await listenFor(page, 'response', (response) => {8 console.log(response.url());9 });10 await page.click('#tsbb');11 await browser.close();12})();13import {listenFor} from 'puppeteer-listen-for';14import * as puppeteer from 'puppeteer';15(async () => {16 const browser = await puppeteer.launch();17 const page = await browser.newPage();18 await page.type('#lst-ib', 'Puppeteer');19 await listenFor(page, 'response', (response) => {20 console.log(response.url());21 });22 await page.click('#tsbb');23 await browser.close();24})();
Using AI Code Generation
1const { PuppeteerCrawler } = require('apify');2const { launchPuppeteer } = require('apify-shared/puppeteer');3const { log } = Apify.utils;4Apify.main(async () => {5 const browser = await launchPuppeteer();6 const page = await browser.newPage();7 const crawler = new PuppeteerCrawler({8 requestList: await Apify.openRequestList('my-list', [9 handlePageFunction: async ({ page, request }) => {10 log.info(`Processing ${request.url}...`);11 await Apify.pushData({12 title: await page.title(),13 });14 },15 handleFailedRequestFunction: async ({ request }) => {16 await Apify.pushData({17 });18 },19 });20 await crawler.run();21 await browser.close();22});23const { CheerioCrawler } = require('apify');24const { log } = Apify.utils;25Apify.main(async () => {26 const crawler = new CheerioCrawler({27 requestList: await Apify.openRequestList('my-list', [28 handlePageFunction: async ({ request, $ }) => {29 log.info(`Processing ${request.url}...`);30 await Apify.pushData({31 title: $('title').text(),32 });33 },34 handleFailedRequestFunction: async ({ request }) => {35 await Apify.pushData({36 });37 },38 });39 await crawler.run();40});41const { PuppeteerCrawler } = require('apify');42const { launchPuppeteer } = require('apify-shared/puppeteer');43const { log } = Apify.utils;44Apify.main(async () => {45 const browser = await launchPuppeteer();46 const page = await browser.newPage();47 const crawler = new PuppeteerCrawler({48 requestList: await Apify.openRequestList('my-list', [
Using AI Code Generation
1const { PuppeteerCrawler } = require('apify');2const crawler = new PuppeteerCrawler({3 handlePageFunction: async ({ page, request }) => {4 await page.listenFor('request', async (req) => {5 });6 },7});8The pool is initialized with a function that must return a Promise resolving to a Puppeteer [Browser](
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!