1use std::borrow::Borrow;
34use std::fmt;
35
36use cssparser::{ToCss, serialize_identifier};
37use precomputed_hash::PrecomputedHash;
38use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
39use selectors::bloom::{BLOOM_HASH_MASK, BloomFilter};
40use selectors::matching::{ElementSelectorFlags, MatchingContext};
41use selectors::parser::{NonTSPseudoClass, PseudoElement as PseudoElementTrait, SelectorImpl};
42use selectors::{Element, OpaqueElement};
43
44use crate::content::{Alignment, Attributes, Block, Book, Inline, ListItem, NodeId, Row};
45
46#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
53pub struct Atom(pub String);
54
55impl From<&str> for Atom {
56 fn from(value: &str) -> Self {
57 Atom(value.to_string())
58 }
59}
60
61impl From<String> for Atom {
62 fn from(value: String) -> Self {
63 Atom(value)
64 }
65}
66
67impl Borrow<str> for Atom {
68 fn borrow(&self) -> &str {
69 &self.0
70 }
71}
72
73impl ToCss for Atom {
74 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
75 serialize_identifier(&self.0, dest)
76 }
77}
78
79impl PrecomputedHash for Atom {
80 fn precomputed_hash(&self) -> u32 {
81 fnv(&self.0)
82 }
83}
84
85fn fnv(name: &str) -> u32 {
88 let mut hash = 0x811c_9dc5u32;
89 for byte in name.as_bytes() {
90 hash ^= *byte as u32;
91 hash = hash.wrapping_mul(0x0100_0193);
92 }
93 hash
94}
95
96#[derive(Clone, Debug, Eq, PartialEq)]
100pub enum PseudoClass {}
101
102impl ToCss for PseudoClass {
103 fn to_css<W: fmt::Write>(&self, _dest: &mut W) -> fmt::Result {
104 match *self {}
105 }
106}
107
108impl NonTSPseudoClass for PseudoClass {
109 type Impl = Fleuron;
110
111 fn is_active_or_hover(&self) -> bool {
112 match *self {}
113 }
114
115 fn is_user_action_state(&self) -> bool {
116 match *self {}
117 }
118}
119
120pub use crate::content::PseudoElement;
121
122impl ToCss for PseudoElement {
123 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
124 match self {
125 PseudoElement::FirstLetter => dest.write_str("::first-letter"),
126 PseudoElement::FirstLine => dest.write_str("::first-line"),
127 PseudoElement::Before => dest.write_str("::before"),
128 PseudoElement::After => dest.write_str("::after"),
129 }
130 }
131}
132
133pub const INLINE_ELEMENTS: [&str; 7] = ["code", "em", "strong", "a", "s", "mark", "span"];
137
138pub const BLOCK_ELEMENTS: [&str; 16] = [
140 "section",
141 "h1",
142 "h2",
143 "h3",
144 "h4",
145 "h5",
146 "h6",
147 "p",
148 "blockquote",
149 "pre",
150 "hr",
151 "img",
152 "ul",
153 "ol",
154 "li",
155 "table",
156];
157
158impl PseudoElementTrait for PseudoElement {
159 type Impl = Fleuron;
160}
161
162#[derive(Clone, Debug, Eq, PartialEq)]
164pub struct Fleuron;
165
166impl SelectorImpl for Fleuron {
167 type ExtraMatchingData<'a> = std::marker::PhantomData<&'a ()>;
168 type AttrValue = Atom;
169 type Identifier = Atom;
170 type LocalName = Atom;
171 type NamespaceUrl = Atom;
172 type NamespacePrefix = Atom;
173 type BorrowedLocalName = Atom;
174 type BorrowedNamespaceUrl = Atom;
175 type NonTSPseudoClass = PseudoClass;
176 type PseudoElement = PseudoElement;
177}
178
179pub const ELEMENTS: [&str; 31] = [
183 "book",
184 "section",
185 "notes",
186 "note",
187 "h1",
188 "h2",
189 "h3",
190 "h4",
191 "h5",
192 "h6",
193 "p",
194 "blockquote",
195 "pre",
196 "hr",
197 "img",
198 "ul",
199 "ol",
200 "li",
201 "table",
202 "thead",
203 "tbody",
204 "tr",
205 "th",
206 "td",
207 "code",
208 "em",
209 "strong",
210 "a",
211 "s",
212 "mark",
213 "span",
214];
215
216fn past_last_id(book: &Book) -> u32 {
220 book.sections
221 .last()
222 .and_then(|section| book.subtree(section.id))
223 .map(|held| held.end)
224 .unwrap_or(1)
225}
226
227#[derive(Debug)]
230pub struct ElementNode {
231 pub name: &'static str,
233 pub id: NodeId,
235 pub attributes: Attributes,
237 pub parent: Option<usize>,
238 pub previous: Option<usize>,
239 pub next: Option<usize>,
240 pub first_child: Option<usize>,
241 pub has_text: bool,
243 pub align: Option<Alignment>,
246}
247
248#[derive(Debug, Default)]
251pub struct ElementTree {
252 nodes: Vec<ElementNode>,
253 anonymous: Vec<(NodeId, usize)>,
256 notes: NodeId,
259}
260
261impl ElementTree {
262 pub fn build(book: &Book) -> ElementTree {
265 let mut tree = ElementTree::default();
266 let root = tree.push(
267 "book",
268 NodeId::UNASSIGNED,
269 &Attributes::default(),
270 None,
271 false,
272 );
273 let sections: Vec<usize> = book
274 .sections
275 .iter()
276 .map(|section| {
277 let index = tree.push(
278 "section",
279 section.id,
280 §ion.attributes,
281 Some(root),
282 false,
283 );
284 let children = tree.blocks(§ion.blocks, index);
285 tree.link(index, &children);
286 index
287 })
288 .collect();
289 tree.link(root, §ions);
290 tree.notes = tree.area(root, past_last_id(book));
291 tree
292 }
293
294 fn area(&mut self, root: usize, past: u32) -> NodeId {
301 let id = NodeId::new(past);
302 self.push("notes", id, &Attributes::default(), Some(root), false);
303 id
304 }
305
306 pub fn notes(&self) -> NodeId {
308 self.notes
309 }
310
311 pub fn nodes(&self) -> &[ElementNode] {
313 &self.nodes
314 }
315
316 pub fn anonymous(&self) -> &[(NodeId, usize)] {
319 &self.anonymous
320 }
321
322 pub fn at(&self, index: usize) -> ElementRef<'_> {
324 ElementRef { tree: self, index }
325 }
326
327 fn blocks(&mut self, blocks: &[Block], parent: usize) -> Vec<usize> {
328 blocks
329 .iter()
330 .map(|block| match block {
331 Block::Heading {
332 id,
333 level,
334 inlines,
335 attributes,
336 ..
337 } => {
338 let name = match u8::from(*level) {
339 1 => "h1",
340 2 => "h2",
341 3 => "h3",
342 4 => "h4",
343 5 => "h5",
344 _ => "h6",
345 };
346 let index = self.push(name, *id, attributes, Some(parent), false);
347 let (children, has_text) = self.inlines(inlines, index);
348 self.link(index, &children);
349 self.nodes[index].has_text = has_text;
350 index
351 }
352 Block::Paragraph {
353 id,
354 inlines,
355 attributes,
356 ..
357 } => {
358 let index = self.push("p", *id, attributes, Some(parent), false);
359 let (children, has_text) = self.inlines(inlines, index);
360 self.link(index, &children);
361 self.nodes[index].has_text = has_text;
362 index
363 }
364 Block::Blockquote {
365 id,
366 blocks,
367 attributes,
368 ..
369 } => {
370 let index = self.push("blockquote", *id, attributes, Some(parent), false);
371 let children = self.blocks(blocks, index);
372 self.link(index, &children);
373 index
374 }
375 Block::CodeBlock {
376 id,
377 text,
378 attributes,
379 ..
380 } => self.push("pre", *id, attributes, Some(parent), !text.is_empty()),
381 Block::ThematicBreak { id, attributes, .. } => {
382 self.push("hr", *id, attributes, Some(parent), false)
383 }
384 Block::PageBreak { id, attributes, .. } => {
385 self.push("pagebreak", *id, attributes, Some(parent), false)
386 }
387 Block::ColumnBreak { id, attributes, .. } => {
388 self.push("columnbreak", *id, attributes, Some(parent), false)
389 }
390 Block::Image { id, attributes, .. } => {
391 self.push("img", *id, attributes, Some(parent), false)
392 }
393 Block::List {
394 id,
395 ordered,
396 tight,
397 items,
398 attributes,
399 ..
400 } => {
401 let name = if *ordered { "ol" } else { "ul" };
402 let index = self.push(name, *id, attributes, Some(parent), false);
403 let children = self.items(items, *tight, index);
404 self.link(index, &children);
405 index
406 }
407 Block::Table {
408 id,
409 head,
410 body,
411 attributes,
412 ..
413 } => {
414 let index = self.push("table", *id, attributes, Some(parent), false);
415 let mut groups = Vec::new();
416 for (group, rows, cell) in [("thead", head, "th"), ("tbody", body, "td")] {
417 if rows.is_empty() {
418 continue;
419 }
420 let at = self.push(
421 group,
422 NodeId::UNASSIGNED,
423 &Attributes::default(),
424 Some(index),
425 false,
426 );
427 let children = self.rows(rows, cell, at);
428 self.link(at, &children);
429 groups.push(at);
430 }
431 self.link(index, &groups);
432 index
433 }
434 })
435 .collect()
436 }
437
438 fn items(&mut self, items: &[ListItem], tight: bool, parent: usize) -> Vec<usize> {
441 let mut indices = Vec::with_capacity(items.len());
442 for item in items {
443 let index = self.push("li", item.id, &item.attributes, Some(parent), false);
444 let mut children = Vec::new();
445 for block in &item.blocks {
446 match block {
447 Block::Paragraph {
448 id,
449 inlines,
450 attributes,
451 ..
452 } if tight && attributes.is_empty() => {
453 let (inline, has_text) = self.inlines(inlines, index);
454 children.extend(inline);
455 self.nodes[index].has_text |= has_text;
456 self.anonymous.push((*id, index));
457 }
458 _ => children.extend(self.blocks(std::slice::from_ref(block), index)),
459 }
460 }
461 self.link(index, &children);
462 indices.push(index);
463 }
464 indices
465 }
466
467 fn rows(&mut self, rows: &[Row], cell: &'static str, parent: usize) -> Vec<usize> {
470 let mut indices = Vec::with_capacity(rows.len());
471 for row in rows {
472 let index = self.push("tr", row.id, &row.attributes, Some(parent), false);
473 let mut cells = Vec::with_capacity(row.cells.len());
474 for content in &row.cells {
475 let at = self.push(cell, content.id, &content.attributes, Some(index), false);
476 self.nodes[at].align = content.align;
477 let children = self.blocks(&content.blocks, at);
478 self.link(at, &children);
479 cells.push(at);
480 }
481 self.link(index, &cells);
482 indices.push(index);
483 }
484 indices
485 }
486
487 fn inlines(&mut self, inlines: &[Inline], parent: usize) -> (Vec<usize>, bool) {
490 let mut children = Vec::new();
491 let mut text = false;
492 for inline in inlines {
493 let (name, id, attributes, nested): (_, _, _, Option<&[Inline]>) = match inline {
494 Inline::Text { value, .. } => {
495 text |= !value.is_empty();
496 continue;
497 }
498 Inline::Break { .. } => continue,
499 Inline::Code {
500 id,
501 value,
502 attributes,
503 ..
504 } => {
505 let index = self.push("code", *id, attributes, Some(parent), !value.is_empty());
506 children.push(index);
507 continue;
508 }
509 Inline::Emphasis {
510 id,
511 children,
512 attributes,
513 ..
514 } => ("em", *id, attributes, Some(children)),
515 Inline::Strong {
516 id,
517 children,
518 attributes,
519 ..
520 } => ("strong", *id, attributes, Some(children)),
521 Inline::Link {
522 id,
523 children,
524 attributes,
525 ..
526 } => ("a", *id, attributes, Some(children)),
527 Inline::Strikethrough {
528 id,
529 children,
530 attributes,
531 ..
532 } => ("s", *id, attributes, Some(children)),
533 Inline::Highlight {
534 id,
535 children,
536 attributes,
537 ..
538 } => ("mark", *id, attributes, Some(children)),
539 Inline::Span {
540 id,
541 children,
542 attributes,
543 ..
544 } => ("span", *id, attributes, Some(children)),
545 Inline::Note {
548 id,
549 blocks,
550 attributes,
551 ..
552 } => {
553 let index = self.push("note", *id, attributes, Some(parent), false);
554 let kids = self.blocks(blocks, index);
555 self.link(index, &kids);
556 children.push(index);
557 continue;
558 }
559 };
560 let index = self.push(name, id, attributes, Some(parent), false);
561 if let Some(nested) = nested {
562 let (kids, has_text) = self.inlines(nested, index);
563 self.link(index, &kids);
564 self.nodes[index].has_text = has_text;
565 }
566 children.push(index);
567 }
568 (children, text)
569 }
570
571 fn push(
572 &mut self,
573 name: &'static str,
574 id: NodeId,
575 attributes: &Attributes,
576 parent: Option<usize>,
577 has_text: bool,
578 ) -> usize {
579 self.nodes.push(ElementNode {
580 name,
581 id,
582 attributes: attributes.clone(),
583 parent,
584 previous: None,
585 next: None,
586 first_child: None,
587 has_text,
588 align: None,
589 });
590 self.nodes.len() - 1
591 }
592
593 fn link(&mut self, parent: usize, children: &[usize]) {
596 self.nodes[parent].first_child = children.first().copied();
597 for (position, index) in children.iter().enumerate() {
598 self.nodes[*index].previous = position.checked_sub(1).map(|p| children[p]);
599 self.nodes[*index].next = children.get(position + 1).copied();
600 }
601 }
602}
603
604#[derive(Clone, Copy)]
606pub struct ElementRef<'a> {
607 tree: &'a ElementTree,
608 pub index: usize,
610}
611
612impl ElementRef<'_> {
613 fn node(&self) -> &ElementNode {
614 &self.tree.nodes[self.index]
615 }
616
617 fn sibling(&self, which: fn(&ElementNode) -> Option<usize>) -> Option<Self> {
618 which(self.node()).map(|index| ElementRef {
619 tree: self.tree,
620 index,
621 })
622 }
623}
624
625impl fmt::Debug for ElementRef<'_> {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 write!(f, "<{}>", self.node().name)
628 }
629}
630
631impl Element for ElementRef<'_> {
632 type Impl = Fleuron;
633
634 fn opaque(&self) -> OpaqueElement {
635 OpaqueElement::new(self.node())
636 }
637
638 fn parent_element(&self) -> Option<Self> {
639 self.sibling(|node| node.parent)
640 }
641
642 fn parent_node_is_shadow_root(&self) -> bool {
643 false
644 }
645
646 fn containing_shadow_host(&self) -> Option<Self> {
647 None
648 }
649
650 fn is_pseudo_element(&self) -> bool {
651 false
652 }
653
654 fn prev_sibling_element(&self) -> Option<Self> {
655 self.sibling(|node| node.previous)
656 }
657
658 fn next_sibling_element(&self) -> Option<Self> {
659 self.sibling(|node| node.next)
660 }
661
662 fn first_element_child(&self) -> Option<Self> {
663 self.sibling(|node| node.first_child)
664 }
665
666 fn is_html_element_in_html_document(&self) -> bool {
667 false
668 }
669
670 fn has_local_name(&self, name: &Atom) -> bool {
671 self.node().name == name.0
672 }
673
674 fn has_namespace(&self, ns: &Atom) -> bool {
675 ns.0.is_empty()
676 }
677
678 fn is_same_type(&self, other: &Self) -> bool {
679 self.node().name == other.node().name
680 }
681
682 fn attr_matches(
683 &self,
684 _ns: &NamespaceConstraint<&Atom>,
685 _local_name: &Atom,
686 _operation: &AttrSelectorOperation<&Atom>,
687 ) -> bool {
688 false
689 }
690
691 fn match_non_ts_pseudo_class(
692 &self,
693 pc: &PseudoClass,
694 _context: &mut MatchingContext<Fleuron>,
695 ) -> bool {
696 match *pc {}
697 }
698
699 fn match_pseudo_element(
703 &self,
704 _pe: &PseudoElement,
705 _context: &mut MatchingContext<Fleuron>,
706 ) -> bool {
707 false
708 }
709
710 fn apply_selector_flags(&self, _flags: ElementSelectorFlags) {}
711
712 fn is_link(&self) -> bool {
713 self.node().name == "a"
714 }
715
716 fn is_html_slot_element(&self) -> bool {
717 false
718 }
719
720 fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
721 self.node()
722 .attributes
723 .id
724 .as_ref()
725 .is_some_and(|mine| case_sensitivity.eq(mine.as_bytes(), id.0.as_bytes()))
726 }
727
728 fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
729 self.node()
730 .attributes
731 .classes
732 .iter()
733 .any(|mine| case_sensitivity.eq(mine.as_bytes(), name.0.as_bytes()))
734 }
735
736 fn has_custom_state(&self, _name: &Atom) -> bool {
737 false
738 }
739
740 fn imported_part(&self, _name: &Atom) -> Option<Atom> {
741 None
742 }
743
744 fn is_part(&self, _name: &Atom) -> bool {
745 false
746 }
747
748 fn is_empty(&self) -> bool {
749 self.node().first_child.is_none() && !self.node().has_text
750 }
751
752 fn is_root(&self) -> bool {
753 self.node().parent.is_none()
754 }
755
756 fn add_element_unique_hashes(&self, filter: &mut BloomFilter) -> bool {
760 let node = self.node();
761 let mut insert = |name: &str| filter.insert_hash(fnv(name) & BLOOM_HASH_MASK);
762 insert(node.name);
763 if let Some(id) = &node.attributes.id {
764 insert(id);
765 }
766 for class in &node.attributes.classes {
767 insert(class);
768 }
769 true
770 }
771}