File size: 8,948 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { Locator, Page, Frame } from 'playwright';
import envVariables from './env-variables';

const coreNavTabParent = 'div.components-tab-panel__tabs';
const calypsoNavTabParent = 'div.section-nav';

const selectors = {
	// clickNavTab
	navTabItem: ( {
		name = '',
		selected = false,
		isCoreTabs = false,
	}: { name?: string; selected?: boolean; isCoreTabs?: boolean } = {} ) =>
		! isCoreTabs || envVariables.VIEWPORT_NAME === 'mobile'
			? `${ calypsoNavTabParent } a[aria-current="${ selected }"]:has(span:has-text("${ name }"))`
			: `${ coreNavTabParent } button[aria-selected="${ selected }"]:has-text("${ name }")`,
	navTabMobileToggleButton: `${ calypsoNavTabParent } button.section-nav__mobile-header`,
};

/**
 * Waits for the element specified by the selector to become enabled.
 *
 * There are two definitions of disabled on wp-calypso:
 * 		- traditional: set the `disabled` property on element.
 * 		- aria: using the `aria-disabled` attribute.
 *
 * Playwright's `isEnabled` method does not look into `aria-disabled = "true"` when determining
 * actionability. This means test steps may fail if it depends on the built-in `isEnabled` to
 * assert actionability.
 *
 * This function will check for both the`disabled` property and `aria-disabled="false"` attributes
 * to determine whether the element is enabled.
 *
 * @param {Page} page Page object.
 * @param {string} selector Selector of the target element.
 * @param {{[key: string]: number}} options Object parameter.
 * @param {number} options.timeout Timeout to override the default value.
 */
export async function waitForElementEnabled(
	page: Page,
	selector: string,
	options?: { timeout?: number }
) {
	const elementHandle = await page.waitForSelector( selector, options );
	await Promise.all( [
		elementHandle.waitForElementState( 'enabled', options ),
		page.waitForFunction(
			( element: SVGElement | HTMLElement ) => element.ariaDisabled !== 'true',
			elementHandle
		),
	] );

	return elementHandle;
}

/**
 * Locates and clicks on a specified tab on the NavTab.
 *
 * NavTabs are used throughout calypso to contain sub-pages within the parent page.
 * For instance, on the Media gallery page a NavTab is used to filter the gallery to
 * show a specific category of gallery items.
 *
 * @param {Page} page Underlying page on which interactions take place.
 * @param {string} name Name of the tab to be clicked.
 * @throws {Error} If the tab name is not the active tab.
 */
export async function clickNavTab(
	page: Page,
	name: string,
	{ force, isCoreTabs = false }: { force?: boolean; isCoreTabs?: boolean } = {}
): Promise< void > {
	// Short circuit operation if the active tab and target tabs are the same.
	// Strip numerals from the extracted tab name to account for the slightly
	// different implementation in PostsPage.
	const selectedTabLocator = page.locator( selectors.navTabItem( { selected: true, isCoreTabs } ) );
	const selectedTabName = await selectedTabLocator.innerText();
	if ( selectedTabName.replace( /[0-9]|,/g, '' ) === name ) {
		return;
	}

	// If force option is specified, force click using a `dispatchEvent`.
	if ( force ) {
		return await page.dispatchEvent( selectors.navTabItem( { name: name, isCoreTabs } ), 'click' );
	}

	// Mobile view - navtabs become a dropdown and thus it must be opened first.
	if ( envVariables.VIEWPORT_NAME === 'mobile' ) {
		// Open the Navtabs which now act as a pseudo-dropdown menu.
		const navTabsButtonLocator = page.locator( selectors.navTabMobileToggleButton );
		await navTabsButtonLocator.click( { noWaitAfter: true } );

		const navTabIsOpenLocator = page.locator( `${ calypsoNavTabParent }.is-open` );
		await navTabIsOpenLocator.waitFor();
	}

	// Click on the intended item and wait for navigation to finish.
	const navTabItem = page.locator(
		selectors.navTabItem( { name: name, selected: false, isCoreTabs } )
	);

	const regex = new RegExp( `.*/${ name.toLowerCase() }/.*` );
	await Promise.all( [ page.waitForURL( regex ), navTabItem.click() ] );

	// Final verification, check that we are now on the expected navtab.
	const newSelectedTabLocator = page.locator(
		selectors.navTabItem( { name: name, selected: true, isCoreTabs } )
	);
	const newSelectedTabName = await newSelectedTabLocator.innerText();

	if ( newSelectedTabName.replace( /[0-9]|,/g, '' ) !== name ) {
		throw new Error(
			`Failed to confirm NavTab is active: expected ${ name }, got ${ newSelectedTabName }`
		);
	}
}

