Skip to content

Commit

Permalink
create ElementClass struct
Browse files Browse the repository at this point in the history
TODO: test struct methods, integration with Node and tests within Node
  • Loading branch information
Kiyoshika committed Oct 3, 2023
1 parent b56f51c commit fc1c0cc
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
target/
target/

# vim
*.swp*
*.swo*
54 changes: 54 additions & 0 deletions src/html5_parser/element_class.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use std::collections::HashMap;

pub struct ElementClass {
/// a map of classes applied to an HTML element.
/// key = name, value = is_active
/// the is_active is used to toggle a class (JavaScript API)
class_map: HashMap<String, bool>,
}

impl ElementClass {
/// Check if class name exists
pub fn contains(&self, name: &str) -> bool {
self.class_map.contains_key(name)
}

/// Add a new class (if already exists, does nothing)
pub fn add(&mut self, name: &str) -> () {
// by default, adding a new class will be active.
// however, map.insert will update a key if it exists
// and we don't want to overwrite an inactive class to make it active unintentionally
// so we ignore this operation if the class already exists
if !self.contains(name) {
self.class_map.insert(name.to_owned(), true);
}
}

/// Remove a class (does nothing if not exists)
pub fn remove(&mut self, name: &str) -> () {
self.class_map.remove(name);
}

/// Toggle a class active/inactive. Does nothing if class doesn't exist
pub fn toggle(&mut self, name: &str) {
if let Some(is_active) = self.class_map.get_mut(name) {
*is_active = !*is_active;
}
}

/// Set explicitly if a class is active or not. Does nothing if class doesn't exist
pub fn set_active(&mut self, name: &str, is_active: bool) -> () {
if let Some(is_active_item) = self.class_map.get_mut(name) {
*is_active_item = is_active;
}
}

/// Check if a class is active. Returns false if class doesn't exist
pub fn is_active(&self, name: &str) -> bool {
if let Some(is_active) = self.class_map.get(name) {
return *is_active;
}

return false;
}
}
2 changes: 2 additions & 0 deletions src/html5_parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ pub mod dom;
pub mod error_logger;
pub mod input_stream;

pub mod element_class;

mod node_arena;

0 comments on commit fc1c0cc

Please sign in to comment.