Skip to content

🎥 Make videos programmatically with React

remove ariaqueryhandler

Jonny Burgerf01b8af1f275
diff --git a/packages/renderer/src/browser/AriaQueryHandler.ts b/packages/renderer/src/browser/AriaQueryHandler.ts
deleted file mode 100644
index b726f47932..0000000000
--- a/packages/renderer/src/browser/AriaQueryHandler.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * Copyright 2020 Google Inc. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import {Protocol} from 'devtools-protocol';
-import {assert} from './assert';
-import {CDPSession} from './Connection';
-import {DOMWorld, PageBinding, WaitForSelectorOptions} from './DOMWorld';
-import {ElementHandle, JSHandle} from './JSHandle';
-import {InternalQueryHandler} from './QueryHandler';
-
-async function queryAXTree(
- client: CDPSession,
- element: ElementHandle,
- accessibleName?: string,
- role?: string
-): Promise<Protocol.Accessibility.AXNode[]> {
- const {nodes} = await client.send('Accessibility.queryAXTree', {
- objectId: element._remoteObject.objectId,
- accessibleName,
- role,
- });
- const filteredNodes: Protocol.Accessibility.AXNode[] = nodes.filter(
- (node: Protocol.Accessibility.AXNode) => {
- return !node.role || node.role.value !== 'StaticText';
- }
- );
- return filteredNodes;
-}
-
-const normalizeValue = (value: string): string => {
- return value.replace(/ +/g, ' ').trim();
-};
-
-const knownAttributes = new Set(['name', 'role']);
-const attributeRegexp =
- /\[\s*(?<attribute>\w+)\s*=\s*(?<quote>"|')(?<value>\\.|.*?(?=\k<quote>))\k<quote>\s*\]/g;
-
-type ARIAQueryOption = {name?: string; role?: string};
-function isKnownAttribute(
- attribute: string
-): attribute is keyof ARIAQueryOption {
- return knownAttributes.has(attribute);
-}
-
-/*
- * The selectors consist of an accessible name to query for and optionally
- * further aria attributes on the form `[<attribute>=<value>]`.
- * Currently, we only support the `name` and `role` attribute.
- * The following examples showcase how the syntax works wrt. querying:
- * - 'title[role="heading"]' queries for elements with name 'title' and role 'heading'.
- * - '[role="img"]' queries for elements with role 'img' and any name.
- * - 'label' queries for elements with name 'label' and any role.
- * - '[name=""][role="button"]' queries for elements with no name and role 'button'.
- */
-function parseAriaSelector(selector: string): ARIAQueryOption {
- const queryOptions: ARIAQueryOption = {};
- const defaultName = selector.replace(
- attributeRegexp,
- (_, attribute: string, _quote: string, value: string) => {
- attribute = attribute.trim();
- assert(
- isKnownAttribute(attribute),
- `Unknown aria attribute "${attribute}" in selector`
- );
- queryOptions[attribute] = normalizeValue(value);
- return '';
- }
- );
- if (defaultName && !queryOptions.name) {
- queryOptions.name = normalizeValue(defaultName);
- }
-
- return queryOptions;
-}
-
-const queryOne = async (
- element: ElementHandle,
- selector: string
-): Promise<ElementHandle | null> => {
- const exeCtx = element.executionContext();
- const {name, role} = parseAriaSelector(selector);
- const res = await queryAXTree(exeCtx._client, element, name, role);
- if (!res[0] || !res[0].backendDOMNodeId) {
- return null;
- }
-
- return exeCtx._adoptBackendNodeId(res[0].backendDOMNodeId);
-};
-
-const waitFor = (
- domWorld: DOMWorld,
- selector: string,
- options: WaitForSelectorOptions
-): Promise<ElementHandle<Element> | null> => {
- const binding: PageBinding = {
- name: 'ariaQuerySelector',
- pptrFunction: async (_selector: string) => {
- const root = options.root || (await domWorld._document());
- const element = await queryOne(root, _selector);
- return element;
- },
- };
- return domWorld._waitForSelectorInPage(
- (_: Element, _selector: string) => {
- return (
- globalThis as any as unknown as {
- ariaQuerySelector(selector: string): void;
- }
- ).ariaQuerySelector(_selector);
- },
- selector,
- options,
- binding
- );
-};
-
-const queryAll = async (
- element: ElementHandle,
- selector: string
-): Promise<ElementHandle[]> => {
- const exeCtx = element.executionContext();
- const {name, role} = parseAriaSelector(selector);
- const res = await queryAXTree(exeCtx._client, element, name, role);
- return Promise.all(
- res.map((axNode) => {
- return exeCtx._adoptBackendNodeId(axNode.backendDOMNodeId);
- })
- );
-};
-
-const queryAllArray = async (
- element: ElementHandle,
- selector: string
-): Promise<JSHandle> => {
- const elementHandles = await queryAll(element, selector);
- const exeCtx = element.executionContext();
- const jsHandle = exeCtx.evaluateHandle((...elements) => {
- return elements;
- }, ...elementHandles);
- return jsHandle;
-};
-
-/**
- * @internal
- */
-export const _ariaHandler: InternalQueryHandler = {
- queryOne,
- waitFor,
- queryAll,
- queryAllArray,
-};
diff --git a/packages/renderer/src/browser/DOMWorld.ts b/packages/renderer/src/browser/DOMWorld.ts
index 54697ee64e..4fbd41e37b 100644
--- a/packages/renderer/src/browser/DOMWorld.ts
+++ b/packages/renderer/src/browser/DOMWorld.ts
@@ -24,14 +24,11 @@ import {
EvaluateHandleFn,
SerializableOrJSHandle,
UnwrapPromiseLike,
- WrapElementHandle,
} from './EvalTypes';
import {ExecutionContext} from './ExecutionContext';
import {Frame, FrameManager} from './FrameManager';
-import {MouseButton} from './Input';
import {ElementHandle, JSHandle} from './JSHandle';
import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher';
-import {_getQueryHandlerAndSelector} from './QueryHandler';
import {TimeoutSettings} from './TimeoutSettings';
import {
debugError,
@@ -205,14 +202,6 @@ export class DOMWorld {
);
}
- async $<T extends Element = Element>(
- selector: string
- ): Promise<ElementHandle<T> | null> {
- const document = await this._document();
- const value = await document.$<T>(selector);
- return value;
- }
-
/**
* @internal
*/
@@ -239,43 +228,6 @@ export class DOMWorld {
return value;
}
- async $eval<ReturnType>(
- selector: string,
- pageFunction: (
- element: Element,
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- const document = await this._document();
- return document.$eval<ReturnType>(selector, pageFunction, ...args);
- }
-
- async $$eval<ReturnType>(
- selector: string,
- pageFunction: (
- elements: Element[],
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- const document = await this._document();
- const value = await document.$$eval<ReturnType>(
- selector,
- pageFunction,
- ...args
- );
- return value;
- }
-
- async $$<T extends Element = Element>(
- selector: string
- ): Promise<Array<ElementHandle<T>>> {
- const document = await this._document();
- const value = await document.$$<T>(selector);
- return value;
- }
-
async content(): Promise<string> {
return await this.evaluate(() => {
let retVal = '';
@@ -568,66 +520,6 @@ export class DOMWorld {
}
}
- async click(
- selector: string,
- options: {delay?: number; button?: MouseButton; clickCount?: number}
- ): Promise<void> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- await handle.click(options);
- await handle.dispose();
- }
-
- async focus(selector: string): Promise<void> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- await handle.focus();
- await handle.dispose();
- }
-
- async hover(selector: string): Promise<void> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- await handle.hover();
- await handle.dispose();
- }
-
- async select(selector: string, ...values: string[]): Promise<string[]> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- const result = await handle.select(...values);
- await handle.dispose();
- return result;
- }
-
- async tap(selector: string): Promise<void> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- await handle.tap();
- await handle.dispose();
- }
-
- async type(
- selector: string,
- text: string,
- options?: {delay: number}
- ): Promise<void> {
- const handle = await this.$(selector);
- assert(handle, `No element found for selector: ${selector}`);
- await handle.type(text, options);
- await handle.dispose();
- }
-
- async waitForSelector(
- selector: string,
- options: WaitForSelectorOptions
- ): Promise<ElementHandle | null> {
- const {updatedSelector, queryHandler} =
- _getQueryHandlerAndSelector(selector);
- assert(queryHandler.waitFor, 'Query handler does not support waiting');
- return queryHandler.waitFor(this, updatedSelector, options);
- }
-
// If multiple waitFor are set up asynchronously, we need to wait for the
// first one to set up the binding in the page before running the others.
#settingUpBinding: Promise<void> | null = null;
diff --git a/packages/renderer/src/browser/FrameManager.ts b/packages/renderer/src/browser/FrameManager.ts
index 0f463ea79b..5c27b94cf8 100644
--- a/packages/renderer/src/browser/FrameManager.ts
+++ b/packages/renderer/src/browser/FrameManager.ts
@@ -24,12 +24,10 @@ import {
EvaluateHandleFn,
SerializableOrJSHandle,
UnwrapPromiseLike,
- WrapElementHandle,
} from './EvalTypes';
import {EventEmitter} from './EventEmitter';
import {EVALUATION_SCRIPT_URL, ExecutionContext} from './ExecutionContext';
import {HTTPResponse} from './HTTPResponse';
-import {MouseButton} from './Input';
import {ElementHandle, JSHandle} from './JSHandle';
import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher';
import {NetworkManager} from './NetworkManager';
@@ -38,7 +36,6 @@ import {TimeoutSettings} from './TimeoutSettings';
import {debugError, isErrorLike, isNumber, isString} from './util';
const UTILITY_WORLD_NAME = '__puppeteer_utility_world__';
-const xPathPattern = /^\(\/\/[^\)]+\)|^\/\//;
/**
* We use symbols to prevent external parties listening to these events.
@@ -936,19 +933,6 @@ export class Frame {
return this._mainWorld.evaluate<T>(pageFunction, ...args);
}
- /**
- * This method queries the frame for the given selector.
- *
- * @param selector - a selector to query for.
- * @returns A promise which resolves to an `ElementHandle` pointing at the
- * element, or `null` if it was not found.
- */
- async $<T extends Element = Element>(
- selector: string
- ): Promise<ElementHandle<T> | null> {
- return this._mainWorld.$<T>(selector);
- }
-
/**
* This method evaluates the given XPath expression and returns the results.
*
@@ -958,78 +942,6 @@ export class Frame {
return this._mainWorld.$x(expression);
}
- /**
- * @remarks
- *
- * This method runs `document.querySelector` within
- * the frame and passes it as the first argument to `pageFunction`.
- *
- * If `pageFunction` returns a Promise, then `frame.$eval` would wait for
- * the promise to resolve and return its value.
- *
- * @example
- *
- * ```js
- * const searchValue = await frame.$eval('#search', el => el.value);
- * ```
- *
- * @param selector - the selector to query for
- * @param pageFunction - the function to be evaluated in the frame's context
- * @param args - additional arguments to pass to `pageFunction`
- */
- async $eval<ReturnType>(
- selector: string,
- pageFunction: (
- element: Element,
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- return this._mainWorld.$eval<ReturnType>(selector, pageFunction, ...args);
- }
-
- /**
- * @remarks
- *
- * This method runs `Array.from(document.querySelectorAll(selector))` within
- * the frame and passes it as the first argument to `pageFunction`.
- *
- * If `pageFunction` returns a Promise, then `frame.$$eval` would wait for
- * the promise to resolve and return its value.
- *
- * @example
- *
- * ```js
- * const divsCounts = await frame.$$eval('div', divs => divs.length);
- * ```
- *
- * @param selector - the selector to query for
- * @param pageFunction - the function to be evaluated in the frame's context
- * @param args - additional arguments to pass to `pageFunction`
- */
- async $$eval<ReturnType>(
- selector: string,
- pageFunction: (
- elements: Element[],
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- return this._mainWorld.$$eval<ReturnType>(selector, pageFunction, ...args);
- }
-
- /**
- * This runs `document.querySelectorAll` in the frame and returns the result.
- *
- * @param selector - a selector to search for
- * @returns An array of element handles pointing to the found frame elements.
- */
- async $$<T extends Element = Element>(
- selector: string
- ): Promise<Array<ElementHandle<T>>> {
- return this._mainWorld.$$<T>(selector);
- }
-
/**
* @returns the full HTML contents of the frame, including the doctype.
*/
@@ -1125,140 +1037,6 @@ export class Frame {
return this._mainWorld.addStyleTag(options);
}
- /**
- *
- * This method clicks the first element found that matches `selector`.
- *
- * @remarks
- *
- * This method scrolls the element into view if needed, and then uses
- * {@link Page.mouse} to click in the center of the element. If there's no
- * element matching `selector`, the method throws an error.
- *
- * Bear in mind that if `click()` triggers a navigation event and there's a
- * separate `page.waitForNavigation()` promise to be resolved, you may end up
- * with a race condition that yields unexpected results. The correct pattern
- * for click and wait for navigation is the following:
- *
- * ```javascript
- * const [response] = await Promise.all([
- * page.waitForNavigation(waitOptions),
- * frame.click(selector, clickOptions),
- * ]);
- * ```
- * @param selector - the selector to search for to click. If there are
- * multiple elements, the first will be clicked.
- */
- async click(
- selector: string,
- options: {
- delay?: number;
- button?: MouseButton;
- clickCount?: number;
- } = {}
- ): Promise<void> {
- return this._secondaryWorld.click(selector, options);
- }
-
- /**
- * This method fetches an element with `selector` and focuses it.
- *
- * @remarks
- * If there's no element matching `selector`, the method throws an error.
- *
- * @param selector - the selector for the element to focus. If there are
- * multiple elements, the first will be focused.
- */
- async focus(selector: string): Promise<void> {
- return this._secondaryWorld.focus(selector);
- }
-
- /**
- * This method fetches an element with `selector`, scrolls it into view if
- * needed, and then uses {@link Page.mouse} to hover over the center of the
- * element.
- *
- * @remarks
- * If there's no element matching `selector`, the method throws an
- *
- * @param selector - the selector for the element to hover. If there are
- * multiple elements, the first will be hovered.
- */
- async hover(selector: string): Promise<void> {
- return this._secondaryWorld.hover(selector);
- }
-
- /**
- * Triggers a `change` and `input` event once all the provided options have
- * been selected.
- *
- * @remarks
- *
- * If there's no `<select>` element matching `selector`, the
- * method throws an error.
- *
- * @example
- * ```js
- * frame.select('select#colors', 'blue'); // single selection
- * frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections
- * ```
- *
- * @param selector - a selector to query the frame for
- * @param values - an array of values to select. If the `<select>` has the
- * `multiple` attribute, all values are considered, otherwise only the first
- * one is taken into account.
- * @returns the list of values that were successfully selected.
- */
- select(selector: string, ...values: string[]): Promise<string[]> {
- return this._secondaryWorld.select(selector, ...values);
- }
-
- /**
- * This method fetches an element with `selector`, scrolls it into view if
- * needed, and then uses {@link Page.touchscreen} to tap in the center of the
- * element.
- *
- * @remarks
- *
- * If there's no element matching `selector`, the method throws an error.
- *
- * @param selector - the selector to tap.
- * @returns a promise that resolves when the element has been tapped.
- */
- async tap(selector: string): Promise<void> {
- return this._secondaryWorld.tap(selector);
- }
-
- /**
- * Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character
- * in the text.
- *
- * @remarks
- * To press a special key, like `Control` or `ArrowDown`, use
- * {@link Keyboard.press}.
- *
- * @example
- * ```js
- * await frame.type('#mytextarea', 'Hello'); // Types instantly
- * await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user
- * ```
- *
- * @param selector - the selector for the element to type into. If there are
- * multiple the first will be used.
- * @param text - text to type into the element
- * @param options - takes one option, `delay`, which sets the time to wait
- * between key presses in milliseconds. Defaults to `0`.
- *
- * @returns a promise that resolves when the typing is complete.
- */
- async type(
- selector: string,
- text: string,
- options?: {delay: number}
- ): Promise<void> {
- return this._mainWorld.type(selector, text, options);
- }
-
/**
* @remarks
*
@@ -1294,17 +1072,12 @@ export class Frame {
);
if (isString(selectorOrFunctionOrTimeout)) {
- const string = selectorOrFunctionOrTimeout;
- if (xPathPattern.test(string)) {
- return this.waitForXPath(string, options);
- }
-
- return this.waitForSelector(string, options);
+ throw new Error('wait for selector not supported');
}
if (isNumber(selectorOrFunctionOrTimeout)) {
return new Promise((fulfill) => {
- return setTimeout(fulfill, selectorOrFunctionOrTimeout);
+ setTimeout(fulfill, selectorOrFunctionOrTimeout);
});
}
@@ -1347,59 +1120,6 @@ export class Frame {
});
}
- /**
- * @remarks
- *
- *
- * Wait for the `selector` to appear in page. If at the moment of calling the
- * method the `selector` already exists, the method will return immediately.
- * If the selector doesn't appear after the `timeout` milliseconds of waiting,
- * the function will throw.
- *
- * This method works across navigations.
- *
- * @example
- * ```js
- * const puppeteer = require('puppeteer');
- *
- * (async () => {
- * const browser = await puppeteer.launch();
- * const page = await browser.newPage();
- * let currentURL;
- * page.mainFrame()
- * .waitForSelector('img')
- * .then(() => console.log('First URL with image: ' + currentURL));
- *
- * for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
- * await page.goto(currentURL);
- * }
- * await browser.close();
- * })();
- * ```
- * @param selector - the selector to wait for.
- * @param options - options to define if the element should be visible and how
- * long to wait before timing out.
- * @returns a promise which resolves when an element matching the selector
- * string is added to the DOM.
- */
- async waitForSelector(
- selector: string,
- options: WaitForSelectorOptions = {}
- ): Promise<ElementHandle | null> {
- const handle = await this._secondaryWorld.waitForSelector(
- selector,
- options
- );
- if (!handle) {
- return null;
- }
-
- const mainExecutionContext = await this._mainWorld.executionContext();
- const result = await mainExecutionContext._adoptElementHandle(handle);
- await handle.dispose();
- return result;
- }
-
/**
* @remarks
* Wait for the `xpath` to appear in page. If at the moment of calling the
diff --git a/packages/renderer/src/browser/JSHandle.ts b/packages/renderer/src/browser/JSHandle.ts
index 6820a29756..959287711f 100644
--- a/packages/renderer/src/browser/JSHandle.ts
+++ b/packages/renderer/src/browser/JSHandle.ts
@@ -23,13 +23,11 @@ import {
EvaluateHandleFn,
SerializableOrJSHandle,
UnwrapPromiseLike,
- WrapElementHandle,
} from './EvalTypes';
import {ExecutionContext} from './ExecutionContext';
import {Frame, FrameManager} from './FrameManager';
import {MouseButton} from './Input';
import {Page, ScreenshotOptions} from './Page';
-import {_getQueryHandlerAndSelector} from './QueryHandler';
import {KeyInput} from './USKeyboardLayout';
import {
debugError,
@@ -388,63 +386,6 @@ export class ElementHandle<
this.#frameManager = frameManager;
}
- /**
- * Wait for the `selector` to appear within the element. If at the moment of calling the
- * method the `selector` already exists, the method will return immediately. If
- * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
- * function will throw.
- *
- * This method does not work across navigations or if the element is detached from DOM.
- *
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * of an element to wait for
- * @param options - Optional waiting parameters
- * @returns Promise which resolves when element specified by selector string
- * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
- * selector is not found in DOM.
- * @remarks
- * The optional parameters in `options` are:
- *
- * - `visible`: wait for the selected element to be present in DOM and to be
- * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
- * properties. Defaults to `false`.
- *
- * - `hidden`: wait for the selected element to not be found in the DOM or to be hidden,
- * i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
- * `false`.
- *
- * - `timeout`: maximum time to wait in milliseconds. Defaults to `30000`
- * (30 seconds). Pass `0` to disable timeout. The default value can be changed
- * by using the {@link Page.setDefaultTimeout} method.
- */
- async waitForSelector(
- selector: string,
- options: {
- visible?: boolean;
- hidden?: boolean;
- timeout?: number;
- } = {}
- ): Promise<ElementHandle | null> {
- const frame = this._context.frame();
- assert(frame);
- const secondaryContext = await frame._secondaryWorld.executionContext();
- const adoptedRoot = await secondaryContext._adoptElementHandle(this);
- const handle = await frame._secondaryWorld.waitForSelector(selector, {
- ...options,
- root: adoptedRoot,
- });
- await adoptedRoot.dispose();
- if (!handle) {
- return null;
- }
-
- const mainExecutionContext = await frame._mainWorld.executionContext();
- const result = await mainExecutionContext._adoptElementHandle(handle);
- await handle.dispose();
- return result;
- }
-
/**
* Wait for the `xpath` within the element. If at the moment of calling the
* method the `xpath` already exists, the method will return immediately. If
@@ -1145,144 +1086,6 @@ export class ElementHandle<
return imageData;
}
- /**
- * Runs `element.querySelector` within the page.
- *
- * @param selector - The selector to query with.
- * @returns `null` if no element matches the selector.
- * @throws `Error` if the selector has no associated query handler.
- */
- async $<T extends Element = Element>(
- selector: string
- ): Promise<ElementHandle<T> | null> {
- const {updatedSelector, queryHandler} =
- _getQueryHandlerAndSelector(selector);
- assert(
- queryHandler.queryOne,
- 'Cannot handle queries for a single element with the given selector'
- );
- return queryHandler.queryOne(this, updatedSelector);
- }
-
- /**
- * Runs `element.querySelectorAll` within the page. If no elements match the selector,
- * the return value resolves to `[]`.
- */
- /**
- * Runs `element.querySelectorAll` within the page.
- *
- * @param selector - The selector to query with.
- * @returns `[]` if no element matches the selector.
- * @throws `Error` if the selector has no associated query handler.
- */
- async $$<T extends Element = Element>(
- selector: string
- ): Promise<Array<ElementHandle<T>>> {
- const {updatedSelector, queryHandler} =
- _getQueryHandlerAndSelector(selector);
- assert(
- queryHandler.queryAll,
- 'Cannot handle queries for a multiple element with the given selector'
- );
- return queryHandler.queryAll(this, updatedSelector);
- }
-
- /**
- * This method runs `document.querySelector` within the element and passes it as
- * the first argument to `pageFunction`. If there's no element matching `selector`,
- * the method throws an error.
- *
- * If `pageFunction` returns a Promise, then `frame.$eval` would wait for the promise
- * to resolve and return its value.
- *
- * @example
- * ```js
- * const tweetHandle = await page.$('.tweet');
- * expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
- * expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
- * ```
- */
- async $eval<ReturnType>(
- selector: string,
- pageFunction: (
- element: Element,
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- const elementHandle = await this.$(selector);
- if (!elementHandle) {
- throw new Error(
- `Error: failed to find element matching selector "${selector}"`
- );
- }
-
- const result = await elementHandle.evaluate<
- (
- element: Element,
- ...args: SerializableOrJSHandle[]
- ) => ReturnType | Promise<ReturnType>
- >(pageFunction, ...args);
- await elementHandle.dispose();
-
- /**
- * This `as` is a little unfortunate but helps TS understand the behavior of
- * `elementHandle.evaluate`. If evaluate returns an element it will return an
- * ElementHandle instance, rather than the plain object. All the
- * WrapElementHandle type does is wrap ReturnType into
- * ElementHandle<ReturnType> if it is an ElementHandle, or leave it alone as
- * ReturnType if it isn't.
- */
- return result as WrapElementHandle<ReturnType>;
- }
-
- /**
- * This method runs `document.querySelectorAll` within the element and passes it as
- * the first argument to `pageFunction`. If there's no element matching `selector`,
- * the method throws an error.
- *
- * If `pageFunction` returns a Promise, then `frame.$$eval` would wait for the
- * promise to resolve and return its value.
- *
- * @example
- * ```html
- * <div class="feed">
- * <div class="tweet">Hello!</div>
- * <div class="tweet">Hi!</div>
- * </div>
- * ```
- *
- * @example
- * ```js
- * const feedHandle = await page.$('.feed');
- * expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText)))
- * .toEqual(['Hello!', 'Hi!']);
- * ```
- */
- async $$eval<ReturnType>(
- selector: string,
- pageFunction: EvaluateFn<
- Element[],
- unknown,
- ReturnType | Promise<ReturnType>
- >,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- const {updatedSelector, queryHandler} =
- _getQueryHandlerAndSelector(selector);
- assert(queryHandler.queryAllArray);
- const arrayHandle = await queryHandler.queryAllArray(this, updatedSelector);
- const result = await arrayHandle.evaluate<EvaluateFn<Element[]>>(
- pageFunction,
- ...args
- );
- await arrayHandle.dispose();
- /* This `as` exists for the same reason as the `as` in $eval above.
- * See the comment there for a full explanation.
- */
- return result as WrapElementHandle<ReturnType>;
- }
-
/**
* The method evaluates the XPath expression relative to the elementHandle.
* If there are no such elements, the method will resolve to an empty array.
diff --git a/packages/renderer/src/browser/Page.ts b/packages/renderer/src/browser/Page.ts
index b30375262d..f96d630535 100644
--- a/packages/renderer/src/browser/Page.ts
+++ b/packages/renderer/src/browser/Page.ts
@@ -29,14 +29,13 @@ import {
EvaluateHandleFn,
SerializableOrJSHandle,
UnwrapPromiseLike,
- WrapElementHandle,
} from './EvalTypes';
import {EventEmitter, Handler} from './EventEmitter';
import {FileChooser} from './FileChooser';
import {Frame, FrameManager, FrameManagerEmittedEvents} from './FrameManager';
import {HTTPRequest} from './HTTPRequest';
import {HTTPResponse} from './HTTPResponse';
-import {Keyboard, Mouse, MouseButton, Touchscreen} from './Input';
+import {Keyboard, Mouse, Touchscreen} from './Input';
import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle';
import {PuppeteerLifeCycleEvent} from './LifecycleWatcher';
import {
@@ -994,23 +993,6 @@ export class Page extends EventEmitter {
this.#timeoutSettings.setDefaultTimeout(timeout);
}
- /**
- * Runs `document.querySelector` within the page. If no element matches the
- * selector, the return value resolves to `null`.
- *
- * @remarks
- * Shortcut for {@link Frame.$ | Page.mainFrame().$(selector) }.
- *
- * @param selector - A `selector` to query page for
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * to query page for.
- */
- async $<T extends Element = Element>(
- selector: string
- ): Promise<ElementHandle<T> | null> {
- return this.mainFrame().$<T>(selector);
- }
-
/**
* @remarks
*
@@ -1100,175 +1082,6 @@ export class Page extends EventEmitter {
return context.queryObjects(prototypeHandle);
}
- /**
- * This method runs `document.querySelector` within the page and passes the
- * result as the first argument to the `pageFunction`.
- *
- * @remarks
- *
- * If no element is found matching `selector`, the method will throw an error.
- *
- * If `pageFunction` returns a promise `$eval` will wait for the promise to
- * resolve and then return its value.
- *
- * @example
- *
- * ```
- * const searchValue = await page.$eval('#search', el => el.value);
- * const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
- * const html = await page.$eval('.main-container', el => el.outerHTML);
- * ```
- *
- * If you are using TypeScript, you may have to provide an explicit type to the
- * first argument of the `pageFunction`.
- * By default it is typed as `Element`, but you may need to provide a more
- * specific sub-type:
- *
- * @example
- *
- * ```
- * // if you don't provide HTMLInputElement here, TS will error
- * // as `value` is not on `Element`
- * const searchValue = await page.$eval('#search', (el: HTMLInputElement) => el.value);
- * ```
- *
- * The compiler should be able to infer the return type
- * from the `pageFunction` you provide. If it is unable to, you can use the generic
- * type to tell the compiler what return type you expect from `$eval`:
- *
- * @example
- *
- * ```
- * // The compiler can infer the return type in this case, but if it can't
- * // or if you want to be more explicit, provide it as the generic type.
- * const searchValue = await page.$eval<string>(
- * '#search', (el: HTMLInputElement) => el.value
- * );
- * ```
- *
- * @param selector - the
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * to query for
- * @param pageFunction - the function to be evaluated in the page context.
- * Will be passed the result of `document.querySelector(selector)` as its
- * first argument.
- * @param args - any additional arguments to pass through to `pageFunction`.
- *
- * @returns The result of calling `pageFunction`. If it returns an element it
- * is wrapped in an {@link ElementHandle}, else the raw value itself is
- * returned.
- */
- async $eval<ReturnType>(
- selector: string,
- pageFunction: (
- element: Element,
- /* Unfortunately this has to be unknown[] because it's hard to get
- * TypeScript to understand that the arguments will be left alone unless
- * they are an ElementHandle, in which case they will be unwrapped.
- * The nice thing about unknown vs any is that unknown will force the user
- * to type the item before using it to avoid errors.
- *
- * TODO(@jackfranklin): We could fix this by using overloads like
- * DefinitelyTyped does:
- * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/HEAD/types/puppeteer/index.d.ts#L114
- */
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- return this.mainFrame().$eval<ReturnType>(selector, pageFunction, ...args);
- }
-
- /**
- * This method runs `Array.from(document.querySelectorAll(selector))` within
- * the page and passes the result as the first argument to the `pageFunction`.
- *
- * @remarks
- *
- * If `pageFunction` returns a promise `$$eval` will wait for the promise to
- * resolve and then return its value.
- *
- * @example
- *
- * ```
- * // get the amount of divs on the page
- * const divCount = await page.$$eval('div', divs => divs.length);
- *
- * // get the text content of all the `.options` elements:
- * const options = await page.$$eval('div > span.options', options => {
- * return options.map(option => option.textContent)
- * });
- * ```
- *
- * If you are using TypeScript, you may have to provide an explicit type to the
- * first argument of the `pageFunction`.
- * By default it is typed as `Element[]`, but you may need to provide a more
- * specific sub-type:
- *
- * @example
- *
- * ```
- * // if you don't provide HTMLInputElement here, TS will error
- * // as `value` is not on `Element`
- * await page.$$eval('input', (elements: HTMLInputElement[]) => {
- * return elements.map(e => e.value);
- * });
- * ```
- *
- * The compiler should be able to infer the return type
- * from the `pageFunction` you provide. If it is unable to, you can use the generic
- * type to tell the compiler what return type you expect from `$$eval`:
- *
- * @example
- *
- * ```
- * // The compiler can infer the return type in this case, but if it can't
- * // or if you want to be more explicit, provide it as the generic type.
- * const allInputValues = await page.$$eval<string[]>(
- * 'input', (elements: HTMLInputElement[]) => elements.map(e => e.textContent)
- * );
- * ```
- *
- * @param selector - the
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * to query for
- * @param pageFunction - the function to be evaluated in the page context. Will
- * be passed the result of `Array.from(document.querySelectorAll(selector))`
- * as its first argument.
- * @param args - any additional arguments to pass through to `pageFunction`.
- *
- * @returns The result of calling `pageFunction`. If it returns an element it
- * is wrapped in an {@link ElementHandle}, else the raw value itself is
- * returned.
- */
- async $$eval<ReturnType>(
- selector: string,
- pageFunction: (
- elements: Element[],
- /* These have to be typed as unknown[] for the same reason as the $eval
- * definition above, please see that comment for more details and the TODO
- * that will improve things.
- */
- ...args: unknown[]
- ) => ReturnType | Promise<ReturnType>,
- ...args: SerializableOrJSHandle[]
- ): Promise<WrapElementHandle<ReturnType>> {
- return this.mainFrame().$$eval<ReturnType>(selector, pageFunction, ...args);
- }
-
- /**
- * The method runs `document.querySelectorAll` within the page. If no elements
- * match the selector, the return value resolves to `[]`.
- * @remarks
- * Shortcut for {@link Frame.$$ | Page.mainFrame().$$(selector) }.
- * @param selector - A `selector` to query page for
- */
- async $$<T extends Element = Element>(
- selector: string
- ): Promise<Array<ElementHandle<T>>> {
- return this.mainFrame().$$<T>(selector);
- }
-
/**
* The method evaluates the XPath expression relative to the page document as
* its context node. If there are no such elements, the method resolves to an
@@ -3091,146 +2904,6 @@ export class Page extends EventEmitter {
return this.#mouse;
}
- /**
- * This method fetches an element with `selector`, scrolls it into view if
- * needed, and then uses {@link Page.mouse} to click in the center of the
- * element. If there's no element matching `selector`, the method throws an
- * error.
- * @remarks Bear in mind that if `click()` triggers a navigation event and
- * there's a separate `page.waitForNavigation()` promise to be resolved, you
- * may end up with a race condition that yields unexpected results. The
- * correct pattern for click and wait for navigation is the following:
- * ```js
- * const [response] = await Promise.all([
- * page.waitForNavigation(waitOptions),
- * page.click(selector, clickOptions),
- * ]);
- * ```
- * Shortcut for {@link Frame.click | page.mainFrame().click(selector[, options]) }.
- * @param selector - A `selector` to search for element to click. If there are
- * multiple elements satisfying the `selector`, the first will be clicked
- * @param options - `Object`
- * @returns Promise which resolves when the element matching `selector` is
- * successfully clicked. The Promise will be rejected if there is no element
- * matching `selector`.
- */
- click(
- selector: string,
- options: {
- delay?: number;
- button?: MouseButton;
- clickCount?: number;
- } = {}
- ): Promise<void> {
- return this.mainFrame().click(selector, options);
- }
-
- /**
- * This method fetches an element with `selector` and focuses it. If there's no
- * element matching `selector`, the method throws an error.
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector }
- * of an element to focus. If there are multiple elements satisfying the
- * selector, the first will be focused.
- * @returns Promise which resolves when the element matching selector is
- * successfully focused. The promise will be rejected if there is no element
- * matching selector.
- * @remarks
- * Shortcut for {@link Frame.focus | page.mainFrame().focus(selector)}.
- */
- focus(selector: string): Promise<void> {
- return this.mainFrame().focus(selector);
- }
-
- /**
- * This method fetches an element with `selector`, scrolls it into view if
- * needed, and then uses {@link Page.mouse} to hover over the center of the element.
- * If there's no element matching `selector`, the method throws an error.
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * to search for element to hover. If there are multiple elements satisfying
- * the selector, the first will be hovered.
- * @returns Promise which resolves when the element matching `selector` is
- * successfully hovered. Promise gets rejected if there's no element matching
- * `selector`.
- * @remarks
- * Shortcut for {@link Page.hover | page.mainFrame().hover(selector)}.
- */
- hover(selector: string): Promise<void> {
- return this.mainFrame().hover(selector);
- }
-
- /**
- * Triggers a `change` and `input` event once all the provided options have been
- * selected. If there's no `<select>` element matching `selector`, the method
- * throws an error.
- *
- * @example
- * ```js
- * page.select('select#colors', 'blue'); // single selection
- * page.select('select#colors', 'red', 'green', 'blue'); // multiple selections
- * ```
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
- * to query the page for
- * @param values - Values of options to select. If the `<select>` has the
- * `multiple` attribute, all values are considered, otherwise only the first one
- * is taken into account.
- * @returns
- *
- * @remarks
- * Shortcut for {@link Frame.select | page.mainFrame().select()}
- */
- select(selector: string, ...values: string[]): Promise<string[]> {
- return this.mainFrame().select(selector, ...values);
- }
-
- /**
- * This method fetches an element with `selector`, scrolls it into view if
- * needed, and then uses {@link Page.touchscreen} to tap in the center of the element.
- * If there's no element matching `selector`, the method throws an error.
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | Selector}
- * to search for element to tap. If there are multiple elements satisfying the
- * selector, the first will be tapped.
- * @returns
- * @remarks
- * Shortcut for {@link Frame.tap | page.mainFrame().tap(selector)}.
- */
- tap(selector: string): Promise<void> {
- return this.mainFrame().tap(selector);
- }
-
- /**
- * Sends a `keydown`, `keypress/input`, and `keyup` event for each character
- * in the text.
- *
- * To press a special key, like `Control` or `ArrowDown`, use {@link Keyboard.press}.
- * @example
- * ```
- * await page.type('#mytextarea', 'Hello');
- * // Types instantly
- * await page.type('#mytextarea', 'World', { delay: 100 });
- * // Types slower, like a user
- * ```
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * of an element to type into. If there are multiple elements satisfying the
- * selector, the first will be used.
- * @param text - A text to type into a focused element.
- * @param options - have property `delay` which is the Time to wait between
- * key presses in milliseconds. Defaults to `0`.
- * @returns
- * @remarks
- */
- type(
- selector: string,
- text: string,
- options?: {delay: number}
- ): Promise<void> {
- return this.mainFrame().type(selector, text, options);
- }
-
/**
* @remarks
*
@@ -3296,65 +2969,6 @@ export class Page extends EventEmitter {
return this.mainFrame().waitForTimeout(milliseconds);
}
- /**
- * Wait for the `selector` to appear in page. If at the moment of calling the
- * method the `selector` already exists, the method will return immediately. If
- * the `selector` doesn't appear after the `timeout` milliseconds of waiting, the
- * function will throw.
- *
- * This method works across navigations:
- * ```js
- * const puppeteer = require('puppeteer');
- * (async () => {
- * const browser = await puppeteer.launch();
- * const page = await browser.newPage();
- * let currentURL;
- * page
- * .waitForSelector('img')
- * .then(() => console.log('First URL with image: ' + currentURL));
- * for (currentURL of [
- * 'https://example.com',
- * 'https://google.com',
- * 'https://bbc.com',
- * ]) {
- * await page.goto(currentURL);
- * }
- * await browser.close();
- * })();
- * ```
- * @param selector - A
- * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector}
- * of an element to wait for
- * @param options - Optional waiting parameters
- * @returns Promise which resolves when element specified by selector string
- * is added to DOM. Resolves to `null` if waiting for hidden: `true` and
- * selector is not found in DOM.
- * @remarks
- * The optional Parameter in Arguments `options` are :
- *
- * - `Visible`: A boolean wait for element to be present in DOM and to be
- * visible, i.e. to not have `display: none` or `visibility: hidden` CSS
- * properties. Defaults to `false`.
- *
- * - `hidden`: ait for element to not be found in the DOM or to be hidden,
- * i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to
- * `false`.
- *
- * - `timeout`: maximum time to wait for in milliseconds. Defaults to `30000`
- * (30 seconds). Pass `0` to disable timeout. The default value can be changed
- * by using the {@link Page.setDefaultTimeout} method.
- */
- waitForSelector(
- selector: string,
- options: {
- visible?: boolean;
- hidden?: boolean;
- timeout?: number;
- } = {}
- ): Promise<ElementHandle | null> {
- return this.mainFrame().waitForSelector(selector, options);
- }
-
/**
* Wait for the `xpath` to appear in page. If at the moment of calling the
* method the `xpath` already exists, the method will return immediately. If
diff --git a/packages/renderer/src/browser/Puppeteer.ts b/packages/renderer/src/browser/Puppeteer.ts
index 4ba6f774da..b3f0370c73 100644
--- a/packages/renderer/src/browser/Puppeteer.ts
+++ b/packages/renderer/src/browser/Puppeteer.ts
@@ -23,13 +23,6 @@ import {
PredefinedNetworkConditions,
} from './NetworkConditions';
import {Product} from './Product';
-import {
- CustomQueryHandler,
- _clearCustomQueryHandlers,
- _customQueryHandlerNames,
- _registerCustomQueryHandler,
- _unregisterCustomQueryHandler,
-} from './QueryHandler';
/**
* Settings that are common to the Puppeteer class, regardless of environment.
@@ -69,12 +62,6 @@ export class Puppeteer {
this._isPuppeteerCore = settings.isPuppeteerCore;
this.connect = this.connect.bind(this);
- this.registerCustomQueryHandler =
- this.registerCustomQueryHandler.bind(this);
- this.unregisterCustomQueryHandler =
- this.unregisterCustomQueryHandler.bind(this);
- this.customQueryHandlerNames = this.customQueryHandlerNames.bind(this);
- this.clearCustomQueryHandlers = this.clearCustomQueryHandlers.bind(this);
}
/**
@@ -164,46 +151,4 @@ export class Puppeteer {
get networkConditions(): PredefinedNetworkConditions {
return networkConditions;
}
-
- /**
- * Registers a {@link CustomQueryHandler | custom query handler}. After
- * registration, the handler can be used everywhere where a selector is
- * expected by prepending the selection string with `<name>/`. The name is
- * only allowed to consist of lower- and upper case latin letters.
- * @example
- * ```
- * puppeteer.registerCustomQueryHandler('text', { … });
- * const aHandle = await page.$('text/…');
- * ```
- * @param name - The name that the custom query handler will be registered under.
- * @param queryHandler - The {@link CustomQueryHandler | custom query handler} to
- * register.
- */
- registerCustomQueryHandler(
- name: string,
- queryHandler: CustomQueryHandler
- ): void {
- _registerCustomQueryHandler(name, queryHandler);
- }
-
- /**
- * @param name - The name of the query handler to unregistered.
- */
- unregisterCustomQueryHandler(name: string): void {
- _unregisterCustomQueryHandler(name);
- }
-
- /**
- * @returns a list with the names of all registered custom query handlers.
- */
- customQueryHandlerNames(): string[] {
- return _customQueryHandlerNames();
- }
-
- /**
- * Clears all registered handlers.
- */
- clearCustomQueryHandlers(): void {
- _clearCustomQueryHandlers();
- }
}
diff --git a/packages/renderer/src/browser/QueryHandler.ts b/packages/renderer/src/browser/QueryHandler.ts
deleted file mode 100644
index 6a72d889ad..0000000000
--- a/packages/renderer/src/browser/QueryHandler.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-/**
- * Copyright 2020 Google Inc. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import {_ariaHandler} from './AriaQueryHandler';
-import {DOMWorld, WaitForSelectorOptions} from './DOMWorld';
-import {ElementHandle, JSHandle} from './JSHandle';
-
-/**
- * @internal
- */
-export interface InternalQueryHandler {
- queryOne?: (
- element: ElementHandle,
- selector: string
- ) => Promise<ElementHandle | null>;
- waitFor?: (
- domWorld: DOMWorld,
- selector: string,
- options: WaitForSelectorOptions
- ) => Promise<ElementHandle | null>;
- queryAll?: (
- element: ElementHandle,
- selector: string
- ) => Promise<ElementHandle[]>;
- queryAllArray?: (
- element: ElementHandle,
- selector: string
- ) => Promise<JSHandle<Element[]>>;
-}
-
-/**
- * Contains two functions `queryOne` and `queryAll` that can
- * be {@link Puppeteer.registerCustomQueryHandler | registered}
- * as alternative querying strategies. The functions `queryOne` and `queryAll`
- * are executed in the page context. `queryOne` should take an `Element` and a
- * selector string as argument and return a single `Element` or `null` if no
- * element is found. `queryAll` takes the same arguments but should instead
- * return a `NodeListOf<Element>` or `Array<Element>` with all the elements
- * that match the given query selector.
- * @public
- */
-export interface CustomQueryHandler {
- queryOne?: (element: Element | Document, selector: string) => Element | null;
- queryAll?: (
- element: Element | Document,
- selector: string
- ) => Element[] | NodeListOf<Element>;
-}
-
-function makeQueryHandler(handler: CustomQueryHandler): InternalQueryHandler {
- const internalHandler: InternalQueryHandler = {};
-
- if (handler.queryOne) {
- const {queryOne} = handler;
- internalHandler.queryOne = async (element, selector) => {
- const jsHandle = await element.evaluateHandle(queryOne, selector);
- const elementHandle = jsHandle.asElement();
- if (elementHandle) {
- return elementHandle;
- }
-
- await jsHandle.dispose();
- return null;
- };
-
- internalHandler.waitFor = (
- domWorld: DOMWorld,
- selector: string,
- options: WaitForSelectorOptions
- ) => {
- return domWorld._waitForSelectorInPage(queryOne, selector, options);
- };
- }
-
- if (handler.queryAll) {
- const {queryAll} = handler;
- internalHandler.queryAll = async (element, selector) => {
- const jsHandle = await element.evaluateHandle(queryAll, selector);
- const properties = await jsHandle.getProperties();
- await jsHandle.dispose();
- const result = [];
- for (const property of properties.values()) {
- const elementHandle = property.asElement();
- if (elementHandle) {
- result.push(elementHandle);
- }
- }
-
- return result;
- };
-
- internalHandler.queryAllArray = async (element, selector) => {
- const resultHandle = await element.evaluateHandle(queryAll, selector);
- const arrayHandle = await resultHandle.evaluateHandle(
- (res: Element[] | NodeListOf<Element>) => {
- return Array.from(res);
- }
- );
- return arrayHandle;
- };
- }
-
- return internalHandler;
-}
-
-const _defaultHandler = makeQueryHandler({
- queryOne: (element: Element | Document, selector: string) => {
- return element.querySelector(selector);
- },
- queryAll: (element: Element | Document, selector: string) => {
- return element.querySelectorAll(selector);
- },
-});
-
-const pierceHandler = makeQueryHandler({
- queryOne: (element, selector) => {
- let found: Element | null = null;
- const search = (root: Element | ShadowRoot) => {
- const iter = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
- do {
- const currentNode = iter.currentNode as HTMLElement;
- if (currentNode.shadowRoot) {
- search(currentNode.shadowRoot);
- }
-
- if (currentNode instanceof ShadowRoot) {
- continue;
- }
-
- if (currentNode !== root && !found && currentNode.matches(selector)) {
- found = currentNode;
- }
- } while (!found && iter.nextNode());
- };
-
- if (element instanceof Document) {
- element = element.documentElement;
- }
-
- search(element);
- return found;
- },
-
- queryAll: (element, selector) => {
- const result: Element[] = [];
- const collect = (root: Element | ShadowRoot) => {
- const iter = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
- do {
- const currentNode = iter.currentNode as HTMLElement;
- if (currentNode.shadowRoot) {
- collect(currentNode.shadowRoot);
- }
-
- if (currentNode instanceof ShadowRoot) {
- continue;
- }
-
- if (currentNode !== root && currentNode.matches(selector)) {
- result.push(currentNode);
- }
- } while (iter.nextNode());
- };
-
- if (element instanceof Document) {
- element = element.documentElement;
- }
-
- collect(element);
- return result;
- },
-});
-
-const builtInHandlers = new Map([
- ['aria', _ariaHandler],
- ['pierce', pierceHandler],
-]);
-const queryHandlers = new Map(builtInHandlers);
-
-/**
- * @internal
- */
-export function _registerCustomQueryHandler(
- name: string,
- handler: CustomQueryHandler
-): void {
- if (queryHandlers.get(name)) {
- throw new Error(`A custom query handler named "${name}" already exists`);
- }
-
- const isValidName = /^[a-zA-Z]+$/.test(name);
- if (!isValidName) {
- throw new Error(`Custom query handler names may only contain [a-zA-Z]`);
- }
-
- const internalHandler = makeQueryHandler(handler);
-
- queryHandlers.set(name, internalHandler);
-}
-
-/**
- * @internal
- */
-export function _unregisterCustomQueryHandler(name: string): void {
- if (queryHandlers.has(name) && !builtInHandlers.has(name)) {
- queryHandlers.delete(name);
- }
-}
-
-/**
- * @internal
- */
-export function _customQueryHandlerNames(): string[] {
- return [...queryHandlers.keys()].filter((name) => {
- return !builtInHandlers.has(name);
- });
-}
-
-/**
- * @internal
- */
-export function _clearCustomQueryHandlers(): void {
- _customQueryHandlerNames().forEach(_unregisterCustomQueryHandler);
-}
-
-/**
- * @internal
- */
-export function _getQueryHandlerAndSelector(selector: string): {
- updatedSelector: string;
- queryHandler: InternalQueryHandler;
-} {
- const hasCustomQueryHandler = /^[a-zA-Z]+\//.test(selector);
- if (!hasCustomQueryHandler) {
- return {updatedSelector: selector, queryHandler: _defaultHandler};
- }
-
- const index = selector.indexOf('/');
- const name = selector.slice(0, index);
- const updatedSelector = selector.slice(index + 1);
- const queryHandler = queryHandlers.get(name);
- if (!queryHandler) {
- throw new Error(
- `Query set to use "${name}", but no query handler of that name was found`
- );
- }
-
- return {
- updatedSelector,
- queryHandler,
- };
-}