refactor(common): move actual constants (#7512)

The values of these constant variables are always the exact same when the `parseAriaSelector()` function is called, so these can be moved out of the function.
This commit is contained in:
Voltrex 2021-09-10 23:58:30 +04:30 committed by GitHub
parent 2aec35553b
commit f04ffdbe2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -37,6 +37,12 @@ async function queryAXTree(
return filteredNodes;
}
const normalizeValue = (value: string): string =>
value.replace(/ +/g, ' ').trim();
const knownAttributes = new Set(['name', 'role']);
const attributeRegexp =
/\[\s*(?<attribute>\w+)\s*=\s*"(?<value>\\.|[^"\\]*)"\s*\]/g;
/*
* The selectors consist of an accessible name to query for and optionally
* further aria attributes on the form `[<attribute>=<value>]`.
@ -49,23 +55,19 @@ async function queryAXTree(
*/
type ariaQueryOption = { name?: string; role?: string };
function parseAriaSelector(selector: string): ariaQueryOption {
const normalize = (value: string): string => value.replace(/ +/g, ' ').trim();
const knownAttributes = new Set(['name', 'role']);
const queryOptions: ariaQueryOption = {};
const attributeRegexp =
/\[\s*(?<attribute>\w+)\s*=\s*"(?<value>\\.|[^"\\]*)"\s*\]/g;
const defaultName = selector.replace(
attributeRegexp,
(_, attribute: string, value: string) => {
attribute = attribute.trim();
if (!knownAttributes.has(attribute))
throw new Error(`Unknown aria attribute "${attribute}" in selector`);
queryOptions[attribute] = normalize(value);
queryOptions[attribute] = normalizeValue(value);
return '';
}
);
if (defaultName && !queryOptions.name)
queryOptions.name = normalize(defaultName);
queryOptions.name = normalizeValue(defaultName);
return queryOptions;
}