How to use visitNames method in Playwright Internal

Best JavaScript code snippet using playwright-internal

main.js

Source:main.js Github

copy

Full Screen

1import {OrbitControls} from 'https://unpkg.com/three@0.108.0/examples/jsm/controls/OrbitControls.js';2import { CSS2DRenderer, CSS2DObject } from 'https://unpkg.com/three@0.108.0/examples/jsm/renderers/CSS2DRenderer.js';3import {TWEEN} from 'https://unpkg.com/three@0.108.0/examples/jsm/libs/tween.module.min';4import 'https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js'5const urlParams = new URLSearchParams(window.location.search);6const GLOBE_STYLE_TEXTURE = "texture";7const GLOBE_STYLE_POLYGON = "polygon";8const GLOBE_STYLE = (urlParams.has('style') ? urlParams.get('style') : GLOBE_STYLE_TEXTURE);9function loadJSON(url, callback) {10 var request = new XMLHttpRequest;11 request.open('GET', url, true);12 request.onload = function() {13 if (request.status >= 200 && request.status < 400){14 // Success!15 var data = JSON.parse(request.responseText);16 callback(data);17 } else {18 console.log("Status code error: " + request.status);19 }20 };21 request.onerror = function() {22 console.log("Error connecting."); 23 };24 request.send();25}26(function() {27 Vue.component('poi', {28 props: {29 text: String,30 id: String,31 },32 template: `<a class="poi" href='#' v-on:click="handleClick"><img :src="icon[0]" :title="icon[1]" :alt="icon[1]" style="width: 1em; display: inline; margin-right: 2px; position: relative; vertical-align: middle;"></img>{{text}}</a>`,33 methods: {34 handleClick() {35 renderInfoForPOI(this.id);36 }37 },38 computed: {39 icon: function() {40 // TODO(iandioch): It's dumb to get this point instead of just having a getVisitForID(this.id) func.41 const visit = getPointForName(this.id).visit;42 if (visit.location.type == 'TOWN' || visit.location.type == "TOWN_CLUSTER") {43 return ['town.svg', 'Town by mapbox on svgrepo.com'];44 } else if (visit.location.type == "STATION") {45 return ['station.svg', 'Railway Station 14 by gmgeo on svgrepo.com'];46 } else if (visit.location.type == "AIRPORT") {47 return ['airport.svg', 'Airplane Plane by SVG Repo on svgrepo.com'];48 }49 return ['town.svg', 'TODO'];50 }51 }52 });53 Vue.component('country', {54 props: {55 text: String,56 id: String,57 },58 template: `<a class="poi" href='#' v-on:click="handleClick"><span v-if="flag">{{flag}} </span>{{text}}</a>`,59 methods: {60 handleClick() {61 renderInfoForCountry(this.text);62 },63 flagEmojiForCountryCode(countryCode) {64 const codePoints = countryCode.toUpperCase().split('').map(c => 127397 + c.charCodeAt());65 return String.fromCodePoint(...codePoints);66 }67 },68 computed: {69 flag: function() {70 if (this.id.length != 2) {71 // Only the three regional flags of [Scotland, Wales, England] are recommended for general interchange by the Unicode consortium.72 switch(this.id) {73 case 'GBSCT': return '🏴󠁧󠁢󠁳󠁣󠁴󠁿';74 case 'GBWLS': return '🏴󠁧󠁢󠁷󠁬󠁳󠁿';75 case 'GBENG': return '🏴󠁧󠁢󠁥󠁮󠁧󠁿';76 default: return null;77 }78 }79 return this.flagEmojiForCountryCode(this.id);80 },81 }82 });83 Vue.component('region', {84 props: {85 country: String, // name of country86 name: String, // name of region87 },88 template: `<a class="poi" href='#' v-on:click="handleClick"><img src="region.svg" title="Location by SVG Repo on svgrepo.com" style="width: 1em; display: inline; margin-right: 2px; position: relative; vertical-align: middle"></img>{{name}}</a>`,89 methods: {90 handleClick() {91 renderInfoForRegion(this.country, this.name);92 },93 }94 });95 Vue.component('collection', {96 props: {97 collection: Object,98 },99 template: `<a class="poi" href='#' v-on:click="handleClick">{{collection.title}}</a>`,100 methods: {101 handleClick() {102 renderInfoForCollection(this.collection);103 },104 }105 });106 Vue.component('top-poi-table', {107 props: {108 pois: Array, // Expecting a list of (user-visible text, poi id/name, number)109 metric: String110 },111 template: `112 <ul class="top-poi-table">113 <li v-for="poi in pois">114 <poi :text="poi[0]" :id="poi[1]"></poi> <span class="fact">{{poi[2]}}</span> {{metric}}115 </li>116 </ul>`117 });118 // TODO(iandioch): It might be easier to have separate components for clusters vs. individual POIs, instead of wrapping everything in ifs.119 Vue.component('poi-visit-dashboard', {120 props: {121 visits: Array, // One (or more, if poi is a cluster) visit objs. 122 poi: Object, // a single visitObj123 },124 template: `<div>125 <div class="poi-list">126 <p v-if="visits.length > 1">This cluster is composed of multiple adjacent places:<br><span v-for="poi in visits"><poi :text="poi.location.human_readable_name" :id="poi.location.id"></poi> </span><br>in <span v-for="country in countries"><country :id="country.code" :text="country.name"></country></span></p>127 <p v-if="poi.location.type != 'CLUSTER'"><poi :text="poi.location.human_readable_name" :id="poi.location.id"></poi> is {{humanReadableType}} in <region :name="regions[0].name" :country="regions[0].country"></region> in <country :id="countries[0].code" :text="countries[0].name"></country></p>128 <p v-if="poi.hasOwnProperty('cluster')">This is a part of <poi text="a cluster" :id="poi.cluster"></poi></p>129 <p><span v-for="region in regions"><region :name="region.name" :country="region.country"></region></span></p>130 </div>131 <p>Number of visits: {{poi.num_visits}}</p>132 <p>Total time visited: {{poi.days > 0 ? poi.days + " days": poi.hours + " hours"}}.</p>133 </div>`,134 computed: {135 countries: function() {136 var seenCountries = new Set();137 var results = [];138 for (let i in this.visits) {139 const visit = this.visits[i];140 if (seenCountries.has(visit.location.country)) continue;141 seenCountries.add(visit.location.country);142 results.push({143 name: visit.location.country, 144 code: visit.location.country_code145 });146 }147 return results;148 },149 regions: function() {150 // seenRegions will conflict if two regions have the same name but are in different countries.151 var seenRegions = new Set();152 var results = [];153 for (let i in this.visits) {154 const visit = this.visits[i];155 if (seenRegions.has(visit.location.region)) continue;156 seenRegions.add(visit.location.region);157 results.push({158 name: visit.location.region, 159 country: visit.location.country,160 });161 }162 return results;163 },164 humanReadableType: function() {165 switch(this.poi.location.type) {166 case "CLUSTER":167 return "a cluster";168 case "TOWN":169 case "TOWN_CLUSTER":170 return "a locality";171 case "AIRPORT":172 return "an airport";173 case "STATION":174 return "a station";175 default:176 return "a place";177 }178 }179 }180 });181 Vue.component('poi-collection-dashboard', {182 props: {183 visits: Array // A list of [human_readable_name, id] pairs of places184 },185 template:`<div>186 <div class="poi-list">187 <span v-for="poi in visits"><poi :text="poi[0]" :id="poi[1]"></poi></span>188 <p>Stayed in these places for {{hours}} hours ({{days}} days) total.</p>189 </div>190 </div>`,191 computed: {192 hours: function() {193 var hours = 0;194 for (let i in this.visits) {195 let visit = visits[this.visits[i][1]];196 hours += visit.hours;197 }198 return hours;199 },200 days: function() {201 return Math.ceil(this.hours / 24.0);202 }203 }204 });205 Vue.component('home-dashboard', {206 props: ['legs', 'visits'],207 template: `<div>208 Logged <span class="fact">{{statistics.num_legs}}</span> trips to <span class="fact">{{statistics.num_unique_pois}}</span> different places in <span class="fact">{{statistics.num_countries}}</span> countries.<br>209 Places I have spent the most time in since I started logging:210 <top-poi-table v-bind:pois="longestStayedPOIs" metric="days"></top-poi-table>211 <br>212 I have logged trips passing through the following countries: <span v-for="country in countries"><country :id="country.code" :text="country.name"></country></span>213 <br>214 See more info about: <collection v-for="collection in collections" :collection="collection"></collection>.215 </div>`,216 computed: {217 longestStayedPOIs() {218 const allPOIs = [];219 for (let i in visits) {220 if (visits[i].location.type == "CLUSTER") continue;221 allPOIs.push([visits[i].location.human_readable_name, visits[i].location.id, visits[i].days]);222 }223 allPOIs.sort(function(a, b) { return b[2]-a[2]; });224 console.log(allPOIs.slice(0, 10));225 return allPOIs.slice(0, 10);226 },227 statistics() {228 const POINames = new Set();229 for (let i in visits) {230 if (visits[i].type == 'CLUSTER') continue;231 POINames.add(visits[i].location.id);232 }233 const numUniquePOIs = POINames.size;234 var numLegs = 0;235 for (let i in legs) {236 numLegs += legs[i].count;237 }238 const countries = new Set();239 for (let i in visits) {240 if (visits[i].type == 'CLUSTER') continue;241 countries.add(visits[i].location.country);242 }243 const numCountries = countries.size;244 return {245 "num_unique_pois": numUniquePOIs,246 "num_legs": numLegs,247 "num_countries": numCountries,248 }249 },250 countries: function() {251 var seenCountries = new Set();252 var results = [];253 for (let i in visits) {254 const visit = visits[i];255 const countryCode = visit.location.country_code;256 const countryName = visit.location.country;257 if (seenCountries.has(countryName)) continue;258 seenCountries.add(countryName);259 results.push({260 name: countryName, 261 code: countryCode,262 });263 }264 results.sort((a, b) => {return a.name.localeCompare(b.name)});265 return results;266 },267 collections: function() {268 return collections;269 }270 }271 });272 function createComponentForPOI(point, locations) {273 return {274 data: () => {275 return {276 visits: locations,277 poi: point.visit,278 }279 },280 template: `<poi-visit-dashboard v-bind:visits="visits" v-bind:poi="poi"></poi-visit-dashboard>`,281 }282 }283 function getVisitsForCountry(country) {284 var locations = [];285 for (let i in visits) {286 if (visits[i].location.type == 'CLUSTER') continue;287 if (visits[i].location.country == country) {288 locations.push(visits[i]);289 }290 }291 locations.sort((a, b) => { return b.days - a.days });292 return locations;293 }294 function createComponentForVisits(visits) {295 var locations = [];296 for (let i in visits) {297 locations.push([visits[i].location.human_readable_name, visits[i].location.id]);298 }299 return {300 data: () => {301 return {302 visits: locations,303 }304 },305 template: `<poi-collection-dashboard v-bind:visits="visits"></poi-collection-dashboard>`,306 }307 }308 function createComponentForCollection(collection) {309 var locations = [];310 for (let location of getLocationsForCollection(collection)) {311 locations.push([location.location.human_readable_name, location.location.id]);312 }313 return {314 data: () => {315 return {316 collection,317 visits: locations,318 }319 },320 template: `<div>321 <p>Total distance travelled: <span class="fact">{{collection.meta.distance}}km</span></p>322 <div v-for="part in collection.parts" stlye="margin-top: 1rem">323 <div v-if="partType(part) == 'NOTE'">324 {{part.note}}325 </div>326 <div v-if="partType(part) == 'LEG'">327 <component :is="renderLeg(part)"></component>328 </div>329 <div v-if="partType(part) == 'IMAGE'">330 <img :src="part.image_url" style="max-width:100%;"></img>331 </div>332 </div>333 </div>`,334 methods: {335 partType: function(part) {336 if (part.note && part.note.length) {337 return 'NOTE';338 }339 if (part.image_url && part.image_url.length) {340 return 'IMAGE';341 }342 return 'LEG';343 },344 modeVerb: function(mode) {345 switch(mode) {346 case 'AEROPLANE':347 return 'Flew';348 case 'CAR':349 return 'Drove';350 case 'TRAIN':351 return 'Took a train';352 case 'BUS':353 return 'Took a bus';354 case 'TAXI':355 return 'Took a taxi';356 case 'BOAT':357 return 'Took a boat';358 default:359 console.log("No verb specified for mode", mode);360 return 'Travelled';361 }362 },363 formatDatetime: function(datetime) {364 const date = new Date();365 date.setTime(Date.parse(datetime));366 return date.toLocaleString("en-IE");367 },368 renderLeg(part) {369 return {370 data: function() {371 return {372 part,373 }374 },375 template: `<div class="leg-description">376 ${this.modeVerb(part.leg.mode)} ${part.distance}km from <poi :text="part.dep.human_readable_name" :id="part.dep.id"></poi> (${this.formatDatetime(part.leg.departure_datetime)}) to <poi :text="part.arr.human_readable_name" :id="part.arr.id"></poi> (${this.formatDatetime(part.leg.arrival_datetime)}).377 </div>`378 }379 },380 },381 }382 }383 var dashboard = new Vue({384 el: '#vue-dashboard',385 data: {386 activeDashboard: {387 template: '<div>Loading...</div>',388 },389 legs: [],390 visits: [],391 collections: [],392 title: "Loading",393 hideBackButton: true,394 },395 methods: {396 loadData: function(data) {397 console.log("Loading data in homeDashboard.");398 console.log(data);399 this.legs.push(...data.legs);400 this.visits.push(...data.visits);401 this.collections.push(...data.collections);402 this.renderHome();403 },404 renderHome: function() {405 this.activeDashboard = "home-dashboard";406 this.title = "Travel globe";407 this.hideBackButton = true;408 const allVisits = [];409 for (let i in this.visits) {410 allVisits.push(this.visits[i].location.id);411 }412 toggleRoutesForSelectedVisits(allVisits, true);413 },414 renderPOI: function(point, locations) {415 this.activeDashboard = createComponentForPOI(point, locations);416 this.title = point.visit.location.human_readable_name;417 this.hideBackButton = false;418 },419 renderCountry: function(country, visits) {420 this.activeDashboard = createComponentForVisits(visits);421 this.title = country;422 this.hideBackButton = false;423 },424 renderCollection: function(collection) {425 this.activeDashboard = createComponentForCollection(collection);426 this.title = collection.title;427 this.hideBackButton = false;428 }429 }430 });431 const GLOBE_RADIUS = 1;432 const GLOBE_TEXTURE_PATH = 'scaled_globe_10800.jpg'433 const canvas = document.querySelector('#globe-canvas');434 const canvasContainer = document.querySelector('#globe-container');435 const renderer = new THREE.WebGLRenderer({canvas, antialias: false});436 const labelRenderer = new CSS2DRenderer();437 labelRenderer.setSize(canvas.width, canvas.height);438 labelRenderer.domElement.style.position = 'absolute';439 labelRenderer.domElement.style.top = '0px';440 canvasContainer.appendChild(labelRenderer.domElement);441 const camera = new THREE.PerspectiveCamera(45, 2, 0.025, 12);442 camera.position.z = 2;443 const controls = new OrbitControls(camera, labelRenderer.domElement);444 const MIN_CAMERA_DISTANCE = GLOBE_RADIUS * 1.05;445 const MAX_CAMERA_DISTANCE = GLOBE_RADIUS * 5;446 controls.minDistance = MIN_CAMERA_DISTANCE;447 controls.maxDistance = MAX_CAMERA_DISTANCE;448 controls.enablePan = false;449 controls.enableDamping = true;450 // Increase this number to make the scrolling snappier.451 controls.dampingFactor = 0.075;452 controls.rotateSpeed = 0.85;453 controls.zoomSpeed = 0.7;454 const scene = new THREE.Scene();455 var raycaster = new THREE.Raycaster(); 456 var mouse = new THREE.Vector2();457 const topLayer = labelRenderer.domElement;458 topLayer.addEventListener('mousemove', onMouseMove, false);459 topLayer.addEventListener('touchmove', onMouseMove, false);460 topLayer.addEventListener('mousedown', onMouseDown, false);461 topLayer.addEventListener('touchstart', onMouseDown, false);462 {463 const MAX_STAR_DIST = GLOBE_RADIUS * 10;464 const MIN_DIST = GLOBE_RADIUS*5;465 function randomStarPosition() {466 while (true) { 467 const x = Math.random() * MAX_STAR_DIST - MAX_STAR_DIST/2.0;468 const y = Math.random() * MAX_STAR_DIST - MAX_STAR_DIST/2.0;469 const z = Math.random() * MAX_STAR_DIST - MAX_STAR_DIST/2.0;470 if (x*x + y*y + z*z > MIN_DIST*MIN_DIST) {471 return new THREE.Vector3(x, y, z);472 }473 }474 }475 const NUM_STARS = 100;476 const starGeom = new THREE.Geometry();477 for (let i = 0; i < NUM_STARS; i++) {478 let star = randomStarPosition();479 starGeom.vertices.push(star);480 }481 const material = new THREE.PointsMaterial({color: 0xFFFFFF, size: 0.1});482 const points = new THREE.Points(starGeom, material);483 scene.add(points);484 }485 { 486 const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.8);487 scene.add(ambientLight);488 const directionalLight = new THREE.DirectionalLight(0xF9D78C, 0.2);489 directionalLight.position.set(-1, 2, 4);490 scene.add(directionalLight);491 }492 const globeGroup = new THREE.Group();493 scene.add(globeGroup);494 const pointGroup = new THREE.Group();495 globeGroup.add(pointGroup);496 function createGlobe(cb) {497 // Create the sphere obj.498 const globeGeometry = new THREE.SphereGeometry(GLOBE_RADIUS*0.995, 64, 64);499 if (GLOBE_STYLE === GLOBE_STYLE_TEXTURE) {500 const textureLoader = new THREE.TextureLoader();501 textureLoader.load(GLOBE_TEXTURE_PATH, (texture) => {502 texture.offset.set(0.25, 0.0);503 texture.wrapS = THREE.RepeatWrapping;504 texture.anisotropy = renderer.getMaxAnisotropy();505 texture.magFilter = THREE.NearestFilter;506 const globeGeometry = new THREE.SphereGeometry(GLOBE_RADIUS, 128, 128);507 const globeMaterial = new THREE.MeshPhongMaterial({ map: texture });508 globeMaterial.map.minFilter = THREE.LinearFilter;509 const globe = new THREE.Mesh(globeGeometry, globeMaterial);510 cb(globeGeometry, globe);511 });512 } else if (GLOBE_STYLE === GLOBE_STYLE_POLYGON) {513 const waterMaterial = new THREE.MeshBasicMaterial({ color: 0x3D6F95});514 const globeObjGroup = new THREE.Group();515 const globe = new THREE.Mesh(globeGeometry, waterMaterial);516 globeObjGroup.add(globe);517 const landMaterial = new THREE.MeshBasicMaterial({518 color: 0xb2bf9d,519 side: THREE.FrontSide, shininess: 0520 });521 const fineness = 2; // The smaller this number, the worse the performance. However, if this number is big, the ConicPolygonGeometry will have parts in the middle where it sags below the globe size.522 loadJSON('/globe/countries.json', (data) => {523 const countryGroup = new THREE.Group();524 globeObjGroup.add(countryGroup);525 data.features.forEach(({properties, geometry}) => {526 const polygons = geometry.type === 'Polygon' ? [geometry.coordinates] : geometry.coordinates;527 polygons.forEach(coords => {528 const mesh = new THREE.Mesh(new THREE.ConicPolygonGeometry(coords, GLOBE_RADIUS*0.9, GLOBE_RADIUS, false, true, false, fineness), landMaterial);529 countryGroup.add(mesh);530 });531 });532 cb(globeGeometry, globeObjGroup);533 });534 } else {535 alert("Invalid globe style " + GLOBE_STYLE);536 }537 }538 createGlobe((globeGeometry, group) => {539 const atmosphereShader = {540 uniforms: {},541 vertexShader: `542 varying vec3 v_normal;543 void main() {544 v_normal = normalize(normalMatrix * normal);545 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);546 }547 `,548 fragmentShader: `549 varying vec3 v_normal;550 void main() {551 vec3 colour = vec3(0.6, 0.8, 1.0);552 float intensity = pow(0.5 - dot(v_normal, vec3(0.0, 0.0, 1.0)), 2.0);553 gl_FragColor = vec4(colour, 1.0) * intensity;554 }555 `,556 }557 const atmosphereMaterial = new THREE.ShaderMaterial({558 uniforms: atmosphereShader.uniforms,559 vertexShader: atmosphereShader.vertexShader,560 fragmentShader: atmosphereShader.fragmentShader,561 side: THREE.BackSide,562 blending: THREE.AdditiveBlending,563 transparent: true,564 });565 const atmosphereMesh = new THREE.Mesh(globeGeometry, atmosphereMaterial);566 atmosphereMesh.scale.set(1.3, 1.3, 1.3);567 globeGroup.add(atmosphereMesh);568 globeGroup.add(group);569 });570 const arcGroup = new THREE.Group();571 globeGroup.add(arcGroup);572 // Convert decimal LatLng to ECEF573 function latLngToVector(lat, lng, altitude = null) {574 // Y = 1 at north pole,575 // Y = -1 at south pole,576 const latRadians = lat * Math.PI / 180.0;577 const lngRadians = lng * Math.PI / 180.0;578 const vector = new THREE.Vector3();579 var N = GLOBE_RADIUS;580 if (altitude !== null) N = altitude;581 vector.x = N * Math.cos(latRadians) * Math.sin(lngRadians);582 vector.y = N * Math.sin(latRadians);583 vector.z = N * Math.cos(latRadians) * Math.cos(lngRadians);584 return vector;585 }586 function latLngMidpoint(lat1, lng1, lat2, lng2) {587 // Following https://stackoverflow.com/a/4656937588 var dLng = (lng2 - lng1) * Math.PI / 180.0;589 //convert to radians590 var lat1 = (lat1) * Math.PI / 180.0;591 var lat2 = (lat2) * Math.PI / 180.0;592 var lng1 = (lng1) * Math.PI / 180.0;593 var Bx = Math.cos(lat2) * Math.cos(dLng);594 var By = Math.cos(lat2) * Math.sin(dLng);595 var lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));596 var lng3 = lng1 + Math.atan2(By, Math.cos(lat1) + Bx);597 return [(lat3) * 180.0 / Math.PI, (lng3) * 180.0 / Math.PI];598 }599 function mapToRange(inputLo, inputHi, outputLo, outputHi, input) {600 const slope = (outputHi - outputLo) / (inputHi - inputLo);601 return outputLo + slope * (input - inputLo);602 }603 // Returns distance in KM between given pair of points, as the crow flies.604 // Results are not exact, possibly because of assumption the earth is a sphere.605 // Examples: Munich -> Zurich is 242km.606 function latLngDistance(lat1, lng1, lat2, lng2) {607 // From https://stackoverflow.com/q/18883601608 const R = 6371; // Earth radius in km.609 const dLat = (lat2-lat1) * Math.PI / 180.0;610 const dLng = (lng2-lng1) * Math.PI / 180.0;611 const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos((lat1) * Math.PI / 180.0) * Math.cos((lat2) * Math.PI / 180.0) * Math.sin(dLng/2) * Math.sin(dLng/2); 612 const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));613 const d = R*c;614 return d;615 }616 function drawSurfaceArc(start, end, smoothness, width, colour) {617 // Following https://stackoverflow.com/a/42721392618 var cb = new THREE.Vector3();619 var ab = new THREE.Vector3();620 var normal = new THREE.Vector3();621 cb.subVectors(new THREE.Vector3(), end);622 ab.subVectors(start, end);623 cb.cross(ab);624 normal.copy(cb).normalize();625 var angle = start.angleTo(end);626 var angleDelta = angle/(smoothness-1);627 var geom = new THREE.Geometry();628 for (var i = 0; i < smoothness; i++) {629 geom.vertices.push(start.clone().applyAxisAngle(normal, angleDelta*i));630 }631 var arc = new THREE.Line(geom, new THREE.LineBasicMaterial({color: colour, linewidth: width}));632 globeGroup.add(arc);633 }634 // [start, controlPoint, end] should all be Vector3.635 function drawRaisedArc(start, controlPoint, end, smoothness, width, colour, leg) {636 const curve = new THREE.QuadraticBezierCurve3(start, controlPoint, end);637 const points = curve.getPoints(smoothness);638 const geom = new THREE.BufferGeometry().setFromPoints(points);639 const material = new THREE.LineBasicMaterial({ color: colour, linewidth: width, transparent: true, opacity: 0.35});640 const arc = new THREE.Line(geom, material);641 arc.material.visible = false;642 arc.userData.leg = leg;643 arcGroup.add(arc);644 }645 function drawPoint(pos, radius, height, colour, label, clusterOrNull, isCluster, isTownCluster, visitObj) {646 const pointObj = new THREE.Group();647 pointObj.position.copy(pos);648 pointObj.lookAt(0, 0, 0);649 // TODO(iandioch): these should be put in userData650 pointObj.locationName = label;651 pointObj.hasCluster = !!clusterOrNull;652 pointObj.cluster = clusterOrNull;653 pointObj.isCluster = isCluster;654 pointObj.isTownCluster = isTownCluster;655 pointObj.visit = visitObj;656 const margin = radius*0.25;657 const baseGeom = new THREE.CircleGeometry(radius + margin, 8);658 const baseMaterial = new THREE.MeshBasicMaterial({color: 0xFFFFFF, side: THREE.BackSide});659 const base = new THREE.Mesh(baseGeom, baseMaterial);660 base.origMaterial = baseMaterial;661 pointObj.add(base);662 const geom = new THREE.CylinderGeometry(radius, radius*0.8, height, 8, 1, true);663 geom.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI/2));664 const sphereGeom = new THREE.SphereGeometry(radius, 8, 4, Math.PI, Math.PI, 0, Math.PI);665 const sphere = new THREE.Mesh(sphereGeom);666 sphere.position.z -= height/2;667 geom.mergeMesh(sphere);668 geom.mergeVertices();669 const material = new THREE.MeshBasicMaterial({color: colour});670 const point = new THREE.Mesh(geom, material);671 point.origMaterial = material;672 point.position.z = -height/2;673 pointObj.add(point);674 const div = document.createElement("div");675 div.textContent = label;676 div.classList.add("poi-tooltip");677 div.style.visibility = "hidden";678 const labelDiv = new CSS2DObject(div);679 labelDiv.position.set(0, margin, 0);680 pointObj.add(labelDiv);681 pointGroup.add(pointObj);682 }683 var visits = {};684 var legs = [];685 var collections = [];686 function loadTravelMap(url) {687 loadJSON(url, (data) => {688 legs = data.legs;689 collections = data.collections;690 var highestVisits = 0;691 var mostVisited = undefined;692 for (var i in data.visits) {693 // Do not consider clusters of points when calculating the most-visited places.694 // We want the height of clusters to be the height of the highest695 // component part, so this 696 if (data.visits[i].location.type === "CLUSTER") continue;697 var numVisits = data.visits[i].hours;698 if (numVisits > highestVisits) {699 highestVisits = numVisits;700 mostVisited = data.visits[i];701 }702 }703 if (mostVisited) {704 lookAt(mostVisited.location.lat, mostVisited.location.lng, 2);705 }706 const highestVisitsLog10 = Math.log10(highestVisits);707 var colourScale = chroma.scale(["navy", "purple", 0xDC6F3D, 0xe9c440]).mode('lch').gamma(0.5);708 for (var i in data.visits) {709 const visit = data.visits[i];710 visits[visit.location.id] = visit;711 var radius = 0.003;712 if (visit.location.type === "CLUSTER") {713 radius *= 1.5;714 }715 var visitHours = visit.hours;716 if (visit.location.type === "CLUSTER") {717 visitHours = Math.max(...data.visits.filter(subVisit => (subVisit.location.type !== "CLUSTER" && subVisit.cluster === visit.location.id)).map(v => v.hours));718 }719 const colour = colourScale(Math.log10(visitHours)/Math.log10(highestVisits)).hex();720 const MIN_HEIGHT = GLOBE_RADIUS/100;721 const MAX_HEIGHT = GLOBE_RADIUS/15;722 // Use a log-based height, because in a normal case, the place where723 // you live will have an order of magnitude more visit time than724 // other places you've visited, and will be 100s of times larger in725 // a linear scale.726 const MAX_LOG_HEIGHT = MAX_HEIGHT/2;727 let height = MIN_HEIGHT + (Math.log10(visitHours)/highestVisitsLog10)*MAX_LOG_HEIGHT;728 // However, also use a linear-scaled height in addition, because729 // we don't want somewhere you stayed for 1000 hours to be the same730 // height at a glance as somewhere you stayed for 120.731 height += (visitHours / highestVisits)*(MAX_HEIGHT - MAX_LOG_HEIGHT - MIN_HEIGHT);732 const label = visit.location.human_readable_name;733 const cluster = (visit.hasOwnProperty("cluster") ? visit.cluster : null);734 drawPoint(latLngToVector(visit.location.lat, visit.location.lng), radius, height, colour, label, cluster, (visit.location.type === "CLUSTER"), (visit.location.type === "TOWN_CLUSTER"), visit);735 }736 for (var i in data.legs) {737 const leg = data.legs[i];738 if (leg.mode === "FILL") {739 // These are auto-added to make all legs into one continuous route.740 continue;741 }742 const legDistance = latLngDistance(leg.dep.lat, leg.dep.lng, leg.arr.lat, leg.arr.lng);743 const globeCircumference = 40000;744 const controlPointHeight = mapToRange(0, globeCircumference, GLOBE_RADIUS, GLOBE_RADIUS * 3, legDistance);745 const smoothness = Math.ceil(mapToRange(0, globeCircumference, 4, 64, legDistance));746 const midpoint = latLngMidpoint(leg.dep.lat, leg.dep.lng, leg.arr.lat, leg.arr.lng);747 drawRaisedArc(latLngToVector(leg.dep.lat, leg.dep.lng), latLngToVector(midpoint[0], midpoint[1], controlPointHeight), latLngToVector(leg.arr.lat, leg.arr.lng), smoothness, 3, 0xFFFFFF, leg);748 }749 dashboard.loadData(data);750 if (urlParams.has("collection")) {751 for (const collection of collections) {752 if (collection.id == urlParams.get("collection")) {753 renderInfoForCollection(collection);754 }755 }756 }757 });758 }759 loadTravelMap('/taisteal/api/travel_map');760 // Make semitransparent most plcaes except the one the user just clicked on.761 // If specificLegs is set, only those legs will be rendered.762 function toggleRoutesForSelectedVisits(locationIDs, showLegs = true, showConnectedLocations = true, specificLegs = null) {763 showLegs = showLegs && (!specificLegs);764 const visitSet = new Set(locationIDs);765 // Build up a set of everywhere that shares a leg with these visitNames.766 const connectedVisitSet = new Set(locationIDs);767 for (let i in arcGroup.children) {768 const arc = arcGroup.children[i];769 const leg = arc.userData.leg;770 var visible = false;771 if (visitSet.has(leg.arr.id)) {772 if (showConnectedLocations) connectedVisitSet.add(leg.dep.id);773 visible = true;774 } else if (visitSet.has(leg.dep.id)) {775 if (showConnectedLocations) connectedVisitSet.add(leg.arr.id);776 visible = true;777 }778 visible = visible && showLegs;779 if (specificLegs) {780 for (const specificLeg of specificLegs) {781 if (leg.arr.id == specificLeg.arr.id && leg.dep.id == specificLeg.dep.id) {782 visible = true;783 }784 }785 }786 arc.material.visible = visible;787 }788 // Also add any relevant clusters to the set, so that if we zoom in/out789 // the clusters will be shown as needed in place of the specific locations.790 // TODO(iandioch): If a station, which is a member of a TOWN_CLUSTER, is clicked, the associated town's own cluster will not be rendered if you zoom out.791 for (let i in visits) {792 const visit = visits[i];793 if (!('cluster' in visit)) continue;794 if (connectedVisitSet.has(visit.location.id)) {795 connectedVisitSet.add(visit.cluster);796 }797 }798 // Make semitransparent all of the pins not in the connectedVisitSet.799 const inactiveBaseMaterial = new THREE.MeshPhongMaterial({800 color: 0xffffff,801 opacity: 0.5,802 transparent: true,803 side: THREE.DoubleSide,804 shininess: 0,805 });806 const inactivePointMaterial = new THREE.MeshPhongMaterial({807 color: 0xdddddd,808 opacity: 0.5,809 transparent: true,810 side: THREE.DoubleSide,811 shininess: 0812 });813 for (let i in pointGroup.children) {814 const pointParent = pointGroup.children[i];815 const visible = connectedVisitSet.has(pointParent.visit.location.id);816 var baseMaterial = pointParent.children[0].origMaterial;817 var pointMaterial = pointParent.children[1].origMaterial;818 if (!visible) {819 baseMaterial = inactiveBaseMaterial;820 pointMaterial = inactivePointMaterial;821 }822 pointParent.children[0].material = baseMaterial;823 pointParent.children[1].material = pointMaterial;824 }825 }826 // TODO: Rename, because it has nothing to do with the name of a location827 // anymore.828 function getPointForName(location_id) {829 // TODO: it'd be more useful to just return here visits[location_id].830 // Check if anything actually needs the point obj.831 for (let i in pointGroup.children) {832 const point = pointGroup.children[i];833 if (point.visit.location.id == location_id) return point;834 }835 return null;836 }837 function getLegsForCollection(collection) {838 const collectionLegs = [];839 for (const part of collection.parts) {840 if (part.leg_id) {841 for (const leg of legs) {842 if (part.dep.id == leg.dep.id && part.arr.id == leg.arr.id) {843 collectionLegs.push(leg);844 }845 }846 }847 }848 return collectionLegs;849 }850 function getLocationsForCollection(collection) {851 const legs = getLegsForCollection(collection);852 const locationIDs = new Set();853 for (const leg of getLegsForCollection(collection)) {854 locationIDs.add(leg.dep.id);855 locationIDs.add(leg.arr.id);856 }857 const locations = [];858 for (const id of locationIDs) {859 locations.push(visits[id]);860 }861 return locations;862 }863 function getClusterMembers(location_id) {864 const point = getPointForName(location_id);865 var locations = [];866 if (point.isCluster || point.isTownCluster) {867 const clusterName = point.visit.location.id;868 for (let i in visits) {869 if (visits[i].hasOwnProperty("cluster") && (visits[i].cluster == location_id)) {870 const members = getClusterMembers(visits[i].location.id);871 locations.push(...members);872 }873 }874 } else {875 locations.push(point.visit.location.id);876 }877 return locations;878 }879 function renderInfoForPOI(location_id) {880 console.log("Rendering info for clicked point: ", location_id);881 const point = getPointForName(location_id);882 const locations = getClusterMembers(location_id);883 const locationObjs = [];884 for (const loc of locations) {885 locationObjs.push(visits[loc]);886 }887 toggleRoutesForSelectedVisits(locations);888 dashboard.renderPOI(point, locationObjs);889 lookAt(point.visit.location.lat, point.visit.location.lng, getCameraDistance());890 }891 function renderInfoForCountry(countryName) {892 const visits = getVisitsForCountry(countryName);893 dashboard.renderCountry(countryName, visits);894 var locationNames = [];895 for (let i in visits) {896 locationNames.push(visits[i].location.id);897 }898 toggleRoutesForSelectedVisits(locationNames, true, false);899 }900 function renderInfoForRegion(countryName, regionName) {901 const visits = getVisitsForCountry(countryName);902 const regionVisits = [];903 const regionLocationIDs = [];904 for (let i in visits) {905 if (visits[i].location.region == regionName) {906 regionVisits.push(visits[i]);907 regionLocationIDs.push(visits[i].location.id);908 }909 }910 dashboard.renderCountry(regionName, regionVisits);911 toggleRoutesForSelectedVisits(regionLocationIDs, true, false);912 }913 function renderInfoForCollection(collection) {914 console.log("Rendering info for collection", collection);915 const locationIDs = new Set();916 for (const leg of getLegsForCollection(collection)) {917 locationIDs.add(leg.dep.id);918 locationIDs.add(leg.arr.id);919 }920 console.log("Location IDs:", locationIDs);921 dashboard.renderCollection(collection);922 toggleRoutesForSelectedVisits([...locationIDs], true, false, getLegsForCollection(collection));923 }924 // Returns true if we needed to resize.925 function resizeRendererToDisplaySize(renderer) {926 const canvas = renderer.domElement;927 const needResize = (canvas.width !== canvas.clientWidth ||928 canvas.height !== canvas.clientHeight);929 if (needResize) {930 renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);931 labelRenderer.setSize(canvas.width, canvas.height);932 }933 return needResize;934 }935 var highlightedPoint; 936 var colourBeforeHighlight;937 var tooltipDiv = document.createElement('div');938 tooltipDiv.textContent = "Ros na Rún";939 tooltipDiv.style.marginTop = '-1em';940 const tooltipLabel = new CSS2DObject(tooltipDiv);941 tooltipLabel.position.set(0, GLOBE_RADIUS, 0);942 function updateHighlightedPoint() {943 function revertHighlightedPoint() {944 if (!highlightedPoint) return;945 /*highlightedPoint.children[1].material.color.setHex(colourBeforeHighlight);*/946 highlightedPoint.children[2].element.style.visibility = "hidden";947 }948 raycaster.setFromCamera(mouse, camera);949 var intersectedPoints = raycaster.intersectObjects(pointGroup.children, true);950 if (intersectedPoints.length > 0) {951 for (var i in intersectedPoints) {952 if (!intersectedPoints[i].object.material.visible) continue;953 // First point is the one closest to camera.954 const pointParent = intersectedPoints[i].object.parent;955 if (pointParent != highlightedPoint) {956 revertHighlightedPoint();957 highlightedPoint = pointParent;958 /*colourBeforeHighlight = pointParent.children[1].material.color.getHex();959 pointParent.children[1].material.color.setHex(0x000000);960 */pointParent.children[2].element.style.visibility = "visible";961 }962 break;963 }964 } else {965 // No currently intersected points.966 revertHighlightedPoint();967 highlightedPoint = null; // Delete prev highlight, if it exists.968 }969 }970 function getCameraDistance() {971 return camera.position.distanceTo(controls.target);972 }973 function lookAt(lat, lng, distance) {974 console.log("Tweening camera to ", lat, ", ", lng, " at distance ", distance);975 TWEEN.removeAll();976 // TODO: Instead need to do latLngToVector(lat, lng) plus some other vector of distance*(some direction)977 const newCameraPos = latLngToVector(lat, lng, distance);978 //newCameraPos.add(new THREE.Vector3(0, 0, 0).lookAt(979 //newCameraPos.addScaledVector(new THREE.Vector3(1, 0, 0).lookAt(new THREE.Vector3(0, 0, 0), distance));980 new TWEEN.Tween(camera.position).to(newCameraPos, 500).easing(TWEEN.Easing.Cubic.Out).start();981 /*const newCameraTarget = latLngToVector(lat, lng);982 new TWEEN.Tween(controls.target).to(newCameraTarget, 500).easing(TWEEN.Easing.Cubic.Out).start();*/983 }984 // If we receive any touch event, set this value.985 var TOUCH_SCREEN = false; 986 function setMousePosition(x, y) {987 const canvasRect = renderer.domElement.getBoundingClientRect();988 x -= canvasRect.left;989 y -= canvasRect.top;990 mouse.x = (x / renderer.domElement.clientWidth) * 2 - 1;991 mouse.y = -(y / renderer.domElement.clientHeight) * 2 + 1;992 }993 function onMouseMove(event) {994 event.preventDefault();995 setMousePosition(event.clientX, event.clientY);996 }997 function onMouseDown(event) {998 console.log("onMouseDown: " + event);999 event.preventDefault();1000 if (("targetTouches" in event) && (event.targetTouches.length == 1)) {1001 // Update "mouse" position for touchscreens. Do not do so for pinch-zooms.1002 TOUCH_SCREEN = true;1003 setMousePosition(event.targetTouches[0].clientX, event.targetTouches[0].clientY);1004 }1005 updateHighlightedPoint();1006 if (highlightedPoint) {1007 renderInfoForPOI(highlightedPoint.visit.location.id);1008 }1009 }1010 var prevCameraDistance = 0;1011 function onZoomChange() {1012 // It seems that the iterations we're doing when zooming are extremely1013 // slow, so we should try to avoid doing them if possible.1014 const cameraDistance = getCameraDistance();1015 if (cameraDistance === prevCameraDistance) {1016 return;1017 }1018 prevCameraDistance = cameraDistance;1019 const scale = mapToRange(MIN_CAMERA_DISTANCE, MAX_CAMERA_DISTANCE, 0.2, 5, cameraDistance);1020 const showClusters = (cameraDistance > MAX_CAMERA_DISTANCE/2.0);1021 const showLocalClusters = (cameraDistance > MIN_CAMERA_DISTANCE*1.1);1022 for (var i in pointGroup.children) {1023 const point = pointGroup.children[i];1024 point.scale.set(scale, scale, scale);1025 if (point.isCluster) {1026 point.visible = showClusters;1027 }1028 if (point.hasCluster) {1029 const clusterPoint = getPointForName(point.visit.cluster);1030 if (clusterPoint.isTownCluster) {1031 point.visible = !showLocalClusters;1032 } else {1033 point.visible = !showClusters;1034 }1035 }1036 }1037 }1038 controls.addEventListener('end', onZoomChange);1039 var lastTime = 0;1040 var frameCount = 0;1041 function render(time) {1042 frameCount ++;1043 if (frameCount % 100 == 0) {1044 const elapsedSeconds = (time - lastTime) * 0.001;1045 console.info("Frame #", frameCount, ": ", 1/elapsedSeconds, "fps");1046 console.log("Scene polycount:", renderer.info.render.triangles)1047 console.log("Active Drawcalls:", renderer.info.render.calls)1048 console.log("Textures in Memory", renderer.info.memory.textures)1049 console.log("Geometries in Memory", renderer.info.memory.geometries)1050 }1051 lastTime = time;1052 const seconds = time * 0.001;1053 const cameraDistance = getCameraDistance();1054 // Only update the highlighted point if it is not a touchscreen. If it1055 // is a touchscreen, and we touch somewhere with a swipe, the globe will1056 // spin, and if any point happens to be under the place we touched as1057 // the globe spins, it will activate without this !TOUCH_SCREEN check.1058 if (!TOUCH_SCREEN) updateHighlightedPoint();1059 controls.rotateSpeed = mapToRange(MIN_CAMERA_DISTANCE, MAX_CAMERA_DISTANCE, 0.1, 1.0, cameraDistance);1060 TWEEN.update();1061 controls.update();1062 if (resizeRendererToDisplaySize(renderer)) {1063 const canvas = renderer.domElement;1064 camera.aspect = canvas.clientWidth / canvas.clientHeight;1065 camera.updateProjectionMatrix();1066 }1067 renderer.render(scene, camera);1068 labelRenderer.render(scene, camera);1069 requestAnimationFrame(render);1070 }1071 requestAnimationFrame(render);...

Full Screen

Full Screen

missingDocs.js

Source:missingDocs.js Github

copy

Full Screen

...159 }160 /**161 * @param {!ts.Node} node162 */163 function visitNames(node) {164 if (ts.isExportSpecifier(node))165 apiClassNames.add(node.name.text);166 ts.forEachChild(node, visitNames);167 }168 visitNames(apiSource);169 visitMethods(apiSource);170 return apiMethods;...

Full Screen

Full Screen

AppliedFilters.js

Source:AppliedFilters.js Github

copy

Full Screen

1import {StyleSheet, Text, View} from "react-native";2import React from 'react';3import Colors from "../primitives/Colors";4import AbstractComponent from "../../framework/view/AbstractComponent";5import General from "../../utility/General";6export default class AppliedFilters extends AbstractComponent {7 static styles = StyleSheet.create({8 container: {9 flexDirection: 'column',10 justifyContent: 'flex-start',11 },12 });13 renderContent(label, content, contentSeparator) {14 const separator = _.isNil(contentSeparator) ? '' : contentSeparator;15 return <Text key={label}>16 <Text style={{17 fontSize: 14,18 color: Colors.TextOnPrimaryColor,19 fontWeight: 'bold',20 }}>{label} - </Text>21 <Text style={{22 fontSize: 14,23 color: Colors.TextOnPrimaryColor,24 }}>{content}{separator}</Text>25 </Text>26 }27 renderFilteredLocations() {28 if (this.props.selectedLocations.length > 0) {29 const allUniqueTypes = _.uniqBy(_.map(this.props.selectedLocations, ({type}) => ({type})), 'type');30 return allUniqueTypes.map((l, index) => this.renderContent(this.I18n.t(l.type),31 _.get(_.groupBy(this.props.selectedLocations, 'type'), l.type, []).map((locations) => this.I18n.t(locations.name)).join(", "),32 index === this.props.selectedLocations.length - 1 ? ' ' : ' | '));33 }34 }35 renderFilteredPrograms() {36 if (this.props.programs.length > 1 && this.props.selectedPrograms.length > 0) {37 const programNames = this.props.selectedPrograms.map((prog) => this.I18n.t(prog.operationalProgramName || prog.name));38 return this.renderContent(this.I18n.t('Program'), programNames.join(', '))39 }40 }41 renderFilteredVisits() {42 if (this.props.selectedEncounterTypes.length > 0) {43 const visitNames = this.props.selectedEncounterTypes.map((encType) => this.I18n.t(encType.operationalEncounterTypeName));44 return this.renderContent(this.I18n.t('Visit'), visitNames.join(', '))45 }46 }47 renderFilteredGeneralVisits() {48 if (!_.isEmpty(this.props.selectedGeneralEncounterTypes)) {49 const visitNames = _.map(this.props.selectedGeneralEncounterTypes, 'operationalEncounterTypeName')50 .map(x => this.I18n.t(x))51 .join(', ');52 return this.renderContent(this.I18n.t('General Visit'), visitNames);53 }54 }55 renderCustomFilters() {56 const readableTime = (dateType, value) => dateType && General.toDisplayDate(value) || value;57 const filterValue = (value) => [58 this.I18n.t(value.name || value.value || readableTime(value.dateType, value.minValue) || ''),59 this.I18n.t(value.maxValue && readableTime(value.dateType, value.maxValue) || '')60 ].filter(Boolean).join(" to ");61 if (!_.isEmpty(this.props.selectedCustomFilters)) {62 const nonEmptyFilters = _.pickBy(this.props.selectedCustomFilters, (v, k) => !_.isEmpty(v));63 const filters = Object.keys(nonEmptyFilters);64 return _.map(filters, filter => {65 const answers = nonEmptyFilters[filter].map(filterValue).join(", ");66 return this.renderContent(this.I18n.t(filter), answers);67 })68 }69 }70 renderGenderFilters() {71 if (!_.isEmpty(this.props.selectedGenders)) {72 const genderNames = _.map(this.props.selectedGenders, gender => this.I18n.t(gender.name)).join(", ");73 return this.renderContent(this.I18n.t('gender'), genderNames);74 }75 }76 render() {77 const appliedFilters = [...this.props.filters.values()]78 .filter(f => f.isApplied())79 .map((f) => this.renderContent(f.label, f.selectedOptions.join(', ')));80 return (81 <View style={AppliedFilters.styles.container}>82 <Text>83 {this.renderFilteredLocations()}84 </Text>85 {this.renderFilteredPrograms()}86 {this.renderFilteredVisits()}87 {this.renderFilteredGeneralVisits()}88 {this.renderCustomFilters()}89 {this.renderGenderFilters()}90 {appliedFilters}91 </View>92 );93 }...

Full Screen

Full Screen

export-util.js

Source:export-util.js Github

copy

Full Screen

1angular.module('os.biospecimen.participant')2 .factory('ExportUtil', function($translate) {3 function addForms(exportTypes, group, entityType, input, forms) {4 angular.forEach(forms,5 function(form) {6 exportTypes.push({7 group: group,8 type: 'extensions',9 title: form.caption,10 '$$input': input,11 params: { entityType: entityType, formName: form.name }12 });13 });14 return exportTypes;15 }16 function msg(key) {17 return $translate.instant(key);18 }19 function getParticipantTypes(entityForms, cpId) {20 var group = $translate.instant('participant.title');21 var input = {'var': 'ppids', varName: 'participant.ppids', varDesc: 'participant.ppids_csv'};22 var exportTypes = [23 { group: group, type: 'cpr', title: msg('participant.list'), '$$input': input },24 { group: group, type: 'consent', title: msg('participant.consents'), '$$input': input }25 ];26 addForms(exportTypes, group, 'CommonParticipant', input, entityForms['CommonParticipant']);27 return addForms(exportTypes, group, 'Participant', input, entityForms['Participant']);28 } 29 function getVisitTypes(entityForms) {30 var group = $translate.instant('visits.title');31 var input = {'var': 'visitNames', varName: 'visits.names', varDesc: 'visits.names_csv'};32 var exportTypes = [{ group: group, type: 'visit', title: msg('visits.list'), '$$input': input }];33 return addForms(exportTypes, group, 'SpecimenCollectionGroup', input, entityForms['SpecimenCollectionGroup']);34 }35 function getSpecimenTypes(cp, entityForms) {36 var group = $translate.instant('specimens.title');37 var input = {'var': 'specimenLabels', varName: 'specimens.labels', varDesc: 'specimens.labels_csv'};38 var exportTypes = [{ group: group, type: 'specimen', title: msg('specimens.list'), '$$input': input }]39 addForms(exportTypes, group, 'Specimen', input, entityForms['Specimen']);40 return addForms(exportTypes, group, 'SpecimenEvent', input, entityForms['SpecimenEvent']);41 }42 function getExportDetail(cp, allowedEntityTypes, forms) {43 var breadcrumbs, onSuccess;44 if (cp.id == -1) {45 breadcrumbs = [{state: 'cp-list', title: 'cp.list'}];46 onSuccess = {state: 'cp-list', params: {}};47 } else {48 breadcrumbs = [{state: 'cp-list-view', title: cp.shortTitle, params: '{cpId:' + cp.id + '}'}];49 onSuccess = {state: 'cp-list-view', params: {cpId: cp.id}};50 }51 var entityForms = {};52 angular.forEach(forms,53 function(form) {54 if (!entityForms[form.entityType]) {55 entityForms[form.entityType] = [];56 }57 entityForms[form.entityType].push(form);58 }59 );60 var exportTypes = [];61 if (!cp.specimenCentric && allowedEntityTypes.indexOf('Participant') >= 0) {62 exportTypes = exportTypes.concat(getParticipantTypes(entityForms, cp.id));63 }64 if (!cp.specimenCentric && allowedEntityTypes.indexOf('SpecimenCollectionGroup') >= 0) {65 exportTypes = exportTypes.concat(getVisitTypes(entityForms));66 }67 if (allowedEntityTypes.indexOf('Specimen') >= 0) {68 exportTypes = exportTypes.concat(getSpecimenTypes(cp, entityForms));69 }70 angular.forEach(exportTypes,71 function(exportType) {72 if (!exportType.params) {73 exportType.params = {};74 }75 exportType.params.cpId = cp.id;76 }77 );78 return {79 breadcrumbs: breadcrumbs,80 title: 'export.title',81 type: undefined,82 onSuccess: onSuccess,83 types: exportTypes,84 params: {85 cpId: cp.id86 }87 };88 }89 return {90 getExportDetail: function(cp, allowedEntityTypes, forms) {91 return $translate('common.none').then(92 function() {93 return getExportDetail(cp, allowedEntityTypes, forms);94 }95 );96 }97 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Docs');8 await page.click('text=API');9 await page.click('text=Class: Page');10 await page.click('text=page.visitName');11 await browser.close();12 }13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page.click('text=Docs');6 const [response] = await Promise.all([7 page.click('text=Intro'),8 ]);9 const allLinks = await page.$$eval('a', (links) => links.map((link) => link.href));10 console.log(allLinks);11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch({ headless: false });16 const page = await browser.newPage();17 await page.click('text=Docs');18 const [response] = await Promise.all([19 page.click('text=Intro'),20 ]);21 const allLinks = await page.$$eval('a', (links) => links.map((link) => link.href));22 console.log(allLinks);23 await browser.close();24})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { visitNames } = require('@playwright/test');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await browser.close();8})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { visitNames } = require('playwright/lib/server/chromium/crNetworkManager');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const visited = await visitNames(page);8 console.log(visited);9 await browser.close();10})();11#### browserType.launch([options])

Full Screen

Using AI Code Generation

copy

Full Screen

1const { visitNames } = require('playwright/lib/internal');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 const visitedPages = visitNames(page);9 console.log(visitedPages);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const links = await page.$$eval('a', (links) => {6 return links.map((link) => link.textContent);7 });8 for (const link of links) {9 await page.click(`text=${link}`);10 await page.goBack();11 }12 await browser.close();13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { visitNames } = require('playwright-internal');2(async () => {3 console.log(names);4})();5### visitNames(url, options)6[Apache-2.0](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { visitNames } = require('@playwright/test');2## Run the test in headless mode with verbose logging and test name filter (regex)3## Run the test in headless mode with verbose logging and test name filter (regex) and test file name filter (regex)4## Run the test in headless mode with verbose logging and test name filter (regex) and test file name filter (regex) and save the results to a file5## Run the test in headless mode with verbose logging and test name filter (regex) and test file name filter (regex) and save the results to a file and run in parallel6## Run the test in headless mode with verbose logging and test name filter (regex) and test file name filter (regex) and save the results to a file and run in parallel and set the timeout to 30 seconds7## Run the test in headless mode with verbose logging and test name filter (regex) and test file name filter (regex) and save the results

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful