Skip to content

Commit

Permalink
src/node/selector.rs: revise Node::first_element_child
Browse files Browse the repository at this point in the history
  • Loading branch information
niklak committed Oct 23, 2024
1 parent 311220c commit ccb1901
Show file tree
Hide file tree
Showing 16 changed files with 84 additions and 84 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "dom_query"
version = "0.6.0"
version = "0.6.1"
description = "HTML querying and manipulations with CSS seletors"
license = "MIT"
repository = "https://github.com/niklak/dom_query"
Expand Down
4 changes: 2 additions & 2 deletions src/dom_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ impl<T: Debug> Tree<T> {
}

/// Gets the ancestors nodes of a node by id.
///
///
/// # Arguments
/// * `id` - The id of the node.
/// * `max_depth` - The maximum depth of the ancestors. If `None`, or Some(0) the maximum depth is unlimited.
///
///
/// # Returns
/// `Vec<NodeRef<T>>` A vector of ancestors nodes.
pub fn ancestors_of(&self, id: &NodeId, max_depth: Option<usize>) -> Vec<NodeRef<T>> {
Expand Down
40 changes: 20 additions & 20 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt;
use cssparser::{CowRcStr, ParseError, SourceLocation, ToCss};
use html5ever::Namespace;
use selectors::parser::{self, SelectorList, SelectorParseErrorKind};
use selectors::{matching,context, visitor, Element};
use selectors::{context, matching, visitor, Element};

use crate::css::{CssLocalName, CssString};
use crate::entities::NodeIdSet;
Expand Down Expand Up @@ -174,28 +174,28 @@ impl<'i> parser::Parser<'i> for InnerSelectorParser {
}

fn parse_non_ts_functional_pseudo_class<'t>(
&self,
name: CowRcStr<'i>,
parser: &mut cssparser::Parser<'i, 't>,
_after_part: bool,
) -> Result<<Self::Impl as parser::SelectorImpl>::NonTSPseudoClass, ParseError<'i, Self::Error>> {

if name.eq_ignore_ascii_case("has-text") {
&self,
name: CowRcStr<'i>,
parser: &mut cssparser::Parser<'i, 't>,
_after_part: bool,
) -> Result<<Self::Impl as parser::SelectorImpl>::NonTSPseudoClass, ParseError<'i, Self::Error>>
{
if name.eq_ignore_ascii_case("has-text") {
let s = parser.expect_string()?.as_ref();
Ok(NonTSPseudoClass::HasText(CssString::from(s)))
} else if name.eq_ignore_ascii_case("contains") {
{
let s = parser.expect_string()?.as_ref();
Ok(NonTSPseudoClass::HasText(CssString::from(s)))
} else if name.eq_ignore_ascii_case("contains") {
{
let s = parser.expect_string()?.as_ref();
Ok(NonTSPseudoClass::Contains(CssString::from(s)))
}
} else {
Err(parser.new_custom_error(
SelectorParseErrorKind::UnsupportedPseudoClassOrElement(name),
))
Ok(NonTSPseudoClass::Contains(CssString::from(s)))
}

} else {
Err(
parser.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClassOrElement(
name,
)),
)
}
}

}

#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down
11 changes: 7 additions & 4 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ pub(crate) fn children_of<T>(nodes: &Ref<Vec<InnerNode<T>>>, id: &NodeId) -> Vec
children
}

pub(crate) fn ancestors_of<T>(nodes: &Ref<Vec<InnerNode<T>>>, id: &NodeId, max_depth: Option<usize>) -> Vec<NodeId> {

let max_depth= max_depth.unwrap_or(0);
pub(crate) fn ancestors_of<T>(
nodes: &Ref<Vec<InnerNode<T>>>,
id: &NodeId,
max_depth: Option<usize>,
) -> Vec<NodeId> {
let max_depth = max_depth.unwrap_or(0);
let mut depth: usize = 0;

let mut ancestors = vec![];
Expand All @@ -62,4 +65,4 @@ pub(crate) fn ancestors_of<T>(nodes: &Ref<Vec<InnerNode<T>>>, id: &NodeId, max_d
}
}
ancestors
}
}
2 changes: 1 addition & 1 deletion src/node/node_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ impl Element {
!names.contains(&name_local)
});
}

