Skip to content

Commit

Permalink
feat: Allow parsed selectors to be passed directly to functions (#418)
Browse files Browse the repository at this point in the history
  • Loading branch information
fb55 authored Apr 11, 2021
1 parent 047ad89 commit 01afada
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
7 changes: 4 additions & 3 deletions src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import type { CompiledQuery, InternalOptions } from "./types";
* @param context Optional context for the selector.
*/
export function compile<Node, ElementNode extends Node>(
selector: string,
selector: string | Selector[][],
options: InternalOptions<Node, ElementNode>,
context?: ElementNode[]
): CompiledQuery<ElementNode> {
Expand All @@ -27,11 +27,12 @@ export function compile<Node, ElementNode extends Node>(
}

export function compileUnsafe<Node, ElementNode extends Node>(
selector: string,
selector: string | Selector[][],
options: InternalOptions<Node, ElementNode>,
context?: ElementNode[] | ElementNode
): CompiledQuery<ElementNode> {
const token = parse(selector, options);
const token =
typeof selector === "string" ? parse(selector, options) : selector;
return compileToken<Node, ElementNode>(token, options, context);
}

Expand Down
5 changes: 4 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,10 @@ export interface CompiledQuery<ElementNode> {
(node: ElementNode): boolean;
shouldTestNextSiblings?: boolean;
}
export type Query<ElementNode> = string | CompiledQuery<ElementNode>;
export type Query<ElementNode> =
| string
| CompiledQuery<ElementNode>
| Selector[][];
export type CompileToken<Node, ElementNode extends Node> = (
token: InternalSelector[][],
options: InternalOptions<Node, ElementNode>,
Expand Down
21 changes: 19 additions & 2 deletions test/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,29 @@ describe("API", () => {
});
});

describe("can be queried by function", () => {
it("in `is`", () => {
describe("can be queried with more than a selector", () => {
it("function in `is`", () => {
expect(CSSselect.is(dom, (elem) => elem.attribs.id === "foo")).toBe(
true
);
});

it("parsed selector in `is`", () => {
expect(
CSSselect.is(dom, [
[
{
type: "attribute",
action: "equals",
ignoreCase: false,
name: "id",
namespace: null,
value: "foo",
},
],
])
).toBe(true);
});
// Probably more cases should be added here
});

Expand Down

0 comments on commit 01afada

Please sign in to comment.