Skip to main content

node_html_parser/css_select/
api.rs

1//! CSS selector public API functions.
2
3use super::legacy;
4use super::types::{Adapter, CompiledQuery, Options};
5use crate::{css_select::compile::compile_token as compile_token_impl, dom::element::HTMLElement};
6
7/// Select all elements matching the CSS selector.
8pub fn select_all<'a>(selector: &str, root: &'a HTMLElement) -> Vec<&'a HTMLElement> {
9	legacy::query_selector_all(root, selector)
10}
11
12/// Select the first element matching the CSS selector.
13pub fn select_one<'a>(selector: &str, root: &'a HTMLElement) -> Option<&'a HTMLElement> {
14	select_all(selector, root).into_iter().next()
15}
16
17/// Check if the element matches the CSS selector.
18pub fn is<'a>(elem: &'a HTMLElement, selector: &str, root: &'a HTMLElement) -> bool {
19	// naive: run full selection and pointer compare
20	let ptr = elem as *const HTMLElement;
21	select_all(selector, root)
22		.into_iter()
23		.any(|e| std::ptr::eq(e as *const HTMLElement, ptr))
24}
25
26/// Prepare selection context.
27pub fn prepare_context<'a>(root: &'a HTMLElement) -> Vec<&'a HTMLElement> {
28	vec![root]
29}
30
31/// Compile CSS selector with options and root element.
32pub fn compile<'a, A: Adapter>(
33	selector: &str,
34	options: &Options<A>,
35	root: &'a HTMLElement,
36) -> CompiledQuery<'a, A> {
37	compile_token_impl::<A>(selector, options, root)
38}
39
40/// Compile a CSS selector token.
41pub fn compile_token<'a, A: Adapter>(
42	selector: &str,
43	options: &Options<A>,
44	root: &'a HTMLElement,
45) -> CompiledQuery<'a, A> {
46	compile_token_impl::<A>(selector, options, root)
47}
48
49/// Compile CSS selector without safety checks.
50pub fn compile_unsafe<'a, A: Adapter>(
51	selector: &str,
52	options: &Options<A>,
53	root: &'a HTMLElement,
54) -> CompiledQuery<'a, A> {
55	compile_token_impl::<A>(selector, options, root)
56}
57
58/// Experimental internal compilation (convert + general).
59pub fn compile_experimental<'a, A: Adapter + 'a>(
60	selector: &str,
61	_options: &Options<A>,
62	adapter: &'a A,
63) -> CompiledQuery<'a, A> {
64	// 直接调用新管线;调用方需自行提供 adapter 实例 (例如 HtmlAdapter)。
65	crate::css_select::compile::compile_internal_new::<A>(selector, adapter)
66}