/// Removes all attributes from the element.
pub fn remove_all_attrs(&mut self) {
self.attrs.clear();
Expand Down
28 changes: 22 additions & 6 deletions src/node/node_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,13 @@ impl<'a, T: Debug> NodeRef<'a, T> {
}

/// Returns ancestor nodes of the selected node.
///
///
/// # Arguments
/// * `max_depth` - The maximum depth of the ancestors. If `None`, or Some(0) the maximum depth is unlimited.
#[inline]
pub fn ancestors(&self, max_depth: Option<usize>) -> Vec<Self> {
self.tree.ancestors_of(&self.id, max_depth)
}


/// Returns the first child node of the selected node.
#[inline]
Expand Down Expand Up @@ -112,8 +111,8 @@ impl<'a, T: Debug> NodeRef<'a, T> {
self.tree.remove_children_of(&self.id)
}

/// Appends another node by id to the parent node of the selected node.
/// Another node takes place of the selected node.
/// Appends another node by id to the parent node of the selected node.
/// Another node takes place of the selected node.
#[inline]
pub fn append_prev_sibling(&self, id: &NodeId) {
self.tree.append_prev_sibling_of(&self.id, id)
Expand Down Expand Up @@ -159,7 +158,6 @@ impl<'a> Node<'a> {
}

impl<'a> Node<'a> {

/// Returns the next sibling, that is an [`crate::node::node_data::Element`] of the selected node.
pub fn next_element_sibling(&self) -> Option<Node<'a>> {
let nodes = self.tree.nodes.borrow();
Expand Down Expand Up @@ -195,10 +193,28 @@ impl<'a> Node<'a> {
};
r
}

/// Returns the first child, that is an [`crate::node::node_data::Element`] of the selected node.
pub fn first_element_child(&self) -> Option<Node<'a>> {
let nodes = self.tree.nodes.borrow();
if let Some(node) = nodes.get(self.id.value) {
let mut next_child_id = node.first_child;

while let Some(node_id) = next_child_id {
if node.is_element() {
return Some(NodeRef {
id: node_id,
tree: self.tree,
});
}
next_child_id = node.next_sibling;
}
}
None
}
}

