Skip to content

Commit

Permalink
Merge a755924 into c13f3e5
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 committed Jan 5, 2021
2 parents c13f3e5 + a755924 commit 18c9926
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
5 changes: 5 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ describe("index", () => {
expect(select("div", dom)).toHaveLength(1);
});

it("should find with a function", () => {
const dom = parseDOM("<div><p>First<p>Second") as Element[];
expect(select((elem) => elem.name === "p", dom)).toHaveLength(2);
});

it("should support positionals", () => {
const dom = parseDOM("<div><p>First<p>Second") as Element[];
expect(select("p:first", dom)).toMatchInlineSnapshot(`
Expand Down
28 changes: 25 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,14 @@ function filterParsed(
}

export function select(
selector: string,
selector: string | ((el: Element) => boolean),
root: Element | Element[],
options: Options = {}
): Element[] {
if (typeof selector === "function") {
return find(root, selector);
}

const [plain, filtered] = groupSelectors(parse(selector, options));

const results: Element[][] = filtered.map((sel) =>
Expand Down Expand Up @@ -276,6 +280,11 @@ function findFilterElements(
filterElements(result, [remainingSelector], remainingOpts);
}

interface CompiledQuery {
(el: Element): boolean;
shouldTestNextSiblings?: boolean;
}

function findElements(
root: Element | Element[],
sel: Selector[][],
Expand All @@ -284,8 +293,21 @@ function findElements(
): Element[] {
if (limit === 0) return [];

// @ts-expect-error TS seems to mess up the type here ¯\_(ツ)_/¯
const query = compileToken<Node, Element>(sel, options, root);
const query: CompiledQuery = compileToken<Node, Element>(
sel,
// @ts-expect-error TS seems to mess up the type here ¯\_(ツ)_/¯
options,
root
);

return find(root, query, limit);
}

function find(
root: Element | Element[],
query: CompiledQuery,
limit = Infinity
): Element[] {
const elems = prepareContext<Node, Element>(
root,
DomUtils,
Expand Down

0 comments on commit 18c9926

Please sign in to comment.