Best JavaScript code snippet using playwright-internal
repos.js
Source:repos.js
1/**2 * @author Lior Hasson3 */4function repos(button, jsFunction, uniqueId, artifactoryUrl, credentialsInput, bind) {5 let username, password, credentialsId, overrideCredentials;6 // Start spinner7 button = button._button;8 let spinner = $(button).up("DIV").next();9 spinner.style.display = "block";10 let target = spinner.next();11 target.innerHTML = "";12 let warning = target.next();13 warning.innerHTML = "";14 let legacyInput = $('legacy' + credentialsInput);15 if (legacyInput) {16 overrideCredentials = legacyInput.down('input[type=checkbox]').checked;17 username = legacyInput.down('input[name=_.username]').value;18 password = legacyInput.down('input[name=_.password]').value;19 }20 let credentialsPluginInput = $(credentialsInput);21 if (credentialsPluginInput) {22 credentialsId = $(credentialsInput).down('select').value;23 }24 if (jsFunction) {25 jsFunctionsMap[jsFunction](spinner, uniqueId, $(artifactoryUrl).value, credentialsId, username, password, overrideCredentials, bind);26 }27}28// maps a function name to the function object29// noinspection JSUnusedGlobalSymbols30let jsFunctionsMap = {31 artifactoryIvyFreeStyleConfigurator: artifactoryIvyFreeStyleConfigurator,32 artifactoryGenericConfigurator: artifactoryGenericConfigurator,33 artifactoryMaven3NativeConfigurator: artifactoryMaven3NativeConfigurator,34 artifactoryMaven3Configurator: artifactoryMaven3Configurator,35 artifactoryGradleConfigurator: artifactoryGradleConfigurator,36 artifactoryGradleConfigurationResolve: artifactoryGradleConfigurationResolve,37 artifactoryRedeployPublisher: artifactoryRedeployPublisher,38 artifactoryIvyConfigurator: artifactoryIvyConfigurator,39};40function artifactoryIvyFreeStyleConfigurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {41 // noinspection JSUnresolvedFunction42 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {43 let target = spinner.next();44 let warning = target.next();45 let response = t.responseObject();46 if (!response.success) {47 displayErrorResponse(spinner, target, response.responseMessage);48 return;49 }50 let select = getElementByUniqueId("select_ivyFreeRepositoryKeys-" + artifactoryUrl, uniqueId);51 let oldValue = select.value;52 let oldSelect = select.cloneNode(true);53 removeElements(select);54 fillSelect(select, response.repositories);55 setSelectValue(select, oldValue);56 let oldValueExistsInNewList = compareSelectTags(select, oldSelect);57 if (!oldValueExistsInNewList) {58 displayWarningMessage(warning);59 }60 displaySuccessMessage(spinner, target);61 });62}63function artifactoryGenericConfigurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {64 // noinspection JSUnresolvedFunction65 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {66 let target = spinner.next();67 let warning = target.next();68 let response = t.responseObject();69 if (!response.success) {70 displayErrorResponse(spinner, target, response.responseMessage);71 return;72 }73 let select = getElementByUniqueId("select_genericRepositoryKeys-" + artifactoryUrl, uniqueId);74 let oldValue = select.value;75 let oldSelect = select.cloneNode(true);76 removeElements(select);77 fillSelect(select, response.repositories);78 setSelectValue(select, oldValue);79 let oldValueExistsInNewList = compareSelectTags(select, oldSelect);80 if (!oldValueExistsInNewList) {81 displayWarningMessage(warning);82 }83 displaySuccessMessage(spinner, target);84 });85}86function artifactoryMaven3NativeConfigurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {87 // noinspection JSUnresolvedFunction88 bind.refreshResolversFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {89 let target = spinner.next();90 let warning = target.next();91 let response = t.responseObject();92 if (!response.success) {93 displayErrorResponse(spinner, target, response.responseMessage);94 return;95 }96 let selectRelease = getElementByUniqueId("select_maven3NativeReleaseRepositoryKeys-" + artifactoryUrl, uniqueId);97 let selectSnapshot = getElementByUniqueId("select_maven3NativeSnapshotRepositoryKeys-" + artifactoryUrl, uniqueId);98 let oldReleaseValue = selectRelease.value;99 let oldSnapshotValue = selectSnapshot.value;100 let oldSelectRelease = selectRelease.cloneNode(true);101 let oldSelectSnapshot = selectSnapshot.cloneNode(true);102 removeElements(selectRelease);103 removeElements(selectSnapshot);104 fillVirtualReposSelect(selectRelease, response.virtualRepositories);105 fillVirtualReposSelect(selectSnapshot, response.virtualRepositories);106 setSelectValue(selectRelease, oldReleaseValue);107 setSelectValue(selectSnapshot, oldSnapshotValue);108 let oldValueExistsInNewList = compareSelectTags(selectRelease, oldSelectRelease) && compareSelectTags(selectSnapshot, oldSelectSnapshot);109 if (!oldValueExistsInNewList) {110 displayWarningMessage(warning);111 }112 displaySuccessMessage(spinner, target);113 });114}115function artifactoryMaven3Configurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {116 // noinspection JSUnresolvedFunction117 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {118 let target = spinner.next();119 let warning = target.next();120 let response = t.responseObject();121 if (!response.success) {122 displayErrorResponse(spinner, target, response.responseMessage);123 return;124 }125 let selectRelease = getElementByUniqueId("select_maven3RepositoryKeys-" + artifactoryUrl, uniqueId);126 let selectSnapshot = getElementByUniqueId("select_maven3SnapshotsRepositoryKeys-" + artifactoryUrl, uniqueId);127 let oldReleaseValue = selectRelease.value;128 let oldSnapshotValue = selectSnapshot.value;129 let oldSelectRelease = selectRelease.cloneNode(true);130 let oldSelectSnapshot = selectSnapshot.cloneNode(true);131 removeElements(selectRelease);132 removeElements(selectSnapshot);133 fillSelect(selectRelease, response.repositories);134 fillSelect(selectSnapshot, response.repositories);135 setSelectValue(selectRelease, oldReleaseValue);136 setSelectValue(selectSnapshot, oldSnapshotValue);137 let oldValueExistsInNewList = compareSelectTags(selectRelease, oldSelectRelease) && compareSelectTags(selectSnapshot, oldSelectSnapshot);138 if (!oldValueExistsInNewList) {139 displayWarningMessage(warning);140 }141 displaySuccessMessage(spinner, target);142 });143}144function artifactoryGradleConfigurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {145 // noinspection JSUnresolvedFunction146 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {147 let target = spinner.next();148 let warning = target.next();149 let response = t.responseObject();150 if (!response.success) {151 displayErrorResponse(spinner, target, response.responseMessage);152 return;153 }154 let selectPublish = getElementByUniqueId("select_gradlePublishRepositoryKeys-" + artifactoryUrl, uniqueId);155 let selectPlugins = getElementByUniqueId("gradleCustomStagingConfiguration-" + artifactoryUrl, uniqueId);156 let oldPublishValue = selectPublish.value;157 let oldPluginsValue = selectPlugins.value;158 let oldSelectPublish = selectPublish.cloneNode(true);159 let oldSelectPlugins = selectPlugins.cloneNode(true);160 removeElements(selectPublish);161 removeElements(selectPlugins);162 fillSelect(selectPublish, response.repositories);163 fillStagingPluginsSelect(selectPlugins, response.userPlugins);164 createStagingParamsInputs(response.userPlugins, uniqueId);165 setSelectValue(selectPublish, oldPublishValue);166 setSelectValue(selectPlugins, oldPluginsValue);167 setStagingParamsSelectedValue(selectPlugins, uniqueId);168 let oldValueExistsInNewList = compareSelectTags(selectPublish, oldSelectPublish) && compareSelectTags(selectPlugins, oldSelectPlugins);169 if (!oldValueExistsInNewList) {170 displayWarningMessage(warning);171 }172 displaySuccessMessage(spinner, target);173 });174}175function artifactoryGradleConfigurationResolve(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {176 // noinspection JSUnresolvedFunction177 bind.refreshResolversFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {178 let target = spinner.next();179 let warning = target.next();180 let response = t.responseObject();181 if (!response.success) {182 displayErrorResponse(spinner, target, response.responseMessage);183 return;184 }185 let selectResolution = getElementByUniqueId("select_gradleResolutionRepositoryKeys-" + artifactoryUrl, uniqueId);186 let oldResolutionValue = selectResolution.value;187 let oldSelectResolution = selectResolution.cloneNode(true);188 removeElements(selectResolution);189 fillVirtualReposSelect(selectResolution, response.virtualRepositories);190 setSelectValue(selectResolution, oldResolutionValue);191 let oldValueExistsInNewList = compareSelectTags(selectResolution, oldSelectResolution);192 if (!oldValueExistsInNewList) {193 displayWarningMessage(warning);194 }195 displaySuccessMessage(spinner, target);196 });197}198function artifactoryRedeployPublisher(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {199 // noinspection JSUnresolvedFunction200 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {201 let target = spinner.next();202 let warning = target.next();203 let response = t.responseObject();204 if (!response.success) {205 displayErrorResponse(spinner, target, response.responseMessage);206 return;207 }208 let selectRelease = getElementByUniqueId("select_publishRepositoryKey-" + artifactoryUrl, uniqueId);209 let selectSnapshot = getElementByUniqueId("select_publishSnapshotsRepositoryKeys-" + artifactoryUrl, uniqueId);210 let selectPlugins = getElementByUniqueId("customStagingConfiguration-" + artifactoryUrl, uniqueId);211 let oldReleaseValue = selectRelease.value;212 let oldSnapshotValue = selectSnapshot.value;213 let oldPluginsValue = selectPlugins.value;214 let oldSelectRelease = selectRelease.cloneNode(true);215 let oldSelectSnapshot = selectSnapshot.cloneNode(true);216 let oldSelectPlugins = selectPlugins.cloneNode(true);217 removeElements(selectRelease);218 removeElements(selectSnapshot);219 removeElements(selectPlugins);220 fillSelect(selectSnapshot, response.repositories);221 fillSelect(selectRelease, response.repositories);222 fillStagingPluginsSelect(selectPlugins, response.userPlugins);223 createStagingParamsInputs(response.userPlugins, uniqueId);224 setSelectValue(selectRelease, oldReleaseValue);225 setSelectValue(selectSnapshot, oldSnapshotValue);226 setSelectValue(selectPlugins, oldPluginsValue);227 setStagingParamsSelectedValue(selectPlugins, uniqueId);228 let oldValueExistsInNewList = compareSelectTags(selectRelease, oldSelectRelease) &&229 compareSelectTags(selectSnapshot, oldSelectSnapshot) && compareSelectTags(selectPlugins, oldSelectPlugins);230 if (!oldValueExistsInNewList) {231 displayWarningMessage(warning);232 }233 displaySuccessMessage(spinner, target);234 });235}236function artifactoryIvyConfigurator(spinner, uniqueId, artifactoryUrl, credentialsId, username, password, overrideCredentials, bind) {237 // noinspection JSUnresolvedFunction238 bind.refreshFromArtifactory(spinner, artifactoryUrl, credentialsId, username, password, overrideCredentials, function (t) {239 let target = spinner.next();240 let warning = target.next();241 let response = t.responseObject();242 if (!response.success) {243 displayErrorResponse(spinner, target, response.responseMessage);244 return;245 }246 let select = getElementByUniqueId("select_publishRepositoryKey-" + artifactoryUrl, uniqueId);247 let oldValue = select.value;248 let oldSelect = select.cloneNode(true);249 removeElements(select);250 fillSelect(select, response.repositories);251 setSelectValue(select, oldValue);252 let oldValueExistsInNewList = compareSelectTags(select, oldSelect);253 if (!oldValueExistsInNewList) {254 displayWarningMessage(warning);255 }256 displaySuccessMessage(spinner, target);257 });258}259function fillSelect(select, list) {260 let txtId = "txt_" + select.id;261 let txtElement = document.getElementById(txtId);262 // noinspection EqualityComparisonWithCoercionJS263 if (list.length > 0 && txtElement != undefined && txtElement.value === "") {264 txtElement.value = list[0];265 }266 for (let i = 0; i < list.length; i++) {267 let item = list[i];268 let option = document.createElement("option");269 option.text = item.value;270 option.innerText = item.value;271 option.value = item.value;272 select.appendChild(option);273 }274}275function fillVirtualReposSelect(select, list) {276 let txtId = "txt_" + select.id;277 let txtElement = document.getElementById(txtId);278 // noinspection EqualityComparisonWithCoercionJS279 if (list.length > 0 && txtElement != undefined && txtElement.value === "") {280 txtElement.value = list[0].value;281 }282 for (let i = 0; i < list.length; i++) {283 let item = list[i];284 let option = document.createElement("option");285 option.text = item.displayName;286 option.innerText = item.displayName;287 option.value = item.value;288 select.appendChild(option);289 }290}291function fillStagingPluginsSelect(select, list) {292 for (let i = 0; i < list.length; i++) {293 let item = list[i];294 let option = document.createElement("option");295 option.text = item.pluginName;296 option.innerText = item.pluginName;297 option.value = item.pluginName;298 select.appendChild(option);299 }300}301function createStagingParamsInputs(list, uniqueId) {302 let str = "";303 for (let i = 0; i < list.length; i++) {304 let item = list[i];305 str += "<input class='setting-input' " +306 "style='display:none' " +307 "id='stagingParams-" + item.pluginName + "-" + uniqueId + "' " +308 "type='text' " +309 "value='" + item.paramsString + "' />";310 }311 getElementByUniqueId("stagingParamsDiv", uniqueId).innerHTML = str;312}313function setStagingParamsSelectedValue(select, uniqueId) {314 for (let i = 0; i < select.options.length; i++) {315 let display = (i === select.selectedIndex) ? "" : "none";316 let inputName = "stagingParams-" + select.options[i].value + "-" + uniqueId;317 let input = document.getElementById(inputName);318 input.style.display = display;319 input.setAttribute("name", display ? "userPluginParams" : "");320 if (!display) {321 let div = getElementByUniqueId("stagingParamsDiv", uniqueId);322 div.style.display = input.value ? "" : "none";323 }324 }325}326function displaySuccessMessage(spinner, target) {327 spinner.style.display = "none";328 target.innerHTML = "Items refreshed successfully";329 target.removeClassName('error');330 target.style.color = "green";331}332function displayErrorResponse(spinner, target, message) {333 spinner.style.display = "none";334 target.innerHTML = message;335 target.addClassName('error');336 target.style.color = "red";337}338function displayWarningMessage(warning) {339 warning.innerHTML = "Warning! One of your previously configured items does not exist.";340 warning.style.color = "orange"341}342function removeElements(e) {343 while (e.firstChild) {344 e.removeChild(e.firstChild);345 }346}347function setSelectValue(select, value) {348 for (let i = 0; i < select.options.length; i++) {349 if (select.options[i].value === value) {350 select.selectedIndex = i;351 return;352 }353 }354}355function compareSelectTags(newRepos, oldRepos) {356 if (oldRepos.options.length === 0) {357 return true;358 }359 for (let i = 0; i < oldRepos.length; i++) {360 let itemOld = oldRepos[i].value;361 let flag = false;362 for (let j = 0; j < newRepos.length; j++) {363 let itemNew = newRepos[j].value;364 if (itemNew.value === itemOld.value) {365 flag = true;366 break;367 }368 }369 if (!flag) {370 return false;371 }372 }373 return true;374}375// toggle button onClick callback376// noinspection JSUnusedGlobalSymbols377function toggleTxtAndSelect(txtId, txtModeId) {378 let select = document.getElementById('select_' + txtId);379 let txt = document.getElementById(txtId);380 let shouldUseText = document.getElementById(txtModeId);381 let button = document.getElementById('btn_' + txtId);382 let currentValue = shouldUseText.value;383 if (currentValue === undefined || currentValue === "") {384 currentValue = false;385 }386 shouldUseText.value = !JSON.parse(currentValue);387 swapHiddenValue(txt, select, button);388}389function swapHiddenValue(txt, select, button) {390 if (txt.style.display === '') {391 txt.style.display = 'none';392 select.style.display = '';393 button.firstChild.firstChild.innerHTML = "Different Value";394 } else {395 select.style.display = 'none';396 txt.style.display = '';397 // noinspection SqlNoDataSourceInspection,SqlResolve398 button.firstChild.firstChild.innerHTML = "Select from List";399 }400}401function initTextAndSelectOnLoad(label, txtValue, selectValue) {402 let select = document.getElementById('select_' + label);403 let txt = document.getElementById(label);404 let button = document.getElementById('btn_' + label);405 // noinspection EqualityComparisonWithCoercionJS406 if (select != undefined && txt != undefined) {407 txt.style.display = txtValue;408 select.style.display = selectValue;409 // noinspection EqualityComparisonWithCoercionJS410 if (button != undefined) {411 if (txtValue === '') {412 // noinspection SqlNoDataSourceInspection,SqlResolve413 button.value = "Select from List";414 } else {415 button.value = "Different Value";416 }417 }418 }419}420/**421 * Get element by id and unique id.422 * @param elementId - The element id423 * @param uniqueId - Unique id generated in the Jelly424 * @returns {HTMLElement} - The element425 */426function getElementByUniqueId(elementId, uniqueId) {427 return document.getElementById(elementId + "-" + uniqueId)...
SnapshotSelector.js
Source:SnapshotSelector.js
...106 snapshots.length > 0 &&107 snapshotIndex < snapshots.length - 1108 ) {109 const newIndex = snapshotIndex + 1;110 selectSnapshot(snapshots[newIndex]);111 }112 };113 selectPreviousSnapshotIndex = () => {114 const {115 selectSnapshot,116 snapshotIndex,117 snapshots,118 } = this.props;119 if (120 snapshots.length > 0 &&121 snapshotIndex > 0122 ) {123 const newIndex = snapshotIndex - 1;124 selectSnapshot(snapshots[newIndex]);125 }126 };127 render() {128 const {129 commitThreshold,130 hideCommitsBelowThreshold,131 isInspectingSelectedFiber,132 selectedFiberID,133 selectedSnapshot,134 selectSnapshot,135 snapshotIndex,136 snapshots,137 theme,138 } = this.props;139 const numSnapshots = snapshots.length;140 return (141 <div142 onKeyDown={this.handleKeyDown}143 style={{144 display: 'flex',145 flex: '1 0 auto',146 alignItems: 'center',147 outline: 'none',148 }}149 tabIndex={0}150 >151 {numSnapshots === 0 && (152 <span style={{whiteSpace: 'nowrap'}}>153 0 / 0154 </span>155 )}156 {numSnapshots > 0 && (157 <span style={{whiteSpace: 'nowrap'}}>158 {`${snapshotIndex >= 0 ? snapshotIndex + 1 : '-'}`.padStart(`${numSnapshots}`.length, '0')} / {numSnapshots}159 </span>160 )}161 <IconButton162 disabled={snapshotIndex <= 0}163 icon={Icons.BACK}164 isTransparent={true}165 onClick={this.selectPreviousSnapshotIndex}166 theme={theme}167 title="Previous render"168 />169 <AutoSizedSnapshotSelector170 commitThreshold={commitThreshold}171 hideCommitsBelowThreshold={hideCommitsBelowThreshold}172 isInspectingSelectedFiber={isInspectingSelectedFiber}173 selectedFiberID={selectedFiberID}174 selectedSnapshot={selectedSnapshot}175 selectSnapshot={selectSnapshot}176 snapshotIndex={snapshotIndex}177 snapshots={snapshots}178 theme={theme}179 />180 <IconButton181 disabled={numSnapshots === 0 || snapshotIndex >= numSnapshots - 1}182 icon={Icons.FORWARD}183 isTransparent={true}184 onClick={this.selectNextSnapshotIndex}185 theme={theme}186 title="Next render"187 />188 </div>189 );190 }191}192const AutoSizedSnapshotSelector = ({193 isInspectingSelectedFiber,194 selectedFiberID,195 selectedSnapshot,196 selectSnapshot,197 snapshotIndex,198 snapshots,199 theme,200}: Props) => (201 <div style={{202 flex: '1 1 100px',203 height: HEIGHT,204 display: 'grid',205 alignitems: 'flex-end',206 gridGap: '1px',207 gridAutoFlow: 'column',208 backgroundColor: theme.base00,209 }}>210 <AutoSizer disableHeight={true}>211 {({ height, width }) => (212 <SnapshotSelector213 height={HEIGHT}214 selectedFiberID={selectedFiberID}215 selectedSnapshot={selectedSnapshot}216 selectSnapshot={selectSnapshot}217 snapshotIndex={snapshotIndex}218 snapshots={snapshots}219 theme={theme}220 width={width}221 />222 )}223 </AutoSizer>224 </div>225);226const LEFT_ARROW = 37;227const RIGHT_ARROW = 39;228type SnapshotSelectorProps = {|229 height: number,230 selectedFiberID: string | null,231 selectedSnapshot: Snapshot,232 selectSnapshot: SelectSnapshot,233 snapshotIndex: number,234 snapshots: Array<Snapshot>,235 theme: Theme,236 width: number,237|};238type SnapshotSelectorState = {|239 isMouseDown: boolean,240|};241class SnapshotSelector extends PureComponent<SnapshotSelectorProps, SnapshotSelectorState> {242 // $FlowFixMe createRef()243 listRef = React.createRef();244 state: SnapshotSelectorState = {245 isMouseDown: false,246 };247 componentDidUpdate(prevProps) {248 // Make sure any newly selected snapshot is visible within the list.249 if (250 this.props.snapshotIndex !== prevProps.snapshotIndex &&251 this.listRef.current !== null252 ) {253 this.listRef.current.scrollToItem(this.props.snapshotIndex);254 }255 }256 componentWillUnmount() {257 window.removeEventListener('mouseup', this.handleMouseUp);258 }259 handleMouseDown = event => this.setState({ isMouseDown: true }, () => {260 window.addEventListener('mouseup', this.handleMouseUp);261 });262 handleMouseUp = event => this.setState({ isMouseDown: false });263 render() {264 const {265 height,266 selectedSnapshot,267 selectSnapshot,268 snapshots,269 theme,270 width,271 } = this.props;272 const {isMouseDown} = this.state;273 const listData = getListData(snapshots, width);274 // Pass required contextual data down to the ListItem renderer.275 // (This method is memoized so it's safe to call on every render.)276 const itemData = getItemData(277 isMouseDown,278 listData.maxDuration,279 selectSnapshot,280 selectedSnapshot,281 snapshots,282 theme,283 );284 const numSnapshots = snapshots.length;285 return (286 <div287 onMouseDown={this.handleMouseDown}288 onMouseUp={this.handleMouseUp}289 style={{ height, width }}290 >291 {numSnapshots > 0 && (292 <List293 direction="horizontal"294 height={height}295 itemCount={snapshots.length}296 itemData={itemData}297 itemSize={listData.itemSize}298 ref={this.listRef}299 width={width}300 >301 {ListItem}302 </List>303 )}304 </div>305 );306 }307}308class ListItem extends PureComponent<any, void> {309 handleMouseEnter = () => {310 const itemData: ItemData = ((this.props.data: any): ItemData);311 if (itemData.isMouseDown) {312 itemData.selectSnapshot(itemData.snapshots[this.props.index]);313 }314 }315 render() {316 const { index, style } = this.props;317 const itemData: ItemData = ((this.props.data: any): ItemData);318 const {319 maxDuration,320 selectedSnapshot,321 selectSnapshot,322 snapshots,323 theme,324 } = itemData;325 const snapshot = snapshots[index];326 // Guard against commits with duration 0327 const percentage = Math.min(1, Math.max(0, snapshot.duration / maxDuration)) || 0;328 const isSelected = selectedSnapshot === snapshot;329 const width = parseFloat(style.width) - 1;330 return (331 <div332 onClick={() => selectSnapshot(snapshot)}333 onMouseEnter={this.handleMouseEnter}334 style={{335 ...style,336 width,337 backgroundColor: isSelected ? theme.base01 : 'transparent',338 userSelect: 'none',339 cursor: 'pointer',340 }}341 title={`Duration ${formatDuration(snapshot.duration)}ms at ${formatTime(snapshot.commitTime)}s`}342 >343 <div style={{344 position: 'absolute',345 bottom: 0,346 width,...
ProfilerTabToolbar.js
Source:ProfilerTabToolbar.js
1/**2 * Copyright (c) 2015-present, Facebook, Inc.3 * All rights reserved.4 *5 * This source code is licensed under the BSD-style license found in the6 * LICENSE file in the root directory of this source tree. An additional grant7 * of patent rights can be found in the PATENTS file in the same directory.8 *9 * @flow10 */11'use strict';12import type {Theme} from '../../../frontend/types';13import type {ChartType, Snapshot} from '../ProfilerTypes';14import React, { Fragment } from 'react';15import AutoSizer from 'react-virtualized-auto-sizer';16import Hoverable from '../../../frontend/Hoverable';17import SvgIcon from '../../../frontend/SvgIcon';18import Icons from '../../../frontend/Icons';19import IconButton from './IconButton';20import SnapshotSelector from './SnapshotSelector';21const CHART_RADIO_LABEL_WIDTH_THRESHOLD = 650;22type SelectSnapshot = (snapshot: Snapshot) => void;23type Props = {|24 commitThreshold: number,25 hideCommitsBelowThreshold: boolean,26 interactionsCount: number,27 isInspectingSelectedFiber: boolean,28 isRecording: boolean,29 selectChart: (chart: ChartType) => void,30 selectedChartType: ChartType,31 selectedFiberID: string | null,32 selectedSnapshot: Snapshot,33 selectSnapshot: SelectSnapshot,34 snapshotIndex: number,35 snapshots: Array<Snapshot>,36 theme: Theme,37 toggleIsRecording: Function,38 toggleIsSettingsPanelActive: Function,39|};40export default (props: Props) => (41 <AutoSizer disableHeight={true}>42 {({ width }) => (43 <ProfilerTabToolbar {...props} width={width} />44 )}45 </AutoSizer>46);47type ProfilerTabToolbarProps = {48 commitThreshold: number,49 hideCommitsBelowThreshold: boolean,50 interactionsCount: number,51 isInspectingSelectedFiber: boolean,52 isRecording: boolean,53 selectChart: (chart: ChartType) => void,54 selectedChartType: ChartType,55 selectedFiberID: string | null,56 selectedSnapshot: Snapshot,57 selectSnapshot: SelectSnapshot,58 snapshotIndex: number,59 snapshots: Array<Snapshot>,60 theme: Theme,61 toggleIsRecording: Function,62 toggleIsSettingsPanelActive: Function,63 width: number,64};65const ProfilerTabToolbar = ({66 commitThreshold,67 hideCommitsBelowThreshold,68 interactionsCount,69 isInspectingSelectedFiber,70 isRecording,71 selectChart,72 selectedChartType,73 selectedFiberID,74 selectedSnapshot,75 selectSnapshot,76 snapshotIndex,77 snapshots,78 theme,79 toggleIsRecording,80 toggleIsSettingsPanelActive,81 width,82}: ProfilerTabToolbarProps) => (83 <div style={{84 display: 'flex',85 flex: '0 0 auto',86 padding: '0.25rem',87 flexWrap: 'wrap',88 alignItems: 'center',89 position: 'relative',90 boxSizing: 'border-box',91 width,92 userSelect: 'none',93 }}>94 <RecordButton95 isActive={isRecording}96 onClick={toggleIsRecording}97 theme={theme}98 />99 <HRule theme={theme} />100 {isRecording || snapshots.length === 0 && (101 <Fragment>102 <div style={{flex: 1}} />103 <IconButton104 icon={Icons.SETTINGS}105 isTransparent={true}106 label="Profiler settings"107 onClick={toggleIsSettingsPanelActive}108 theme={theme}109 />110 </Fragment>111 )}112 {!isRecording && snapshots.length > 0 && (113 <Fragment>114 <RadioOption115 icon={Icons.FLAME_CHART}116 isChecked={selectedChartType === 'flamegraph'}117 isDisabled={isInspectingSelectedFiber}118 label="Flamegraph"119 onChange={() => selectChart('flamegraph')}120 theme={theme}121 width={width}122 />123 124 <RadioOption125 icon={Icons.RANKED_CHART}126 isChecked={selectedChartType === 'ranked'}127 isDisabled={isInspectingSelectedFiber}128 label="Ranked"129 onChange={() => selectChart('ranked')}130 theme={theme}131 width={width}132 />133 134 <RadioOption135 icon={Icons.INTERACTION}136 isChecked={selectedChartType === 'interactions'}137 isDisabled={isInspectingSelectedFiber}138 label={`Interactions (${interactionsCount})`}139 onChange={() => selectChart('interactions')}140 theme={theme}141 width={width}142 />143 <div style={{flex: 1}} />144 <IconButton145 icon={Icons.SETTINGS}146 isTransparent={true}147 label="Profiler settings"148 onClick={toggleIsSettingsPanelActive}149 theme={theme}150 />151 {selectedChartType !== 'interactions' && (152 <Fragment>153 <HRule theme={theme} />154 <SnapshotSelector155 commitThreshold={commitThreshold}156 hideCommitsBelowThreshold={hideCommitsBelowThreshold}157 isInspectingSelectedFiber={isInspectingSelectedFiber}158 selectedFiberID={selectedFiberID}159 selectedSnapshot={selectedSnapshot}160 selectSnapshot={selectSnapshot}161 snapshotIndex={snapshotIndex}162 snapshots={snapshots}163 theme={theme}164 />165 </Fragment>166 )}167 </Fragment>168 )}169 </div>170);171const HRule = ({ theme }) => (172 <div style={{173 height: '18px',174 width: '1px',175 backgroundColor: theme.base03,176 margin: '0px 0.5rem 0 0.25rem',177 }} />178);179type RadioOptionProps = {|180 icon: string,181 isChecked: boolean,182 isDisabled: boolean,183 label: string,184 isHovered: boolean,185 onChange: Function,186 onMouseEnter: Function,187 onMouseLeave: Function,188 theme: Theme,189 width: number,190|};191const RadioOption = Hoverable(({192 icon,193 isChecked,194 isDisabled = false,195 isHovered,196 label,197 onChange,198 onMouseEnter,199 onMouseLeave,200 theme,201 width,202}: RadioOptionProps) => (203 <label204 onMouseEnter={onMouseEnter}205 onMouseLeave={onMouseLeave}206 style={{207 color: isHovered ? theme.state06 : 'inherit',208 marginRight: '0.5rem',209 cursor: 'pointer',210 opacity: isDisabled ? 0.5 : 1,211 pointerEvents: isDisabled ? 'none' : 'auto',212 }}213 title={label}214 >215 <input216 disabled={isDisabled}217 type="radio"218 checked={isChecked}219 onChange={onChange}220 />221 <SvgIcon222 path={icon}223 style={{224 flex: '0 0 1rem',225 width: '1rem',226 height: '1rem',227 fill: 'currentColor',228 display: 'inline',229 verticalAlign: 'sub',230 margin: '0 0.25rem',231 }}232 />233 {width >= CHART_RADIO_LABEL_WIDTH_THRESHOLD && (234 <span>{label}</span>235 )}236 </label>237));238const RecordButton = Hoverable(239 ({ isActive, isHovered, onClick, onMouseEnter, onMouseLeave, theme }) => (240 <button241 onClick={onClick}242 onMouseEnter={onMouseEnter}243 onMouseLeave={onMouseLeave}244 style={{245 background: 'none',246 border: 'none',247 outline: 'none',248 cursor: 'pointer',249 color: isActive250 ? theme.special03251 : isHovered ? theme.state06 : theme.base05,252 filter: isActive253 ? `drop-shadow( 0 0 2px ${theme.special03} )`254 : 'none',255 padding: '4px',256 }}257 title={isActive ? 'Stop profiling' : 'Start profiling'}258 >259 <SvgIcon260 path={Icons.RECORD}261 style={{262 flex: '0 0 1rem',263 width: '1rem',264 height: '1rem',265 fill: 'currentColor',266 display: 'inline',267 verticalAlign: 'sub',268 }}269 />270 </button>271 )...
FiberRenderDurations.js
Source:FiberRenderDurations.js
...165 height={safeHeight}166 isDimmed={node.parentSnapshot === selectedSnapshot}167 key={index}168 label={`${node.value.toFixed(1)}ms`}169 onClick={() => selectSnapshot(node.parentSnapshot)}170 onDoubleClick={stopInspecting}171 title={`${node.value.toFixed(3)}ms`}172 width={width}173 x={left}174 y={height - safeHeight}175 />176 );177 }178}179const getChartData = memoize((180 nodeID: string,181 snapshots: Array<Snapshot>,182 width: number183): ChartData => {...
index.jsx
Source:index.jsx
1import React, { Component } from 'react'2import { get, set } from 'lodash'3import { ScrollLoad } from 'components/Base'4import { toJS } from 'mobx'5import { observer } from 'mobx-react'6import { AccessModes } from 'components/Inputs'7import classNames from 'classnames'8import { Form, Icon, Loading } from '@kube-design/components'9import PropTypes from 'prop-types'10import SnapshotStore from 'stores/volumeSnapshot'11import StorageClassStore from 'stores/storageClass'12import { safeParseJSON } from 'utils'13import { ACCESS_MODES } from 'utils/constants'14import styles from './index.scss'15@observer16export default class SanpshotForm extends Component {17 snapshotStore = new SnapshotStore()18 storageClassStore = new StorageClassStore()19 static contextTypes = {20 formData: PropTypes.object,21 }22 componentDidMount() {23 if (this.storageClassName) {24 this.fetchStorageClassDetail()25 }26 }27 get storageClassName() {28 return get(this.context.formData, 'spec.storageClassName')29 }30 get supportedAccessModes() {31 return safeParseJSON(32 get(33 this.storageClassStore.detail,34 'annotations["storageclass.kubesphere.io/supported-access-modes"]',35 ''36 )37 )38 }39 fetchSnapshots = (params = { limit: 10 }) => {40 const { namespace, cluster } = this.props41 this.snapshotStore42 .fetchList({43 ...params,44 namespace,45 cluster,46 status: 'ready',47 })48 .then(() => {49 const { data } = this.snapshotStore.list50 const name = get(data, '[0].name')51 if (name) {52 set(this.context.formData, 'spec.dataSource.name', name)53 this.handeSnapshotChange(name)54 }55 })56 }57 fetchStorageClassDetail = () => {58 if (59 this.storageClassName &&60 this.storageClassName !== this.storageClassStore.detail.name61 ) {62 this.storageClassStore.fetchDetail({63 cluster: this.props.cluster,64 name: this.storageClassName,65 })66 }67 }68 handeSnapshotChange = name => {69 const { data } = this.snapshotStore.list70 const selectSnapshot =71 toJS(data).find(snapshot => snapshot.name === name) || {}72 set(73 this.context.formData,74 'spec.resources.requests.storage',75 selectSnapshot.restoreSize76 )77 set(78 this.context.formData,79 'spec.storageClassName',80 selectSnapshot.snapshotClassName81 )82 set(this.context.formData, 'spec.dataSource.kind', 'VolumeSnapshot')83 set(84 this.context.formData,85 'spec.dataSource.apiGroup',86 'snapshot.storage.k8s.io'87 )88 this.fetchStorageClassDetail()89 }90 render() {91 const { data: snapshots, total, page, isLoading } = this.snapshotStore.list92 const { isLoading: isStorageClassLoading } = this.storageClassStore93 const supportedAccessModes = this.supportedAccessModes94 return (95 <>96 <Form.Item97 label={t('Volume Snapshot')}98 rules={[{ required: true, message: t('This param is required') }]}99 className={styles.snapshotContainer}100 >101 <SnapshotSelect102 className={styles.snapshots}103 name="spec.dataSource.name"104 snapshots={toJS(snapshots)}105 total={total}106 page={page}107 loading={isLoading}108 onChange={this.handeSnapshotChange}109 onFetch={this.fetchSnapshots}110 />111 </Form.Item>112 {this.storageClassName && (113 <Loading spinning={isStorageClassLoading}>114 <Form.Item115 className="margin-t12"116 label={t('Access Mode')}117 rules={[{ required: true, message: t('This param is required') }]}118 >119 <AccessModes120 name="spec.accessModes[0]"121 defaultValue={122 get(supportedAccessModes, '[0]') ||123 Object.keys(ACCESS_MODES)[0]124 }125 supportedAccessModes={supportedAccessModes}126 />127 </Form.Item>128 </Loading>129 )}130 </>131 )132 }133}134function SnapshotSelect({135 onChange,136 snapshots,137 total,138 page,139 loading,140 onFetch,141 value,142 className,143}) {144 return (145 <ScrollLoad146 className={className}147 data={snapshots}148 total={total}149 page={page}150 loading={loading}151 onFetch={onFetch}152 >153 {snapshots.map(snapshot => (154 <div155 className={classNames(156 {157 [styles.selected]: snapshot.name === value,158 },159 styles.snapshot160 )}161 key={snapshot.uid}162 onClick={() => onChange(snapshot.name)}163 >164 <Icon165 name={'snapshot'}166 type={snapshot.name === value ? 'light' : 'dark'}167 size={40}168 />169 <div>170 <h3>{snapshot.name}</h3>171 <p>{snapshot.snapshotClassName}</p>172 </div>173 <div>174 <h3>{snapshot.restoreSize || 0}</h3>175 <p>{t('Capacity')}</p>176 </div>177 <div>178 <h3>{snapshot.createTime}</h3>179 <p>{t('Created Time')}</p>180 </div>181 </div>182 ))}183 </ScrollLoad>184 )...
test_action-select-snapshot.js
Source:test_action-select-snapshot.js
1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3/**4 * Tests the reducer responding to the action `selectSnapshot(snapshot)`5 */6let actions = require("devtools/client/memory/actions/snapshot");7let { snapshotState: states } = require("devtools/client/memory/constants");8function run_test() {9 run_next_test();10}11add_task(function* () {12 let front = new StubbedMemoryFront();13 yield front.attach();14 let store = Store();15 for (let i = 0; i < 5; i++) {16 store.dispatch(actions.takeSnapshot(front));17 }18 yield waitUntilState(store, ({ snapshots }) => snapshots.length === 5 && snapshots.every(isDone));19 for (let i = 0; i < 5; i++) {20 do_print(`Selecting snapshot[${i}]`);21 store.dispatch(actions.selectSnapshot(store.getState().snapshots[i].id));22 yield waitUntilState(store, ({ snapshots }) => snapshots[i].selected);23 let { snapshots } = store.getState();24 ok(snapshots[i].selected, `snapshot[${i}] selected`);25 equal(snapshots.filter(s => !s.selected).length, 4, "All other snapshots are unselected");26 }27});...
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 const snapshot = await page.selectSnapshot('h1');7 const snapshotText = await snapshot.innerText();8 console.log(snapshotText);9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();
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.selectSnapshot({ name: 'mySnapshot' });7 await page.selectSnapshot({ name: 'mySnapshot' });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.selectSnapshot({ name: 'mySnapshot' });16 await page.selectSnapshot({ name: 'mySnapshot' });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.selectSnapshot({ name: 'mySnapshot' });25 await page.selectSnapshot({ name: 'mySnapshot' });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.selectSnapshot({ name: 'mySnapshot' });34 await page.selectSnapshot({ name: 'mySnapshot' });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.selectSnapshot({ name: 'mySnapshot' });43 await page.selectSnapshot({ name: 'mySnapshot' });44 await browser.close();45})();
Using AI Code Generation
1const { selectSnapshot } = require('playwright');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 page.waitForSelector('input[name="q"]');8 await selectSnapshot(page, 'snapshot1');9 await page.fill('input[name="q"]', 'Playwright');10 await selectSnapshot(page, 'snapshot2');11 await page.keyboard.press('Enter');12 await page.waitForSelector('text=Playwright');13 await selectSnapshot(page, 'snapshot3');14 await browser.close();15})();16const { selectSnapshot } = require('playwright');17const { chromium } = require('playwright');18describe('My test', () => {19 it('should work', async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.waitForSelector('input[name="q"]');24 await selectSnapshot(page, 'snapshot1');25 await page.fill('input[name="q"]', 'Playwright');26 await selectSnapshot(page, 'snapshot2');27 await page.keyboard.press('Enter');28 await page.waitForSelector('text=Playwright');29 await selectSnapshot(page, 'snapshot3');30 await browser.close();31 });32});33selectSnapshot(page: Page, name: string)
Using AI Code Generation
1const { selectSnapshot } = require('playwright-core/lib/server/snapshot/snapshotter');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const snapshot = await selectSnapshot(page, 'body', { timeout: 1000 });8 console.log(snapshot);9 await browser.close();10})();11{12 attributes: {
Using AI Code Generation
1const { selectSnapshot } = require('playwright');2const snapshot = await selectSnapshot(page, 'snapshotName');3await snapshot.restore();4await snapshot.take();5await snapshot.take('snapshotName');6await snapshot.take();7await snapshot.take('snapshotName');8await snapshot.take();9await snapshot.take('snapshotName');10await snapshot.take();11await snapshot.take('snapshotName');12await snapshot.take();13await snapshot.take('snapshotName');14await snapshot.take();15await snapshot.take('snapshotName');16await snapshot.take();17await snapshot.take('snapshotName');18await snapshot.take();19await snapshot.take('snapshotName');20await snapshot.take();21await snapshot.take('snapshotName');22await snapshot.take();23await snapshot.take('snapshotName');24await snapshot.take();25await snapshot.take('snapshotName');26await snapshot.take();27await snapshot.take('snapshotName');
Using AI Code Generation
1const { selectSnapshot } = require('playwright');2const snapshot = selectSnapshot('snapshotName');3const context = await browser.newContext({ snapshot });4const page = await context.newPage();5const { selectSnapshot } = require('playwright');6const snapshot = selectSnapshot('snapshotName');7const context = await browser.newContext({ snapshot });8const page = await context.newPage();9const { selectSnapshot } = require('playwright');10const snapshot = selectSnapshot('snapshotName');11const context = await browser.newContext({ snapshot });12const page = await context.newPage();13const { selectSnapshot } = require('playwright');14const snapshot = selectSnapshot('snapshotName');15const context = await browser.newContext({ snapshot });16const page = await context.newPage();17const { selectSnapshot } = require('playwright');18const snapshot = selectSnapshot('snapshotName');19const context = await browser.newContext({ snapshot });20const page = await context.newPage();21const { selectSnapshot } = require('playwright');22const snapshot = selectSnapshot('snapshotName');23const context = await browser.newContext({ snapshot });24const page = await context.newPage();25const { selectSnapshot } = require('playwright');26const snapshot = selectSnapshot('snapshotName');27const context = await browser.newContext({ snapshot });28const page = await context.newPage();29const { selectSnapshot } = require('playwright');30const snapshot = selectSnapshot('snapshotName');31const context = await browser.newContext({ snapshot });32const page = await context.newPage();33const { selectSnapshot } = require('playwright');34const snapshot = selectSnapshot('snapshotName');35const context = await browser.newContext({ snapshot });36const page = await context.newPage();37const { selectSnapshot } = require('playwright');38const snapshot = selectSnapshot('snapshotName');39const context = await browser.newContext({ snapshot });40const page = await context.newPage();
Using AI Code Generation
1const { selectSnapshot } = require('playwright');2(async () => {3 const { page } = await selectSnapshot('snapshot-1');4 await page.screenshot({ path: 'google.png' });5})();6{7 "scripts": {8 },9 "devDependencies": {10 }11}12const { selectSnapshot } = require('playwright');13(async () => {14 const { page } = await selectSnapshot('snapshot-2');15 await page.screenshot({ path: 'google.png' });16})();17const { selectSnapshot } = require('playwright');18(async () => {19 const { page } = await selectSnapshot('snapshot-1');20 await page.screenshot({ path: 'google.png' });21})();
Using AI Code Generation
1const { selectSnapshot } = require('playwright/lib/server/snapshotter/snapshotter');2(async () => {3 const snapshot = await selectSnapshot({4 viewport: { width: 1280, height: 720 },5 });6 console.log(snapshot);7})();8{
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright['chromium'].launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const snapshot = await page.selectSnapshot('.example');7 await snapshot.screenshot({ path: 'example.png' });8 await browser.close();9})();10const playwright = require('playwright');11(async () => {12 const browser = await playwright['chromium'].launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const snapshot = await page.selectSnapshot('.example');16 await snapshot.screenshot({ path: 'example.png' });17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright['chromium'].launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const snapshot = await page.selectSnapshot('.example');25 await snapshot.screenshot({ path: 'example.png' });26 await browser.close();27})();28const playwright = require('playwright');29(async () => {30 const browser = await playwright['chromium'].launch();31 const context = await browser.newContext();32 const page = await context.newPage();
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!!