Best JavaScript code snippet using playwright-internal
screenshot-viewer.js
Source:screenshot-viewer.js  
1/**2 * @license Copyright 2017 Google Inc. All Rights Reserved.3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.04 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.5 */6'use strict';7/* global aggregatedScreenshots */8/* eslint-env browser */9const queuedRendering = [];10const imagePopoverElement = document.getElementById('image-popover');11const imagePopoverImageElement = imagePopoverElement.querySelector('img');12const rootElement = document.getElementById('container');13let isAlignTimelineEnabled = true;14let shouldHidePopover = true;15/**16 * Incrementally renders the sites, otherwise it hangs the browser17 * because it's rendering so many screenshots.18 * @param {!Function} fn19 */20function enqueueRendering(fn) {21  const isFirst = queuedRendering.length === 0;22  queuedRendering.push(fn);23  if (isFirst) {24    renderFromQueue();25  }26}27function renderFromQueue() {28  window.requestAnimationFrame(_ => {29    const renderFn = queuedRendering.shift();30    if (renderFn) {31      renderFn();32      renderFromQueue();33    }34  });35}36/**37 * Renders the A/B screenshot comparison content generated from analyze.js.38 */39function main() {40  registerHotkeys();41  renderLegend(aggregatedScreenshots.a, aggregatedScreenshots.b);42  renderScreenshots(aggregatedScreenshots.data);43  document.getElementById('align-control').addEventListener('click', onToggleAlign);44}45main();46/**47 * Toggling the align timelines checkbox throws away previously rendered48 * timelines and renders new timelines based on the new setting value.49 */50function onToggleAlign() {51  isAlignTimelineEnabled = !isAlignTimelineEnabled;52  removeChildren(rootElement);53  renderScreenshots(aggregatedScreenshots.data);54}55/**56 * Queues the rendering of the timelines for each site57 * so the page loading is less painful.58 * @param {!SiteScreenshotsComparison} comparisons59 */60function renderScreenshots(comparisons) {61  comparisons.forEach(comparison =>62    enqueueRendering(() => {63      rootElement.appendChild(createSiteElement(comparison));64    }));65}66/**67 * Animates the horizontal scroll position68 * @param {number} scrollDistancePx69 */70function scrollPageHorizontally(scrollDistancePx, durationMs = 350) {71  // thank you, paul lewis. <3z72  const ease = (v, pow=3) => 1 - Math.pow(1 - v, pow);73  const start = Date.now();74  const end = start + durationMs;75  let lastChangePx = 0;76  scroll();77  function scroll() {78    const now = Date.now();79    if (now >= end) return;80    const pctDone = (now - start) / durationMs;81    const pxToGo = ease(pctDone) * scrollDistancePx;82    window.scrollBy(pxToGo - lastChangePx, 0);83    lastChangePx = pxToGo;84    window.requestAnimationFrame(scroll);85  }86}87/**88 * Binds global keyboard event handlers for panning the view with A & D keys.89 */90function registerHotkeys() {91  document.addEventListener('keydown', event => {92    // move to the left93    if (event.code === 'KeyA') scrollPageHorizontally(-350);94    // move to the right95    if (event.code === 'KeyD') scrollPageHorizontally(350);96  }, {passive: true});97}98/**99 * Renders the legend in the top bar based on the name of the path.100 * @param {string} a101 * @param {string} b102 */103function renderLegend(a, b) {104  document.getElementById('legend-a').appendChild(createText(a));105  document.getElementById('legend-b').appendChild(createText(b));106}107/**108 * Creates an A/B timeline comparison for a site.109 * @param {!SiteScreenshotsComparison} comparison110 * @return {!Element}111 */112function createSiteElement(comparison) {113  const siteElement = createElement('div', 'site-container');114  const siteNameElement = createElement('div', 'site-name');115  siteNameElement.appendChild(createText(comparison.siteName));116  siteElement.appendChild(siteNameElement);117  const runTimelineElement = createElement('div');118  runTimelineElement.appendChild(createRunTimeline(comparison.runA.screenshots));119  runTimelineElement.appendChild(createRunTimeline(comparison.runB.screenshots));120  if (isAlignTimelineEnabled) {121    const maxMsTimestamp = comparison.runA.screenshots122      .concat(comparison.runB.screenshots)123      .reduce((acc, screenshot) => Math.max(acc, screenshot.timing), 0);124    runTimelineElement.appendChild(createTimelineXAxis(maxMsTimestamp));125  } else {126    runTimelineElement.style['overflow-x'] = 'scroll';127  }128  siteElement.appendChild(runTimelineElement);129  return siteElement;130}131/**132 * Creates a timeline of screenshots for a single run.133 * @param {!Array<!Screenshot>} screenshots134 * @return {!Element}135 */136function createRunTimeline(screenshots) {137  const runElement = createElement('div', 'run-container');138  if (isAlignTimelineEnabled) {139    runElement.appendChild(createAlignedTimeline(screenshots));140  } else {141    runElement.appendChild(createNonOverlappingTimeline(screenshots));142  }143  return runElement;144}145/**146 * Creates a marker every 0.5 seconds on the x axis.147 * @param {number} maxMsTimestamp148 * @return {!Element}149 */150function createTimelineXAxis(maxMsTimestamp) {151  const xAxisElement = createElement('div', 'x-axis-container');152  const maxSeconds = Math.ceil(maxMsTimestamp) / 1000;153  for (let i = 0; i <= maxSeconds; i += 0.5) {154    const markerElement = createElement('div', 'x-axis-marker');155    markerElement.style.left = i * 1000 / 5 + 'px';156    markerElement.style.top = '-20px';157    markerElement.appendChild(createText(i + 's'));158    xAxisElement.appendChild(markerElement);159  }160  return xAxisElement;161}162/**163 * Creates a timeline of screenshots that are aligned on the x axis.164 * Useful for comparing across runs and sites.165 * @param {!Array<!Screenshot>} screenshots166 * @return {!Element}167 */168function createAlignedTimeline(screenshots) {169  const timelineElement = createElement('div', 'timeline-container');170  timelineElement.style.height = '115px';171  let previousShownScreenshotTiming = 0;172  screenshots.forEach(screenshot => {173    const screenshotElement = createElement('div', 'screenshot-container');174    screenshotElement.style.position = 'absolute';175    screenshotElement.style.left = screenshot.timing / 5 + 'px';176    const headerElement = createElement('div', 'screenshot-header');177    const headerLabelElement = createHeaderLabelElement(screenshot);178    if (!headerLabelElement.childNodes.length) {179      if (screenshot.timing - previousShownScreenshotTiming < 100) {180        return;181      }182    }183    previousShownScreenshotTiming = screenshot.timing;184    if (headerLabelElement.childNodes.length) {185      screenshotElement.style.top = '-17px';186    }187    headerElement.appendChild(headerLabelElement);188    screenshotElement.appendChild(headerElement);189    screenshotElement.appendChild(createScreenshotImageElement(screenshot));190    timelineElement.appendChild(screenshotElement);191  });192  return timelineElement;193}194/**195 * Creates a timeline of screenshots that are not aligned.196 * Useful for viewing every screenshot.197 * @param {!Array<!Screenshot>} screenshots198 * @return {!Element}199 */200function createNonOverlappingTimeline(screenshots) {201  const timelineElement = createElement('div', 'timeline-container');202  screenshots.forEach(screenshot => {203    const screenshotElement = createElement('div', 'screenshot-container');204    const headerElement = createElement('div', 'screenshot-header');205    headerElement.appendChild(createHeaderLabelElement(screenshot));206    headerElement.appendChild(createText(screenshot.timing));207    screenshotElement.appendChild(headerElement);208    screenshotElement.appendChild(createScreenshotImageElement(screenshot));209    timelineElement.appendChild(screenshotElement);210  });211  return timelineElement;212}213/**214 * @param {!Screenshot} screenshot215 * @return {!Element}216 */217function createHeaderLabelElement(screenshot) {218  const headerLabelElement = createElement('div', 'screenshot-header-label');219  // Leave a space after each text label because a single screenshot may have220  // multiple labels on it221  if (screenshot.isFCP) {222    headerLabelElement.classList.add('is-fcp');223    headerLabelElement.appendChild(createText('fcp '));224  }225  if (screenshot.isFMP) {226    headerLabelElement.classList.add('is-fmp');227    headerLabelElement.appendChild(createText('fmp '));228  }229  if (screenshot.isVC85) {230    headerLabelElement.classList.add('is-vc85');231    headerLabelElement.appendChild(createText('vc85 '));232  }233  if (screenshot.isVC100) {234    headerLabelElement.classList.add('is-vc100');235    headerLabelElement.appendChild(createText('vc100 '));236  }237  return headerLabelElement;238}239/**240 * @param {!Screenshot} screenshot241 * @return {!Element}242 */243function createScreenshotImageElement(screenshot) {244  const image = createElement('img', 'screenshot-image');245  image.src = screenshot.datauri;246  image.addEventListener('mouseenter', event =>247    onImageMouseover(imagePopoverElement, screenshot, event));248  image.addEventListener('mouseleave', () => {249    shouldHidePopover = true;250    setTimeout(_ => {251      if (shouldHidePopover) {252        imagePopoverElement.classList.add('hidden');253      }254    }, 200);255  });256  return image;257}258/**259 * Show a zoomed in image of the screenshot as a popover.260 * @param {!Element} imagePopoverElement261 * @param {!Screenshot} screenshot262 * @param {!Event} event263 */264function onImageMouseover(imagePopoverElement, screenshot, event) {265  shouldHidePopover = false;266  imagePopoverImageElement.src = screenshot.datauri;267  imagePopoverElement.classList.remove('hidden');268  const pos = event.currentTarget.getBoundingClientRect();269  imagePopoverElement.style.top = pos.bottom + 2 + 'px';270  imagePopoverElement.style.left = pos.left + 20 + 'px';271}272/**273 * @param {string} tag274 * @param {string} className275 */276function createElement(tag, className) {277  const element = document.createElement(tag);278  element.className = className;279  return element;280}281/**282 * @param {string} text283 */284function createText(text) {285  return document.createTextNode(text);286}287/**288 * @param {!Element} parent289 */290function removeChildren(parent) {291  while (parent.firstChild) {292    parent.removeChild(parent.firstChild);293  }...galenReport.js
Source:galenReport.js  
1/**2 * Copyright 2014 - 2017 Cognizant Technology Solutions3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 **/16var popupFlag=0;17jQuery.fn.centerHorizontally = function () {18	console.log(popupFlag);19	if(popupFlag==1){20		this.css({21		position: 'fixed',22		top: '200px',23		width:'700px' ,24		height:'150px',25		overflow: 'auto',26		left: "300px",27		'z-index': '2'28    });29	}else{30		this.css({31		position: 'fixed',32		top: '40px',33		width: Math.max(0, (($(window).width() - 70))) + "px",34		height: Math.max(0, (($(window).height() - 50))) + "px",35		overflow: 'auto',36		left: "30px",37		'z-index': '2'38		});39	}40    return this;41}42function loadImage(imagePath, callback) {43    var img = new Image();44    img.onload = function () {45        callback(this, this.width, this.height);46    };47    img.onerror = function () {48        console.log("Cannot load image", "Path: " + imagePath);49    };50    img.src = imagePath;51}52function setStatusLink(stat, actualImagePath, expectedImagePath, mapImagePath, objects, screenshot)53{54    if ((actualImagePath && actualImagePath !== "") || (screenshot && screenshot !== "")) {55	var link=screenshot?screenshot.indexOf(".html")!==-1 ? ("' href='." + screenshot) : "":"";56        return "<a class='exe table " + stat.toUpperCase() +57                "' data-actual-image='" + actualImagePath58                + "' data-expected-image='" + expectedImagePath59                + "' data-map-image='" + mapImagePath60                + "' data-screenshot-image='." + screenshot61				+ link62                + "' data-objects-area='" + objects63                + "' style='cursor:pointer;'>" + stat + "</a>";64    }65    return stat;66}67function setStatusLinkWeb(stat,stepNo,fileLink, flag){68	fileLink=fileLink.replaceAll("\\","/");69	popupFlag=1;70	return "<a class='exe table "+ stat.toUpperCase()+ "' onclick='showDialog("+ stepNo +",\""+ fileLink +"\","+flag+")'>"+ stat +" </a>";71}72function setStatus() {73    var $this = $(this);74    var actualImagePath = $this.attr("data-actual-image");75    var expectedImagePath = $this.attr("data-expected-image");76    var mapImagePath = $this.attr("data-map-image");77    var screenshot = $this.attr("data-screenshot-image");78    var objects = $this.attr("data-objects-area");79    if (actualImagePath && actualImagePath !== "undefined") {80        showImageComparison(actualImagePath, expectedImagePath, mapImagePath);81    }82    else if (screenshot && screenshot !== "undefined") {83        showScreenShot(objects, screenshot);84    }85}86function showImageComparison(actualImagePath, expectedImagePath, mapImagePath) {87    loadImage(actualImagePath, function (actualImage, actualImageWidth, actualImageHeight) {88        loadImage(expectedImagePath, function (expectedImage, expectedImageWidth, expectedImageHeight) {89            loadImage(mapImagePath, function (mapImage, mapImageWidth, mapImageHeight) {90                showPopup(setImages({91                    actual: actualImagePath,92                    expected: expectedImagePath,93                    map: mapImagePath94                }));95            });96        });97    });98    return false;99}100function showScreenShot(objects, screenshot) {101    showScreenshotWithObjects(screenshot, this.width, this.height, objects);102}103function onImageComparisonClick() {104    var $this = $(this);105    var actualImagePath = $this.attr("data-actual-image");106    var expectedImagePath = $this.attr("data-expected-image");107    var mapImagePath = $this.attr("data-map-image");108    loadImage(actualImagePath, function (actualImage, actualImageWidth, actualImageHeight) {109        loadImage(expectedImagePath, function (expectedImage, expectedImageWidth, expectedImageHeight) {110            loadImage(mapImagePath, function (mapImage, mapImageWidth, mapImageHeight) {111                showPopup(setImages({112                    actual: actualImagePath,113                    expected: expectedImagePath,114                    map: mapImagePath115                }));116            });117        });118    });119    return false;120}121function showScreenshotWithObjects(screenshotPath, width, height, objects) {122    loadImage(screenshotPath, function (actualImage, actualImageWidth, actualImageHeight) {123        $('#screenShotImage').attr("src", screenshotPath);124        showPopup(setScreenshotImages({125            screenshot: screenshotPath,126            objects: objects127        }));128    });129}130function setScreenshotImages(data) {131    var screenshotElement = $("div.screenshot-canvas");132    if (data.objects && data.objects !== "undefined")133        appendObjects(screenshotElement, JSON.parse(data.objects));134    screenshotElement.show();135    return screenshotElement;136}137function setImages(data) {138    $('#actual').attr("src", data.actual);139    $('#expected').attr("src", data.expected);140    $('#comparison').attr("src", data.map);141    $("div.image-comparison").show();142    return $("div.image-comparison");143}144function showShadow() {145    $("#screen-shadow").fadeIn();146}147function hideShadow() {148    $("#screen-shadow").fadeOut();149    removeAllChild($('div.canvas-rect'));150}151function showPopup(html) {152    showShadow();153    $("#popup .popup-content").html(html);154    $("#popup").centerHorizontally().fadeIn('fast');155}156function hidePopup() {157    $("div.image-comparison").hide();158    $("div.screenshot-canvas").hide();159    hideShadow();160    $("#popup").fadeOut();161}162function onPopupCloseClick() {163    hideShadow();164    $(this).closest(".popup").fadeOut();165    return false;166}167var colors = [168    "#B55CFF", "#FF5C98", "#5C9AFF", "#5CE9FF", "#5CFFA3", "#98FF5C", "#FFE95C", "#FFA05C"169];170function appendObjects(screenshotElement, objects)171{172    objects.forEach(function (object, index) {173        screenshotElement.append(getObjectCanvas(object.name, JSON.parse(object.area), colors[index % colors.length]));174    });175}176function getObjectCanvas(name, area, color)177{178    return  "<div class='canvas-rect' style='left: " + area[0] + "px; " +179            "top:" + area[1] + "px;" +180            "width: " + area[2] + "px;" +181            "height:" + area[3] + "px; border-color:" + color + ";'>"182            + "<div class='canvas-rect-wrapper'>"183            + "<div class='canvas-rect-hint' style='background: " + color + ";'>" + name + "</div>"184            + "</div>"185            + "</div>"186}187function removeAllChild(el) {188    try {189        for (var i = 0; i < el.length; i++)190        {191            el[i].remove();192        }193    }194    catch (e) {195    }196}197function showDialog(stepNo, fileLink, flag) {198	var request=fileLink+"/Step-"+stepNo+"_Request.txt";199	if (flag==1){200		request="";201	}202	var response=fileLink+"/Step-"+stepNo+"_Response.txt";203    showShadow();204	if (request !=""){205		$('#Request').css("background","#008CBA");206		$('#Request').attr("href", request);207	}208	else{209		$('#Request').css("background","#D3D3D3");210		$('#Request').attr("href", "");211	}212	if (response !=""){213		$('#Response').css("background","#4CAF50");214	    $('#Response').attr("href", response);215	}216	else{217		$('#Response').css("background","#D3D3D3");218		$('#Response').attr("href", "");219	}220    $("#popup-web .popup-content").show();221    $("#popup-web").centerHorizontally().fadeIn('fast');...main.js
Source:main.js  
1$(document).ready(function () {2    /* highlight code */3    SyntaxHighlighter.defaults['gutter'] = false;4    SyntaxHighlighter.all();5    /* generate the input and labels */6    $(".tabs").each(function () {7        initialize_tabs($(this));8    });9    /* initialize snippets */10    $('[data-snippet-source]').each(function () {11        var parent = $(this);12        var source = parent.attr('data-snippet-source');13        var type = parent.attr('data-snippet-type');14        /* If they didn't specify a type */15        if (!type) {16            /* Get the type from the file type */17            type = source.split('.').pop().toLowerCase();18            switch (type)19            {20                case "cs":21                    type = "csharp";22                    break;23            }24        }25        parent.text("Loading...");26        $.ajax({27            url: source,28            dataType: "text"29        }).done(function (data) {30            /* get the scroll position before adding */31            var pageYOffsetBefore = window.pageYOffset;32            var YPositionOfElement = parent.offset().top;33            var documentHeightBefore = $(document).height();34            /* compute whether item will be affecting our scroll position, based on whether the item is above our view or not */35            var doesAffectScrollPosition = YPositionOfElement < pageYOffsetBefore;36            /* remove all children */37            parent.empty();38            var newChild = document.createElement("pre");39            newChild.appendChild(document.createTextNode(data));40            newChild.setAttribute("class", "brush: " + type);41            /* push the item that will become the highlighted */42            parent.append(newChild);43            /* Have SyntaxHighlighter run on the new child */44            SyntaxHighlighter.highlight({}, newChild);45            /* if the item affects our scroll position */46            if (doesAffectScrollPosition) {47                var documentHeightAfter = $(document).height();48                var scrollBy = documentHeightAfter - documentHeightBefore;49                window.scrollBy(null, scrollBy);50            }51        }).fail(function () {52            parent.text("Failed to load.");53        });;54    });55    // Initialize the "AppsUsingControl" control56    initializeAppsUsingControl();57});58var _uniqueIdNum = 0;59function getNewUniqueName()60{61    return 'myUniqueId' + _uniqueIdNum++;62}63function initialize_tabs(tabs_parent)64{65    var groupName = getNewUniqueName();66    var first = true;67    var elementsToAdd = [];68    tabs_parent.children('[title]').each(function () {69        var id = getNewUniqueName();70        var input = jQuery('<input/>',71        {72            id: id,73            type: 'radio',74            name: groupName75        });76        /* first one gets checked by default */77        if (first)78        {79            input.attr('checked', true);80            first = false;81        }82        elementsToAdd.push(input);83        elementsToAdd.push(jQuery('<label>',84            {85                text: $(this).attr("title"),86                "for": id87            }));88    });89    /* reverse the array so when we add, we add in order */90    elementsToAdd.reverse();91    /* and then add at the beginning */92    elementsToAdd.forEach(function (el) {93        tabs_parent.prepend(el);94    });95}96function initializeAppsUsingControl() {97    $(".apps-using-control").each(function () {98        var container = $(this);99        // Add the screenshot container100        var screenshotElement = document.createElement("div");101        screenshotElement.className = "app-using-control-screenshot";102        container.append(screenshotElement);103    })104    $('.app-using-control[data-icon][data-screenshot]').each(function () {105        var parent = $(this);106        // Get and clear the inner text107        var name = parent.text();108        parent.text("");109        var icon = parent.attr('data-icon');110        var screenshot = parent.attr('data-screenshot');111        var iconElement = document.createElement("div");112        iconElement.style.backgroundImage = "url('" + icon + "')";113        parent.append(iconElement);114        var nameElement = document.createElement("span");115        nameElement.innerText = name;116        parent.append(nameElement);117        parent.hover(function () {118            var screenshotElement = $(this).parents(".apps-using-control").find(".app-using-control-screenshot");119            screenshotElement.css("background-image", "url('" + screenshot + "')");120            screenshotElement.css("display", "block");121        }, function () {122            var screenshotElement = $(this).parents(".apps-using-control").find(".app-using-control-screenshot");123            screenshotElement.css("display", "none");124        });125    });...GameScreenshotList.js
Source:GameScreenshotList.js  
1import { Component, Div } from '../global';2import { GameScreenshot } from './GameScreenshot';34export class GameScreenshotList extends Component {5	screenshots;6	firstScreenshot;78	constructor(screenshots) {9		super(10			'div',11			[{ name: 'class', value: 'gameScreenshotList' }],12			[13				screenshots.length >= 314					? new Div(15							[16								{ name: 'id', value: 'previousScreenshotImage' },17								{ name: 'class', value: 'screenshotButton' },18							],19							'<'20					  )21					: null,22				new Div(23					[{ name: 'class', value: 'imageContainer' }],24					screenshots25						.slice(0, 3)26						.map(27							(screenshot, index) =>28								new GameScreenshot(screenshot.image, `game-screenshot-${index}`)29						)30				),31				screenshots.length >= 332					? new Div(33							[34								{ name: 'id', value: 'nextScreenshotImage' },35								{ name: 'class', value: 'screenshotButton' },36							],37							'>'38					  )39					: null,40			]41		);4243		screenshots.forEach(screenshot => (new Image().src = screenshot.image));44		this.screenshots = screenshots;45		this.firstScreenshot = 0;46		this.handleNextClick = this.handleNextClick.bind(this);47		this.handlePreviousClick = this.handlePreviousClick.bind(this);48	}4950	handlePreviousClick(e) {51		e.stopPropagation();52		if (document.querySelector(`#previousScreenshotImage`)) {53			const selectedScreenshots = [0, 1, 2].map(number => ({54				a: document.querySelector(`#game-screenshot-${number}-a`),55				img: document.querySelector(`#game-screenshot-${number}-img`),56			}));57			selectedScreenshots.forEach((screenshotElement, index) => {58				screenshotElement.a.setAttribute(59					'href',60					this.screenshots[61						(((this.firstScreenshot + index - 1) % this.screenshots.length) +62							this.screenshots.length) %63							this.screenshots.length64					].image65				);66				screenshotElement.img.setAttribute(67					'src',68					this.screenshots[69						(((this.firstScreenshot + index - 1) % this.screenshots.length) +70							this.screenshots.length) %71							this.screenshots.length72					].image73				);74			});75			this.firstScreenshot =76				(((this.firstScreenshot - 1) % this.screenshots.length) +77					this.screenshots.length) %78				this.screenshots.length;79		}80	}8182	handleNextClick(e) {83		e.stopPropagation();84		if (document.querySelector(`#nextScreenshotImage`)) {85			const selectedScreenshots = [0, 1, 2].map(number => ({86				a: document.querySelector(`#game-screenshot-${number}-a`),87				img: document.querySelector(`#game-screenshot-${number}-img`),88			}));89			selectedScreenshots.forEach((screenshotElement, index) => {90				screenshotElement.a.setAttribute(91					'href',92					this.screenshots[93						(((this.firstScreenshot + index + 1) % this.screenshots.length) +94							this.screenshots.length) %95							this.screenshots.length96					].image97				);98				screenshotElement.img.setAttribute(99					'src',100					this.screenshots[101						(((this.firstScreenshot + index + 1) % this.screenshots.length) +102							this.screenshots.length) %103							this.screenshots.length104					].image105				);106			});107			this.firstScreenshot =108				(((this.firstScreenshot + 1) % this.screenshots.length) +109					this.screenshots.length) %110				this.screenshots.length;111		}112	}113114	initOrDestroyEvent(key = 'addEventListener') {115		document116			.querySelector(`#previousScreenshotImage`)117			?.[key]('click', this.handlePreviousClick);118119		document120			.querySelector(`#nextScreenshotImage`)121			?.[key]('click', this.handleNextClick);122	}
...aos.js
Source:aos.js  
1$(document).ready(function() {2    /**3     * .js-feature               the global container holding the images and blocks.4     * .js-screenshot-container  an inner container holding the images.5     * .js-screenshot-block      an element to click on to change the visible image.6     *7     * Each block element and image tag should also have an attribute as such: "data-screenshot-id" with an integer8     * value which match each other. e.g.9     *10     * <div class="js-screenshot-block" data-screenshot-id="1"></div>11     *12     * with13     *14     * <div class="js-screenshot-container">15     *   <img data-screenshot-id="1">16     * </div>17     */18    $('.js-screenshot-block, .js-screenshot-container img').click(function() {19        var clickedElement = $(this);20        var globalContainer = clickedElement.parents('.js-feature');21        var screenshotContainer = globalContainer.find('.js-screenshot-container');22        var screenshotId = clickedElement.data('screenshot-id');23        if (clickedElement.is('img')) {24            var blockElement = globalContainer.find('.js-screenshot-block[data-screenshot-id="' + screenshotId + '"]');25            switchScreenshot(blockElement, globalContainer, screenshotContainer, clickedElement);26        } else {27            var screenshotElement = screenshotContainer.find('[data-screenshot-id="' + screenshotId + '"]');28            switchScreenshot(clickedElement, globalContainer, screenshotContainer, screenshotElement);29        }30    });31    /**32     * Switches the top screenshot on the stack.33     *34     * @param blockElement  the block element that matches the screenshot (e.g. the block titled "To-Do" matches the35     * screenshot about the To-Do feature).36     * @param globalContainer  div with class .js-screenshot for this section.37     * @param screenshotContainer  div with class .js-screenshot-container for this section.38     * @param screenshotElement  the screenshot to be pushed to the top of the stack.39     */40    function switchScreenshot(blockElement, globalContainer, screenshotContainer, screenshotElement) {41        // Switch the 'selected' class to the block that was just clicked on.42        globalContainer.find('.js-screenshot-block').removeClass('selected');43        blockElement.addClass('selected');44        // Move the intended screenshot to the top of the stack.45        screenshotContainer.prepend(screenshotElement);46        /**47         * In the styling, the elements must have classes as such: shot1, shot2, shot3 in order from top to bottom to48         * achieve the stacking appearance.49         *50         * Here we reset those classes on the element so they can be back in order.51         */52        var i = 1;53        screenshotContainer.find('img').each(function() {54            var thisImg = $(this);55            var classes = thisImg.attr('class');56            // Only remove the 'shot([0-9]*)' class57            thisImg.removeClass(classes.match(/shot([0-9]*)/g).shift());58            thisImg.addClass('shot' + i);59            i++;60        });61    }...slideParser.js
Source:slideParser.js  
1const Promise = require('bluebird');2const fs = require('fs');3const readFile = Promise.promisify(fs.readFile);4const cheerio = require('cheerio');5const path = require('path');6const parseTarget = require('./targetParser');7const actionsInterpreter = require('../interpreters/actionsInterpreter');8function ParserError(message, extra) {9  Error.captureStackTrace(this, this.constructor);10  this.name = this.constructor.name;11  this.message = message;12  this.extra = extra;13}14/*15* Returns the absoulte file path name of the screenshot.16*/17function parseSlideWithScreenshot($, slideRelPath) {18  const screenshotElement = $('p\\:pic > p\\:blipFill > a\\:blip');19  if (screenshotElement.length === 0) {20    return Promise.resolve(undefined);21  }22  const relId = screenshotElement.attr('r:embed');23  if (relId === undefined) {24    return Promise.resolve(undefined);25  }26  return readFile(slideRelPath)27    .then((content) => {28      const r$ = cheerio.load(content, { xmlMode: true });29      const screenshotPath = r$(`Relationship[Id="${relId}"]`).attr('Target');30      return path.resolve(slideRelPath, '..', '..', screenshotPath);31    });32}33/*34* Returns the text of the first non-empty text box element35*/36function parseActionName($) {37  const txBodyElements = $('p\\:txBody > a\\:p > a\\:r > a\\:t')38                          .filter((i, elem) => $(elem).text() !== '');39  if (txBodyElements.length > 0) {40    return Promise.resolve(actionsInterpreter.lookup(txBodyElements[0].children[0].data));41  }42  return Promise.resolve(undefined);43}44/*45* TODO: Returns audio and caption items.46*/47function parseDisplayItems() {48  return Promise.resolve([]);49}50module.exports = function parseSlideFile(slideFilePath) {51  const fileBaseName = path.basename(slideFilePath, '.xml');52  const slideRelPath = path.resolve(slideFilePath, '..', '_rels', `${fileBaseName}.xml.rels`);53  return readFile(slideFilePath)54    .then((content) => {55      const $ = cheerio.load(content, { xmlMode: true });56      return [57        parseSlideWithScreenshot($, slideRelPath),58        parseActionName($),59        parseTarget($),60        parseDisplayItems()61      ];62    })63    .all()64    .then(([screenshot, action, target, displayItems]) =>65      ({ slide: Number(fileBaseName.substring(5)),66        screenshot,67        action,68        target,69        displayItems70      })71    )72    .catch((e) => {73      throw new ParserError(`Failed to parse file: ${fileBaseName}`, e.message);74    });...index.js
Source:index.js  
1import React, { useRef, useEffect } from 'react'2import styles from "./screenshot.module.css"3const Screenshot = ({ webPage, handleScreenshotClick, nodeInFocus }) => {4    const src = "data:image/png;base64," + webPage.screenshot;5    const screenshotRef = useRef(null)6    const canvasRef = useRef(null)7    useEffect(() => {8        const screenshotElement = screenshotRef.current9        const canvas = canvasRef.current10        const context = canvas.getContext('2d')11        // Set canvas height to match screenshot12        canvas.width = screenshotElement.width;13        canvas.height = screenshotElement.height;14        // Draw bounding box of node in focus on canvas15        if (nodeInFocus){16            const { coordinates } = nodeInFocus;17            // Node coordinates must be scaled down to fit screenshot18            const x = coordinates.left * (screenshotElement.width / webPage.viewportWidth);19            const width = coordinates.width * (screenshotElement.width / webPage.viewportWidth);20            const y = coordinates.top * (screenshotElement.height / webPage.viewportHeight);21            const height = coordinates.height * (screenshotElement.height / webPage.viewportHeight);22            // Draw bounding box of node on canvas23            context.fillStyle = "rgba(255, 165, 0, 0.5)"24            context.fillRect(x, y, width, height)25        }26    }, [webPage, nodeInFocus])27    return (28        <div className={styles.screenshotDiv}>29            <img ref={screenshotRef} src={src} alt="screenshot" className={styles.screenshotImg} onClick={handleScreenshotClick}/>30            <canvas ref={canvasRef} width={100} height={100} className={styles.screenshotCanvas}/>31        </div>32    )33}...screenshotElement.spec.js
Source:screenshotElement.spec.js  
1/// <reference types="Cypress" />2import {screenshotElement} from "../page_objects/screenshotElement"3var data = require("../fixtures/screenshotElement.json")4describe("Using filter input field", ()=> {5    before(()=> {6        cy.visit("/")7    })8    it("Clicking on the next button", ()=> {9        screenshotElement.buttonClickTwice()10    })11    it("Check if the properties for the picture are valid", ()=> {12        screenshotElement.sliderCSS(data.element.pixels)13        screenshotElement.sliderPicture(data.element.src)14    })15    it("Screenshot the container", ()=> {16        screenshotElement.containerScreenshot()17    })...Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.screenshot({ path: 'screenshot.png' });7  await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11  const browser = await chromium.launch();12  const context = await browser.newContext();13  const page = await context.newPage();14  await page.screenshotElement({ path: 'screenshot.png' });15  await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19  const browser = await chromium.launch();20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.screenshotElement({ path: 'screenshot.png' });23  await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27  const browser = await chromium.launch();28  const context = await browser.newContext();29  const page = await context.newPage();30  await page.screenshotElement({ path: 'screenshot.png' });31  await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35  const browser = await chromium.launch();36  const context = await browser.newContext();37  const page = await context.newPage();38  await page.screenshotElement({ path: 'screenshot.png' });39  await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43  const browser = await chromium.launch();44  const context = await browser.newContext();45  const page = await context.newPage();Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.screenshotElement('input[name="q"]');7  await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11  const browser = await chromium.launch();12  const context = await browser.newContext();13  const page = await context.newPage();14  await page.screenshotElement('input[name="q"]', { path: 'screenshot.png' });15  await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19  const browser = await chromium.launch();20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.screenshotElement('input[name="q"]', { path: 'screenshot.png', fullPage: true });23  await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27  const browser = await chromium.launch();28  const context = await browser.newContext();29  const page = await context.newPage();30  await page.screenshotElement('input[name="q"]', { path: 'screenshot.png', type: 'jpeg' });31  await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35  const browser = await chromium.launch();36  const context = await browser.newContext();37  const page = await context.newPage();38  await page.screenshotElement('input[name="q"]', { path: 'screenshot.png', quality: 50 });39  await browser.close();40})();41const { chromium }Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  for (const browserType of ['chromium', 'webkit', 'firefox']) {4    const browser = await playwright[browserType].launch();5    const context = await browser.newContext();6    const page = await context.newPage();7    await page.screenshot({ path: `example-${browserType}.png` });8    await browser.close();9  }10})();11const playwright = require('playwright');12(async () => {13  for (const browserType of ['chromium', 'webkit', 'firefox']) {14    const browser = await playwright[browserType].launch();15    const context = await browser.newContext();16    const page = await context.newPage();17    await page.screenshot({ path: `example-${browserType}.png` });18    await browser.close();19  }20})();21const playwright = require('playwright');22(async () => {23  for (const browserType of ['chromium', 'webkit', 'firefox']) {24    const browser = await playwright[browserType].launch();25    const context = await browser.newContext();26    const page = await context.newPage();27    await page.screenshot({ path: `example-${browserType}.png` });28    await browser.close();29  }30})();31const playwright = require('playwright');32(async () => {33  for (const browserType of ['chromium', 'webkit', 'firefox']) {34    const browser = await playwright[browserType].launch();35    const context = await browser.newContext();36    const page = await context.newPage();37    await page.screenshot({ path: `example-${browserType}.png` });38    await browser.close();39  }40})();41const playwright = require('playwright');42(async () => {43  for (const browserType of ['chromium', 'webkit', 'firefox']) {Using AI Code Generation
1const playwright = require('playwright');2(async () => {3  const browser = await playwright['chromium'].launch({ headless: false });4  const context = await browser.newContext();5  const page = await context.newPage();6  await page.screenshot({ path: 'example.png' });7  await browser.close();8})();9const playwright = require('playwright');10(async () => {11  const browser = await playwright['chromium'].launch({ headless: false });12  const context = await browser.newContext();13  const page = await context.newPage();14  await page.screenshotElement({ selector: 'body' });15  await browser.close();16})();17const playwright = require('playwright');18(async () => {19  const browser = await playwright['chromium'].launch({ headless: false });20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.screenshotElement({ selector: 'body', path: 'example.png' });23  await browser.close();24})();25const playwright = require('playwright');26(async () => {27  const browser = await playwright['chromium'].launch({ headless: false });28  const context = await browser.newContext();29  const page = await context.newPage();30  await page.screenshotElement({ selector: 'body', type: 'png' });31  await browser.close();32})();33const playwright = require('playwright');34(async () => {35  const browser = await playwright['chromium'].launch({ headless: false });36  const context = await browser.newContext();37  const page = await context.newPage();38  await page.screenshotElement({ selector: 'body', type: 'jpeg' });39  await browser.close();40})();41const playwright = require('playwright');42(async () => {43  const browser = await playwright['chromium'].launch({ headless: false });Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch();4  const page = await browser.newPage();5  await page.screenshotElement({ selector: 'body' });6  await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10  const browser = await chromium.launch();11  const page = await browser.newPage();12  await page.screenshotElement({ selector: 'body' });13  await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17  const browser = await chromium.launch();18  const page = await browser.newPage();19  await page.screenshotElement({ selector: 'body' });20  await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24  const browser = await chromium.launch();25  const page = await browser.newPage();26  await page.screenshotElement({ selector: 'body' });27  await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31  const browser = await chromium.launch();32  const page = await browser.newPage();33  await page.screenshotElement({ selector: 'body' });34  await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38  const browser = await chromium.launch();39  const page = await browser.newPage();40  await page.screenshotElement({ selector: 'body' });41  await browser.close();42})();Using AI Code Generation
1const { screenshotElement } = require('playwright/lib/server/screenshotter');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const page = await browser.newPage();6  const element = await page.$('header');7  const buffer = await screenshotElement(element);8  await browser.close();9})();10const { screenshotElement } = require('playwright/lib/server/screenshotter');11const { chromium } = require('playwright');12(async () => {13  const browser = await chromium.launch();14  const page = await browser.newPage();15  const element = await page.$('header');16  const buffer = await screenshotElement(element);17  await browser.close();18})();19const { screenshotElement } = require('playwright/lib/server/screenshotter');20const { chromium } = require('playwright');21(async () => {22  const browser = await chromium.launch();23  const page = await browser.newPage();24  const element = await page.$('header');25  const buffer = await screenshotElement(element);26  await browser.close();27})();28const { screenshotElement } = require('playwright/lib/server/screenshotter');29const { chromium } = require('playwright');30(async () => {31  const browser = await chromium.launch();32  const page = await browser.newPage();33  const element = await page.$('header');34  const buffer = await screenshotElement(element);35  await browser.close();36})();37const { screenshotElement } = require('playwright/lib/server/screenshotter');38const { chromium } = require('playwright');39(async () => {40  const browser = await chromium.launch();41  const page = await browser.newPage();42  const element = await page.$('header');43  const buffer = await screenshotElement(element);44  await browser.close();45})();Using AI Code Generation
1const { chromium } = require('playwright-internal');2(async () => {3  const browser = await chromium.launch({ headless: false });4  const page = await browser.newPage();5  await page.screenshotElement({ selector: 'body' });6  await browser.close();7})();8page.screenshot()9page.setDefaultTimeout(timeout)Using AI Code Generation
1const { chromium, devices } = require('playwright');2const fs = require('fs');3(async () => {4  const browser = await chromium.launch({headless: false});5  const context = await browser.newContext();6  const page = await context.newPage();7  const elementHandle = await page.$('text=Docs');8  const box = await elementHandle.boundingBox();9  const screenshot = await elementHandle.screenshot({ clip: box });10  fs.writeFileSync('element-screenshot.png', screenshot);11  await browser.close();12})();13Your name to display (optional):14Your name to display (optional):Using AI Code Generation
1const { chromium } = require('playwright');2const { screenshotElement } = require('playwright/lib/server/screenshotter/screenshotter');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await screenshotElement(page, {8  });9  await browser.close();10})();LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
