Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/adblocker-extended-selectors/src/eval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

import { classifySelector, SelectorType } from './extended.js';
import type { AST, Complex, PseudoClass } from './types.js';

const createXpathExpression = (function () {
Expand All @@ -23,6 +24,26 @@ const createXpathExpression = (function () {
};
})();

const cachedIsExtended = (function () {
const extended: string[] = [];
const standard: string[] = [];

return function classify(selector: string) {
if (extended.includes(selector)) {
return true;
}
if (standard.includes(selector)) {
return false;
}
if (classifySelector(selector) === SelectorType.Extended) {
extended.push(selector);
return true;
}
standard.push(selector);
return false;
};
})();

/**
* Evaluates an XPath expression and returns matching Element nodes.
* @param element - The context element for XPath evaluation
Expand Down Expand Up @@ -365,6 +386,11 @@ function transpose(element: Element, selector: AST): Element[] | null {
return [parentElement];
}
}
} else if (cachedIsExtended(argument) === false) {
const closest = element.closest(argument);
if (closest !== null) {
return [closest];
}
} else {
while ((parentElement = parentElement.parentElement) !== null) {
if (parentElement.matches(argument)) {
Expand Down
Loading