/**
 * Retry any function up to three times or action passes without throwing an exception,
 * whichever comes first.
 *
 * The function being passed in must throw an exception for this retry to work.
 *
 * This is useful for situations where the backend must process the results of a
 * previous action then inform the front end of the result of the process.
 * An example of this is the user invitation system where the backend must receive,
 * verify and send the invitation issued by a user. If the resulting checks were
 * successful, the resulting invitation is shown as 'pending'.
 *
 * @param {Page} page Page object.
 */
export async function reloadAndRetry(
	page: Page,
	func: ( page: Page ) => Promise< void >
): Promise< void > {
	for ( let retries = 3; retries > 0; retries -= 1 ) {
		try {
			return await func( page );
		} catch ( err ) {
			// Throw the error if final retry failed.
			if ( retries === 1 ) {
				throw err;
			} else {
				await page.reload();
			}
		}
	}
	return;
}

/**
 * Gets and validates the block ID from a Locator to a parent Block element in the editor.
 *
 * @param {Locator} block A frame-safe Loccator to the top of a block.
 * @returns A block ID that can be used to identify the block in the DOM later.
 */
export async function getIdFromBlock( block: Locator ): Promise< string > {
	const blockId = await block.getAttribute( 'id' );
	const blockIdRegex = /^block-[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$/;
	if ( ! blockId || ! blockIdRegex.test( blockId ) ) {
		throw new Error( `Unable to find valid block ID from Locator. ID was "${ blockId }"` );
	}

	return blockId;
}

/**
 * Waits until DOM mutations for given target element become idle. Can be used
 * in situations where Playwright auto-waiting is not working for some reason.
 *
 * @example
 * await Promise.all( [
 *   waitForMutations( page, '.foobars-wrapper' ),
 *   page.click( 'button.load-foobars' ),
 * ] );
 * const foobarsText = await page.innerText( '.foobars' );
 * @param {Page} page Page object.
 * @param {string} selector Observer target selector.
 * @param {Object} options
 * @param {number} options.timeout Maximum time in milliseconds, defaults to 10
 * seconds, pass 0 to disable timeout.
 * @param {number} options.debounce Maximum time to wait between consecutive
 * mutations, defaults to 1 second.
 * @param {Object} options.observe Mutation observation options.
 */
export async function waitForMutations(
	page: Page | Frame,
	selector: string,
	options?: {
		timeout?: number;
		debounce?: number;
		observe?: MutationObserverInit;
	}
): Promise< void > {
	const timeout = options?.timeout || 10000;
	const debounce = options?.debounce || 1000;
	const observe = options?.observe || { attributes: true, subtree: true, childList: true };
	const target = await page.waitForSelector( selector );

	await Promise.race( [
		new Promise( ( resolve, reject ) => {
			if ( timeout > 0 ) {
				setTimeout( () => {
					reject( `Waiting for ${ selector } mutations timed out.` );
				}, timeout );
			}
		} ),
		page.evaluate(
			async ( args ) => {
				await new Promise( ( resolve ) => {
					const debounceResolve = () => {
						let timer: NodeJS.Timeout;
						return () => {
							clearTimeout( timer );
							timer = setTimeout( resolve, args.debounce );
						};
					};

					const observer = new MutationObserver( debounceResolve() );
					observer.observe( args.target, args.observe );
				} );
			},
			{ target, debounce, observe }
		),
	] );
}

/**
 * Resolves once widgets.wp.com `message` events become idle or when no
 * `message` events are dispatched within the first 3 seconds. Once resolved,
 * all the widgets should be ready to be interacted with. This helper can be
 * used on Atomic sites where the iframed widgets have, e.g., custom resize
 * handlers (like the like button), causing layout shifting and, consequently,
 * Playwright's stability checks to fail.
 *
 * @param {Page} page The parent page object.
 */
export async function waitForWPWidgetsIfNecessary( page: Page ): Promise< void > {
	await page.evaluate( async () => {
		await new Promise( ( resolve ) => {
			let timer: NodeJS.Timeout;
			const setResolveTimer = ( delay: number ) => {
				clearTimeout( timer );
				timer = setTimeout( resolve, delay );
			};

			setResolveTimer( 3000 );

			window.addEventListener( 'message', ( event ) => {
				if ( event.origin === 'https://widgets.wp.com' ) {
					setResolveTimer( 1000 );
				}
			} );
		} );
	} );
}