Best JavaScript code snippet using wpt
selectionhelper.ts
Source:selectionhelper.ts
1interface SelectionEx extends Selection {2 modify(alter: string, direction: string, granularity: string): void;3}4export interface SelectionInfo {5 selectionText: string;6 contextText: string;7 rect: DOMRect;8 selectionOffsetInContext: number;9 selectionLength: number;10}11export class SelectionHelper {12 constructor() {13 this.getSelection = this.getSelection.bind(this);14 this.extractContext = this.extractContext.bind(this);15 }16 getSelection(): SelectionInfo | null {17 const selection = window.getSelection();18 const selectionText = selection.toString().trim();19 if (selectionText.length == 0 || !this.isSourceLanguageText(selectionText)) {20 return null;21 }22 let rect = selection.getRangeAt(0).getBoundingClientRect();23 if (rect.height === rect.width && rect.width === 0 && this.isInputFieldElement(document.activeElement)) {24 const inputElement = document.activeElement as HTMLInputElement;25 rect = this.getTextBoundingRect(inputElement, inputElement.selectionStart, inputElement.selectionEnd, false);26 }27 const selectionContext = this.extractContext(selection);28 return {29 contextText: selectionContext[0],30 rect: this.offset(rect, window.pageXOffset, window.pageYOffset),31 selectionText: selectionText,32 selectionLength: selectionText.length,33 selectionOffsetInContext: selectionContext[1]34 }35 }36 offset(rect: DOMRect, xOffset: number, yOffset: number): DOMRect {37 return new DOMRect(rect.x + xOffset, rect.y + yOffset, rect.width, rect.height);38 }39 isSourceLanguageText(text: string): boolean {40 return (/^[a-zA-Z ]+$/.test(text));41 }42 extractContext(selection: Selection): [contextText: string, selectionOffset: number] {43 const selEx = selection as SelectionEx;44 const activeElement = document.activeElement;45 let toRestore: {46 type: "simple",47 range: Range48 } | {49 type: "input",50 selectionStart: number,51 selectionEnd: number,52 };53 if (this.isInputFieldElement(activeElement)) {54 const inputElement = activeElement as HTMLInputElement;55 toRestore = {56 type: "input",57 selectionStart: inputElement.selectionStart,58 selectionEnd: inputElement.selectionEnd59 }60 }61 else {62 toRestore = {63 type: "simple",64 range: selEx.getRangeAt(0).cloneRange()65 }66 }67 selEx.modify("move", "left", "sentence");68 selEx.modify("extend", "right", "sentence");69 const contextText = selEx.toString();70 const selectionStartPosition = toRestore.type == "simple"71 ? toRestore.range.startOffset - selEx.getRangeAt(0).startOffset72 : toRestore.selectionStart - (activeElement as HTMLInputElement).selectionStart;73 if (toRestore.type == "simple") {74 selEx.removeAllRanges();75 selEx.addRange(toRestore.range);76 }77 else {78 const inputElement = activeElement as HTMLInputElement;79 inputElement.setSelectionRange(toRestore.selectionStart, toRestore.selectionEnd);80 }81 return [contextText, selectionStartPosition];82 }83 isInputFieldElement(element: Element): boolean {84 const tagName = element.tagName?.toLowerCase();85 return tagName === "textarea"86 || tagName === "input" && (element as HTMLInputElement).type === "text";87 }88 listOfModifiers = ['direction', 'font-family', 'font-size', 'font-size-adjust', 'font-variant', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-align', 'text-indent', 'text-transform', 'word-wrap', 'word-spacing'];89 // https://stackoverflow.com/a/7948715/302935990 getTextBoundingRect(input: HTMLInputElement, selectionStart: number, selectionEnd: number, debug: boolean) : DOMRect {91 const offset = this.getInputOffset(input);92 let topPos = offset.top;93 let leftPos = offset.left;94 const width = this.getInputCSS(input, 'width', true);95 const height = this.getInputCSS(input, 'height', true);96 // Styles to simulate a node in an input field97 topPos += this.getInputCSS(input, 'padding-top', true);98 topPos += this.getInputCSS(input, 'border-top-width', true);99 leftPos += this.getInputCSS(input, 'padding-left', true);100 leftPos += this.getInputCSS(input, 'border-left-width', true);101 leftPos += 1; //Seems to be necessary102 let cssDefaultStyles = "white-space:pre;padding:0;margin:0;";103 for (var i = 0; i < this.listOfModifiers.length; i++) {104 var property = this.listOfModifiers[i];105 cssDefaultStyles += property + ':' + this.getInputCSS(input, property, false) + ';';106 }107 // End of CSS variable checks108 const text = input.value;109 const textLen = text.length;110 const fakeClone = document.createElement("div");111 if (selectionStart > 0) {112 this.appendPart(cssDefaultStyles, text, 0, selectionStart, fakeClone);113 }114 var fakeRange = this.appendPart(cssDefaultStyles, text, selectionStart, selectionEnd, fakeClone);115 if (textLen > selectionEnd) {116 this.appendPart(cssDefaultStyles, text, selectionEnd, textLen, fakeClone);117 }118 // Styles to inherit the font styles of the element119 fakeClone.style.cssText = cssDefaultStyles;120 // Styles to position the text node at the desired position121 fakeClone.style.position = "absolute";122 fakeClone.style.top = topPos + "px";123 fakeClone.style.left = leftPos + "px";124 fakeClone.style.width = width + "px";125 fakeClone.style.height = height + "px";126 document.body.appendChild(fakeClone);127 const returnValue = fakeRange.getBoundingClientRect(); //Get rect128 if (!debug) {129 fakeClone.parentNode.removeChild(fakeClone) //Remove temp130 };131 return returnValue;132 }133 getInputCSS(input: HTMLInputElement, prop: string, isnumber: true) : number;134 getInputCSS(input: HTMLInputElement, prop: string, isnumber: false) : string;135 getInputCSS(input: HTMLInputElement, prop: string, isnumber: boolean) : string | number {136 var val = document.defaultView.getComputedStyle(input, null).getPropertyValue(prop);137 return isnumber ? parseFloat(val) : val;138 }139 appendPart(cssDefaultStyles:string, text:string, start: number, end: number, fakeClone: HTMLDivElement): HTMLSpanElement {140 const span = document.createElement("span");141 span.style.cssText = cssDefaultStyles; //Force styles to prevent unexpected results142 span.textContent = text.substring(start, end);143 fakeClone.appendChild(span);144 return span;145 }146 getInputOffset(input: HTMLInputElement) : DOMRect {147 const body = document.body;148 const win = document.defaultView;149 const docElem = document.documentElement;150 const box = document.createElement('div');151 box.style.paddingLeft = box.style.width = "1px";152 body.appendChild(box);153 var isBoxModel = box.offsetWidth == 2;154 body.removeChild(box);155 const rect = input.getBoundingClientRect();156 const clientTop = docElem.clientTop || body.clientTop || 0;157 const clientLeft = docElem.clientLeft || body.clientLeft || 0;158 const scrollTop = win.pageYOffset || isBoxModel && docElem.scrollTop || body.scrollTop;159 const scrollLeft = win.pageXOffset || isBoxModel && docElem.scrollLeft || body.scrollLeft;160 return this.offset(rect, scrollLeft - clientLeft ,scrollTop - clientTop);161 }...
getTextBoundingRect.ts
Source:getTextBoundingRect.ts
1// @ts-ignore2// @author Rob W http://stackoverflow.com/users/938089/rob-w3// @name getTextBoundingRect4// @param input Required HTMLElement with `value` attribute5// @param selectionStart Optional number: Start offset. Default 06// @param selectionEnd Optional number: End offset. Default selectionStart7// @param debug Optional boolean. If true, the created test layer8// will not be removed.9export function getTextBoundingRect(10 input: HTMLInputElement,11 selectionStart?: number,12 selectionEnd?: number,13 debug?: boolean,14): DOMRect | void {15 // Basic parameter validation16 if (!input || !('value' in input)) return;17 if (typeof selectionStart == 'string') selectionStart = parseFloat(selectionStart);18 if (typeof selectionStart != 'number' || isNaN(selectionStart)) {19 selectionStart = 0;20 }21 if (selectionStart < 0) selectionStart = 0;22 else selectionStart = Math.min(input.value.length, selectionStart);23 if (typeof selectionEnd == 'string') selectionEnd = parseFloat(selectionEnd);24 if (typeof selectionEnd != 'number' || isNaN(selectionEnd) || selectionEnd < selectionStart) {25 selectionEnd = selectionStart;26 }27 if (selectionEnd < 0) selectionEnd = 0;28 else selectionEnd = Math.min(input.value.length, selectionEnd);29 // If available (thus IE), use the createTextRange method30 //@ts-expect-error31 if (typeof input.createTextRange == 'function') {32 //@ts-expect-error33 const range = input.createTextRange();34 range.collapse(true);35 range.moveStart('character', selectionStart);36 range.moveEnd('character', selectionEnd - selectionStart);37 return range.getBoundingClientRect();38 }39 // createTextRange is not supported, create a fake text range40 const offset = getInputOffset(),41 width = getInputCSS('width', true),42 height = getInputCSS('height', true);43 let topPos = offset.top,44 leftPos = offset.left;45 // Styles to simulate a node in an input field46 // use pre-wrap instead of wrap for white-space to support wrapping in textareas47 let cssDefaultStyles = 'white-space:pre-wrap;padding:0;margin:0;';48 const listOfModifiers = [49 'direction',50 'font-family',51 'font-size',52 'font-size-adjust',53 'font-constiant',54 'font-weight',55 'font-style',56 'letter-spacing',57 'line-height',58 'text-align',59 'text-indent',60 'text-transform',61 'word-wrap',62 'word-spacing',63 ];64 topPos += Number(getInputCSS('padding-top', true));65 topPos += Number(getInputCSS('border-top-width', true));66 leftPos += Number(getInputCSS('padding-left', true));67 leftPos += Number(getInputCSS('border-left-width', true));68 leftPos += 1; //Seems to be necessary69 for (let i = 0; i < listOfModifiers.length; i++) {70 const property = listOfModifiers[i];71 cssDefaultStyles += property + ':' + String(getInputCSS(property)) + ';';72 }73 // End of CSS constiable checks74 const text = input.value,75 textLen = text.length,76 fakeClone = document.createElement('div');77 if (selectionStart > 0) appendPart(0, selectionStart);78 const fakeRange = appendPart(selectionStart, selectionEnd);79 if (textLen > selectionEnd) appendPart(selectionEnd, textLen);80 // Styles to inherit the font styles of the element81 fakeClone.style.cssText = cssDefaultStyles;82 // Styles to position the text node at the desired position83 fakeClone.style.position = 'absolute';84 fakeClone.style.top = topPos + 'px';85 fakeClone.style.left = leftPos + 'px';86 fakeClone.style.width = width + 'px';87 fakeClone.style.height = height + 'px';88 document.body.appendChild(fakeClone);89 const returnValue = fakeRange.getBoundingClientRect(); //Get rect90 if (!debug) fakeClone.parentNode?.removeChild(fakeClone); //Remove temp91 return returnValue;92 // Local functions for readability of the previous code93 function appendPart(start, end) {94 const span = document.createElement('span');95 let tmpText = text.substring(start, end);96 span.style.cssText = cssDefaultStyles; //Force styles to prevent unexpected results97 // add a space if it ends in a newline98 if (/[\n\r]$/.test(tmpText)) {99 tmpText += ' ';100 }101 span.textContent = tmpText;102 fakeClone.appendChild(span);103 return span;104 }105 // Computing offset position106 function getInputOffset() {107 const body = document.body,108 win = document.defaultView,109 docElem = document.documentElement,110 box = document.createElement('div');111 box.style.paddingLeft = box.style.width = '1px';112 body.appendChild(box);113 const isBoxModel = box.offsetWidth == 2;114 body.removeChild(box);115 const bufferBox: DOMRect = input.getBoundingClientRect();116 const clientTop = docElem.clientTop || body.clientTop || 0,117 clientLeft = docElem.clientLeft || body.clientLeft || 0,118 scrollTop = win?.pageYOffset || (isBoxModel && docElem.scrollTop) || body.scrollTop,119 scrollLeft = win?.pageXOffset || (isBoxModel && docElem.scrollLeft) || body.scrollLeft;120 return {121 top: bufferBox.top + scrollTop - clientTop,122 left: bufferBox.left + scrollLeft - clientLeft,123 };124 }125 function getInputCSS(prop, isnumber = false) {126 const val = document.defaultView?.getComputedStyle(input, null).getPropertyValue(prop);127 return isnumber ? parseFloat(val ?? '0') : val;128 }...
caret.js
Source:caret.js
1// @author Rob W http://stackoverflow.com/users/938089/rob-w2// @name getTextBoundingRect3// @param input Required HTMLElement with `value` attribute4// @param selectionStart Optional number: Start offset. Default 05// @param selectionEnd Optional number: End offset. Default selectionStart6// @param debug Optional boolean. If true, the created test layer7// will not be removed.8define(function() {9 var exports = {};10 exports.getTextBoundingRect = function(input, selectionStart, selectionEnd, debug) {11 // Basic parameter validation12 if(!input || !('value' in input)) return input;13 if(typeof selectionStart == "string") selectionStart = parseFloat(selectionStart);14 if(typeof selectionStart != "number" || isNaN(selectionStart)) {15 selectionStart = 0;16 }17 if(selectionStart < 0) selectionStart = 0;18 else selectionStart = Math.min(input.value.length, selectionStart);19 if(typeof selectionEnd == "string") selectionEnd = parseFloat(selectionEnd);20 if(typeof selectionEnd != "number" || isNaN(selectionEnd) || selectionEnd < selectionStart) {21 selectionEnd = selectionStart;22 }23 if (selectionEnd < 0) selectionEnd = 0;24 else selectionEnd = Math.min(input.value.length, selectionEnd);25 // If available (thus IE), use the createTextRange method26 if (typeof input.createTextRange == "function") {27 var range = input.createTextRange();28 range.collapse(true);29 range.moveStart('character', selectionStart);30 range.moveEnd('character', selectionEnd - selectionStart);31 return range.getBoundingClientRect();32 }33 // createTextRange is not supported, create a fake text range34 var offset = getInputOffset(),35 topPos = offset.top,36 leftPos = offset.left,37 width = getInputCSS('width', true),38 height = getInputCSS('height', true);39 // Styles to simulate a node in an input field40 var cssDefaultStyles = "white-space:pre;padding:0;margin:0;",41 listOfModifiers = ['direction', 'font-family', 'font-size', 'font-size-adjust', 'font-variant', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-align', 'text-indent', 'text-transform', 'word-wrap', 'word-spacing'];42 topPos += getInputCSS('padding-top', true);43 topPos += getInputCSS('border-top-width', true);44 leftPos += getInputCSS('padding-left', true);45 leftPos += getInputCSS('border-left-width', true);46 leftPos += 1; //Seems to be necessary47 for (var i=0; i<listOfModifiers.length; i++) {48 var property = listOfModifiers[i];49 cssDefaultStyles += property + ':' + getInputCSS(property) +';';50 }51 // End of CSS variable checks52 var text = input.value,53 textLen = text.length,54 fakeClone = document.createElement("div");55 if(selectionStart > 0) appendPart(0, selectionStart);56 var fakeRange = appendPart(selectionStart, selectionEnd);57 if(textLen > selectionEnd) appendPart(selectionEnd, textLen);58 // Styles to inherit the font styles of the element59 fakeClone.style.cssText = cssDefaultStyles;60 // Styles to position the text node at the desired position61 fakeClone.style.position = "absolute";62 fakeClone.style.top = topPos + "px";63 fakeClone.style.left = leftPos + "px";64 fakeClone.style.width = width + "px";65 fakeClone.style.height = height + "px";66 document.body.appendChild(fakeClone);67 var returnValue = fakeRange.getBoundingClientRect(); //Get rect68 if (!debug) fakeClone.parentNode.removeChild(fakeClone); //Remove temp69 return returnValue;70 // Local functions for readability of the previous code71 function appendPart(start, end){72 var span = document.createElement("span");73 span.style.cssText = cssDefaultStyles; //Force styles to prevent unexpected results74 span.textContent = text.substring(start, end);75 fakeClone.appendChild(span);76 return span;77 }78 // Computing offset position79 function getInputOffset(){80 var body = document.body,81 win = document.defaultView,82 docElem = document.documentElement,83 box = document.createElement('div');84 box.style.paddingLeft = box.style.width = "1px";85 body.appendChild(box);86 var isBoxModel = box.offsetWidth == 2;87 body.removeChild(box);88 box = input.getBoundingClientRect();89 var clientTop = docElem.clientTop || body.clientTop || 0,90 clientLeft = docElem.clientLeft || body.clientLeft || 0,91 scrollTop = win.pageYOffset || isBoxModel && docElem.scrollTop || body.scrollTop,92 scrollLeft = win.pageXOffset || isBoxModel && docElem.scrollLeft || body.scrollLeft;93 return {94 top : box.top + scrollTop - clientTop,95 left: box.left + scrollLeft - clientLeft};96 }97 function getInputCSS(prop, isnumber){98 var val = document.defaultView.getComputedStyle(input, null).getPropertyValue(prop);99 return isnumber ? parseFloat(val) : val;100 }101 }102 return exports;...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7var wpt = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org');9}, function(err, data) {10 if (err) return console.error(err);11 console.log(data);12});13var wpt = require('webpagetest');14var wpt = new WebPageTest('www.webpagetest.org');15}, function(err, data) {16 if (err) return console.error(err);17 console.log(data);18});19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org');21}, function(err, data) {22 if (err) return console.error(err);23 console.log(data);24});25var wpt = require('
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9 if (err) {10 console.log(err);11 } else {12 console.log(data);13 }14});15var wpt = require('webpagetest');16var wpt = new WebPageTest('www.webpagetest.org');17 if (err) {18 console.log(err);19 } else {20 console.log(data);21 }22});23 if (err) {24 console.log(err);25 } else {26 console.log(data);27 }28});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 return console.log(err);5 }6 console.log(data);7 wpt.fakeClone(data.data.testId, function(err, data) {8 if (err) {9 return console.log(err);10 }11 console.log(data);12 });13});14{ statusCode: 200,
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7var wpt = require('wpt');8var wpt = new WebPageTest('www.webpagetest.org');9wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {10 if (err) return console.error(err);11 console.log(data);12});13var wpt = require('wpt');14var wpt = new WebPageTest('www.webpagetest.org');15wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {16 if (err) return console.error(err);17 console.log(data);18});19var wpt = require('wpt');20var wpt = new WebPageTest('www.webpagetest.org');21wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {22 if (err) return console.error(err);23 console.log(data);24});25var wpt = require('wpt');26var wpt = new WebPageTest('www.webpagetest.org');27wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {28 if (err) return console.error(err);29 console.log(data);30});31var wpt = require('wpt');32var wpt = new WebPageTest('www.webpagetest.org');33wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {34 if (err) return console.error(err);35 console.log(data);36});37var wpt = require('wpt');38var wpt = new WebPageTest('www.webpagetest.org');39wpt.runTest('www.webpagetest.org', {f: 'json'}, function(err, data) {
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.6f3e7a3c6e3d7f9e6b7f7a3c6e3d7f9e');3var options = {4 lighthouseConfig: {5 settings: {6 throttling: {7 },8 },9 },10};11wpt.runTest(options, function(err, data) {12 if (err) return console.error(err);13 console.log('Test ID: %s', data.data.testId);14 wpt.getTestResults(data.data.testId, function(err, data) {15 if (err) return console.error(err);16 console.log('Test status: %s', data.statusText);17 console.log('First View: %s', data.data.average.firstView);18 console.log('First View Speed Index: %s', data.data.average.firstView.SpeedIndex);19 });20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org', 'A.6f3e7a3c6e3d7f9e6b7f7a3c6e3d7f9e');23var options = {24 lighthouseConfig: {
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!!