impl<'a> Node<'a> {

/// Returns the name of the selected node if it is an [`crate::node::node_data::Element`] otherwise `None`.
pub fn node_name(&self) -> Option<StrTendril> {
let nodes = self.tree.nodes.borrow();
Expand Down
39 changes: 17 additions & 22 deletions src/node/selector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,14 @@ impl<'a> selectors::Element for Node<'a> {
false
}

fn has_custom_state(
&self,
_name: &<Self::Impl as SelectorImpl>::Identifier,
) -> bool {
fn has_custom_state(&self, _name: &<Self::Impl as SelectorImpl>::Identifier) -> bool {
false
}

// Converts self into an opaque representation.
/// Converts self into an opaque representation. It can be crucial.
#[inline]
fn opaque(&self) -> OpaqueElement {
let nodes =self.tree.nodes.borrow();
let nodes = self.tree.nodes.borrow();
let node = nodes.get(self.id.value).expect("element not in the tree!");
OpaqueElement::new(node)
}
Expand All @@ -40,31 +37,31 @@ impl<'a> selectors::Element for Node<'a> {
self.parent()
}

// Whether the parent node of this element is a shadow root.
/// Whether the parent node of this element is a shadow root.
#[inline]
fn parent_node_is_shadow_root(&self) -> bool {
false
}

// The host of the containing shadow root, if any.
/// The host of the containing shadow root, if any.
#[inline]
fn containing_shadow_host(&self) -> Option<Self> {
None
}

// Whether we're matching on a pseudo-element.
/// Whether we're matching on a pseudo-element.
#[inline]
fn is_pseudo_element(&self) -> bool {
false
}

// Skips non-element nodes.
/// Skips non-element nodes.
#[inline]
fn prev_sibling_element(&self) -> Option<Self> {
self.prev_element_sibling()
}

// Skips non-element nodes.
/// Skips non-element nodes.
#[inline]
fn next_sibling_element(&self) -> Option<Self> {
self.next_element_sibling()
Expand All @@ -90,7 +87,7 @@ impl<'a> selectors::Element for Node<'a> {
})
}

// Empty string for no namespace.
/// Empty string for no namespace.
#[inline]
fn has_namespace(&self, ns: &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl) -> bool {
self.query_or(false, |node| {
Expand All @@ -101,7 +98,7 @@ impl<'a> selectors::Element for Node<'a> {
})
}

// Whether this element and the `other` element have the same local name and namespace.
/// Whether this element and the `other` element have the same local name and namespace.
fn is_same_type(&self, other: &Self) -> bool {
//TODO: maybe we should unpack compare_node directly here
Expand Down Expand Up @@ -164,7 +161,7 @@ impl<'a> selectors::Element for Node<'a> {
false
}

// Whether this element is a `link`.
/// Whether this element is a `link`.
fn is_link(&self) -> bool {
self.query_or(false, |node| {
if let NodeData::Element(ref e) = node.data {
Expand All @@ -180,7 +177,7 @@ impl<'a> selectors::Element for Node<'a> {
})
}

// Whether the element is an HTML element.
/// Whether the element is an HTML element.
fn is_html_slot_element(&self) -> bool {
true
}
Expand Down Expand Up @@ -213,7 +210,7 @@ impl<'a> selectors::Element for Node<'a> {
})
}

// Returns the mapping from the `exportparts` attribute in the regular direction, that is, outer-tree->inner-tree.
/// Returns the mapping from the `exportparts` attribute in the regular direction, that is, outer-tree->inner-tree.
fn imported_part(&self, _name: &CssLocalName) -> Option<CssLocalName> {
None
}
Expand All @@ -222,24 +219,22 @@ impl<'a> selectors::Element for Node<'a> {
false
}

// Whether this element matches `:empty`.
/// Whether this element matches `:empty`.
fn is_empty(&self) -> bool {
!self
.children()
.iter()
.any(|child| child.is_element() || child.is_text())
}

// Whether this element matches `:root`, i.e. whether it is the root element of a document.
/// Whether this element matches `:root`, i.e. whether it is the root element of a document.
fn is_root(&self) -> bool {
self.is_document()
}

/// Returns the first element child. Skips non-element nodes.
fn first_element_child(&self) -> Option<Self> {
self.children()
.iter()
.find(|&child| child.is_element())
.cloned()
self.first_element_child()
}

fn apply_selector_flags(&self, _flags: ElementSelectorFlags) {}
Expand Down
2 changes: 1 addition & 1 deletion src/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tendril::StrTendril;
use crate::matcher::{MatchScope, Matcher, Matches};
use crate::Document;

use crate::node::{Node,NodeRef,NodeData};
use crate::node::{Node, NodeData, NodeRef};

/// Selection represents a collection of nodes matching some criteria. The
/// initial Selection object can be created by using [`crate::document::Document::select`], and then
Expand Down
2 changes: 1 addition & 1 deletion tests/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#[cfg(target_arch = "wasm32")]
#[global_allocator]
static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT;
static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT;
1 change: 0 additions & 1 deletion tests/data.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

#![allow(dead_code)]
use dom_query::Document;

Expand Down
1 change: 0 additions & 1 deletion tests/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use wasm_bindgen_test::*;

mod alloc;


const HTML_CONTENTS: &str = r#"<!DOCTYPE html>
<html>
<head><title>Test</title></head>
Expand Down
1 change: 0 additions & 1 deletion tests/pseudo-classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use wasm_bindgen_test::*;

mod alloc;


#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn pseudo_class_has() {
Expand Down
4 changes: 0 additions & 4 deletions tests/selection-manipulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use wasm_bindgen_test::*;

mod alloc;


#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_replace_with_html() {
Expand Down Expand Up @@ -75,9 +74,6 @@ fn test_replace_with_selection() {
s1.append_selection(&sel);
// after appending detached element, it can be matched
assert!(sel.is("#nf6"));



}

#[cfg_attr(not(target_arch = "wasm32"), test)]
Expand Down
1 change: 0 additions & 1 deletion tests/selection-property.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use wasm_bindgen_test::*;

mod alloc;


#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_attr_exists() {
Expand Down
1 change: 0 additions & 1 deletion tests/selection-query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use wasm_bindgen_test::*;

mod alloc;


#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_is() {
Expand Down
Loading

0 comments on commit ccb1901

Please sign in to comment.