1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! Visdom
//!
//! ### Description
//! A library use jquery-like api to operate html document, well experienced for scraping and keep away from scraping.
//!
//! ### Features
//! - Most css selectors, e.g. `#id`, `[attr~=value]`, `:nth-child`, `:nth-of-type`, `:not`, `:contains` and so on.
//! - Most selector methods, such as `find`,`filter`,`has`, `not`, `add`, `closest`.
//! - Powerful text modification ability: `set_html`, `set_text`, `append_text`, `prepend_text` can used for text node.
//! - Well-defined and easy to use apis.
use mesdoc::interface::{
	BoxDynElement, BoxDynNode, BoxDynText, BoxDynUncareNode, Elements, IDocumentTrait, IElementTrait,
	IErrorHandle, INodeTrait, ITextTrait, IUncareNodeTrait, InsertPosition, MaybeDoc, MaybeElement,
	Texts,
};

use mesdoc::{self, error::Error as IError, utils::retain_by_index};
use rphtml::{
	config::RenderOptions,
	entity::{encode, EncodeType::NamedOrDecimal, EntitySet::SpecialChars},
	parser::{
		allow_insert, is_content_tag, Attr, AttrData, Doc, DocHolder, NameCase, Node, NodeType, RefNode,
	},
};
use std::error::Error;
use std::rc::Rc;
use std::{any::Any, cell::RefCell};

// re export `IAttrValue` `IEnumTyped` `INodeType`
pub mod types {
	pub use mesdoc::interface::{
		BoxDynElement, BoxDynNode, BoxDynText, Elements, IAttrValue, IEnumTyped, INodeType, Texts,
	};
}

// re export `ParseOptions`
pub mod html {
	pub use rphtml::config::ParseOptions;
}

use crate::html::ParseOptions;
use crate::types::{IAttrValue, IEnumTyped, INodeType};
/// type implement INodeTrait with Node
struct Dom {
	node: Rc<RefCell<Node>>,
}

impl Dom {
	fn halt(&self, method: &str, message: &str) {
		if let Some(doc) = &self.owner_document() {
			doc.trigger_error(Box::new(IError::InvalidTraitMethodCall {
				method: String::from(method),
				message: String::from(message),
			}));
		}
	}

	fn validate_dom_change(&self, node: &BoxDynElement, method: &str) -> bool {
		// test if current node is element node
		let my_node_type = self.node.borrow().node_type;
		if my_node_type != NodeType::Tag {
			self.halt(
				method,
				&format!("Can't {} for a {:?} type", method, my_node_type),
			);
			return false;
		}
		// document
		if let INodeType::Document = node.node_type() {
			self.halt(method, &format!("Can't {} of a document type", method));
			return false;
		}
		// test if same node
		if self.is(&node) {
			self.halt(method, &format!("Can't {} of self.", method));
			return false;
		}
		// test if the node is self's parent node
		let mut cur = self.cloned();
		while let Some(parent) = &cur.parent() {
			if parent.is(&node) {
				self.halt(method, &format!("Can't {} of self's parent", method));
				return false;
			}
			cur = parent.cloned();
		}
		true
	}
}

fn to_static_str(orig: String) -> &'static str {
	Box::leak(orig.into_boxed_str())
}

fn reset_next_siblings_index(start_index: usize, childs: &[RefNode]) {
	for (step, node) in childs.iter().enumerate() {
		node.borrow_mut().index = start_index + step;
	}
}

fn remove_not_allowed_nodes(tag_name: &str, nodes: &mut Vec<RefNode>) -> bool {
	let mut not_allowed_indexs: Vec<usize> = Vec::with_capacity(nodes.len());
	let orig_len = nodes.len();
	for (index, node) in nodes.iter().enumerate() {
		if !allow_insert(tag_name, node.borrow().node_type) {
			not_allowed_indexs.push(index);
		}
	}
	if !not_allowed_indexs.is_empty() {
		retain_by_index(nodes, &not_allowed_indexs);
	}
	let now_allowed_len = not_allowed_indexs.len();
	now_allowed_len > 0 && now_allowed_len != orig_len
}

impl INodeTrait for Dom {
	/// impl `to_node`
	fn to_node(self: Box<Self>) -> Box<dyn Any> {
		self
	}

	/// impl `index`
	fn index(&self) -> usize {
		self.node.borrow().index
	}

	/// impl `clone_node`
	fn clone_node<'b>(&self) -> BoxDynNode<'b> {
		Box::new(Dom {
			node: self.node.clone(),
		})
	}

	/// impl `typed`
	fn typed<'b>(self: Box<Self>) -> IEnumTyped<'b> {
		match self.node_type() {
			INodeType::Element | INodeType::DocumentFragement | INodeType::Document => {
				IEnumTyped::Element(self as BoxDynElement)
			}
			INodeType::Text => IEnumTyped::Text(self as BoxDynText),
			_ => IEnumTyped::UncareNode(self as BoxDynUncareNode),
		}
	}

	/// impl `node_type`
	fn node_type(&self) -> INodeType {
		let node_type = self.node.borrow().node_type;
		match node_type {
			NodeType::AbstractRoot => {
				let (is_document, _) = self.node.borrow().is_document();
				if is_document {
					INodeType::Document
				} else {
					INodeType::DocumentFragement
				}
			}
			NodeType::Comment => INodeType::Comment,
			NodeType::Text | NodeType::SpacesBetweenTag => INodeType::Text,
			NodeType::Tag => INodeType::Element,
			NodeType::XMLCDATA => INodeType::XMLCDATA,
			NodeType::HTMLDOCTYPE => INodeType::HTMLDOCTYPE,
			_ => INodeType::Other,
		}
	}

	/// impl `parent`
	fn parent<'b>(&self) -> MaybeElement<'b> {
		if let Some(parent) = &self.node.borrow().parent {
			if let Some(node) = parent.upgrade() {
				let cur = Dom { node };
				return Some(Box::new(cur));
			}
		}
		None
	}

	/// impl `uuid`
	fn uuid(&self) -> Option<&str> {
		None
	}

	/// impl `owner_document`
	fn owner_document(&self) -> MaybeDoc {
		if let Some(root) = &self.node.borrow().root {
			if let Some(root) = &root.upgrade() {
				if let Some(doc) = &root.borrow().document {
					return Some(Box::new(Document {
						doc: Rc::clone(doc).into(),
					}));
				}
			}
		}
		None
	}

	/// impl `text_content`
	fn text_content(&self) -> &str {
		to_static_str(self.node.borrow().build(
			&RenderOptions {
				decode_entity: true,
				..Default::default()
			},
			matches!(self.node_type(), INodeType::Element),
		))
	}

	/// impl `set_text`
	fn set_text(&mut self, content: &str) {
		let node_type = self.node_type();
		match node_type {
			INodeType::Element => {
				let tag_name = self.tag_name();
				let no_content_tag = !is_content_tag(tag_name);
				let mut node = self.node.borrow_mut();
				if !content.is_empty() {
					if no_content_tag {
						// encode content
						let content = encode(content, SpecialChars, NamedOrDecimal);
						let mut text_node = Node::create_text_node(&content, None);
						// set text node parent
						text_node.parent = Some(Rc::downgrade(&self.node));
						// set childs
						node.childs = Some(vec![Rc::new(RefCell::new(text_node))]);
					} else {
						node.content = Some(content.chars().collect::<Vec<char>>());
					}
				} else {
					// empty content
					if no_content_tag {
						node.childs = None;
					} else {
						node.content = None;
					}
				}
			}
			INodeType::Text => {
				if content.is_empty() {
					self.halt("set_text",
            "the text parameter can't be empty, if you want to remove a text node, you can use 'remove' method instead."
          );
				} else {
					// replace the text content
					self.node.borrow_mut().content = Some(content.chars().collect::<Vec<char>>());
				}
			}
			_ => {
				// nothing to do with other node types
			}
		}
	}

	/// impl `set_html`
	fn set_html(&mut self, content: &str) {
		let mut is_element = true;
		let target = match self.node_type() {
			INodeType::Element => Some(Rc::clone(&self.node)),
			INodeType::Text => {
				if let Some(parent) = &self.node.borrow_mut().parent {
					if let Some(parent) = &parent.upgrade() {
						is_element = false;
						Some(Rc::clone(parent))
					} else {
						None
					}
				} else {
					None
				}
			}
			_ => None,
		};
		if let Some(target) = &target {
			let tag_name = target
				.borrow()
				.meta
				.as_ref()
				.map(|meta| meta.borrow().get_name(None))
				.expect("A tag use `set_html` must have a tag name.");
			if is_content_tag(&tag_name.to_ascii_lowercase()) {
				// content tag, just set html as content, no need encode
				target.borrow_mut().content = Some(content.chars().collect::<Vec<char>>());
			} else {
				let doc_holder = Doc::parse(
					content,
					ParseOptions {
						auto_fix_unexpected_endtag: true,
						auto_fix_unescaped_lt: true,
						..Default::default()
					},
				)
				.unwrap();
				if let Some(nodes) = &mut doc_holder.get_root_node().borrow_mut().childs {
					let mut nodes = nodes.split_off(0);
					let has_not_allowed = remove_not_allowed_nodes(&tag_name, &mut nodes);
					let has_nodes = !nodes.is_empty();
					if has_nodes {
						// set nodes parent as target
						for node in &nodes {
							node.borrow_mut().parent = Some(Rc::downgrade(target));
						}
					}
					if is_element {
						// reset node indexs
						if has_not_allowed {
							reset_next_siblings_index(0, &nodes);
						}
						// set childs as new nodes
						(*target.borrow_mut()).childs = if has_nodes { Some(nodes) } else { None };
					} else if let Some(childs) = &mut target.borrow_mut().childs {
						let index = self.index();
						// not last node, whenever nodes is empty or not, reset next childs indexs
						if index < childs.len() - 1 {
							// change next siblings index begin with index+nodes.len
							reset_next_siblings_index(index + nodes.len(), &childs[index + 1..]);
						}
						// delete the node and append childs
						if has_nodes {
							// change append nodes index begin with index
							reset_next_siblings_index(index, &nodes);
							// remove self and insert nodes
							childs.splice(index..index + 1, nodes);
						} else {
							// then just remove self
							childs.remove(index);
						}
					} else {
						// text node's parent can't be empty
					}
				} else {
					// empty html, just set childs to none
					target.borrow_mut().childs = None;
				}
			}
		}
	}
}

impl ITextTrait for Dom {
	// delete the node
	fn remove(self: Box<Self>) {
		let index = self.index();
		if let Some(parent) = &self.node.borrow_mut().parent {
			if let Some(parent) = parent.upgrade() {
				if let Some(childs) = &mut parent.borrow_mut().childs {
					// remove the text node
					childs.remove(index);
					// change next siblings index
					reset_next_siblings_index(index, &childs[index..]);
				}
			}
		}
	}

	// append text
	fn append_text(&mut self, content: &str) {
		let chars = content.chars().collect::<Vec<char>>();
		if let Some(content) = &mut self.node.borrow_mut().content {
			content.extend(chars);
		} else {
			self.node.borrow_mut().content = Some(chars);
		}
	}

	// prepend text
	fn prepend_text(&mut self, content: &str) {
		let chars = content.chars().collect::<Vec<char>>();
		if let Some(content) = &mut self.node.borrow_mut().content {
			content.splice(0..0, chars);
		} else {
			self.node.borrow_mut().content = Some(chars);
		}
	}
}

impl IUncareNodeTrait for Dom {}

impl IElementTrait for Dom {
	/// impl `tag_name`
	fn tag_name(&self) -> &str {
		match self.node_type() {
			INodeType::Element => {
				if let Some(meta) = &self.node.borrow().meta {
					let name = meta.borrow().get_name(Some(NameCase::Upper));
					return to_static_str(name);
				}
				self.halt("tag_name", "Html syntax error: not found a tag name.");
			}
			INodeType::Document | INodeType::DocumentFragement => {}
			cur_type => self.halt(
				"tag_name",
				&format!("The node type of '{:?}' doesn't have a tag name.", cur_type),
			),
		};
		""
	}

	/// impl `children`
	fn child_nodes_length(&self) -> usize {
		self
			.node
			.borrow()
			.childs
			.as_ref()
			.map_or(0, |childs| childs.len())
	}
	fn child_nodes_item<'b>(&self, index: usize) -> Option<BoxDynNode<'b>> {
		if let Some(childs) = &self.node.borrow().childs {
			return childs.get(index).map(|node| {
				Box::new(Dom {
					node: Rc::clone(node),
				}) as BoxDynNode
			});
		}
		None
	}
	/// impl `get_attribute`
	fn get_attribute(&self, name: &str) -> Option<IAttrValue> {
		// use lowercase to get attribute: issue: #2
		let name = name.to_ascii_lowercase();
		if let Some(meta) = &self.node.borrow().meta {
			for attr in &meta.borrow().attrs {
				if let Some(key) = &attr.key {
					// compare with lowercase
					if key.content.to_ascii_lowercase() == name {
						if let Some(value) = &attr.value {
							let attr_value = value.content.clone();
							return Some(IAttrValue::Value(attr_value, attr.quote));
						} else {
							return Some(IAttrValue::True);
						}
					}
				}
			}
		}
		None
	}
	/// impl `set_attribute`
	fn set_attribute(&mut self, name: &str, value: Option<&str>) {
		let mut need_quote = false;
		let mut quote: char = '"';
		if let Some(meta) = &self.node.borrow().meta {
			let value = value.map(|v| {
				let mut find_quote: bool = false;
				let mut content = String::with_capacity(v.len());
				// loop the chars
				for ch in v.chars() {
					if !need_quote {
						need_quote = Attr::need_quoted_char(&ch);
					}
					if ch == '"' || ch == '\'' {
						if find_quote {
							if quote == ch {
								// find more quotes
								content.push('\\');
							}
						} else {
							// if first is double quote, change the variable `quote` to single quote
							find_quote = true;
							if ch == '"' {
								quote = '\'';
							}
						}
					}
					content.push(ch);
				}
				AttrData { content }
			});
			// first, check if the attribute has exist.
			for attr in &mut meta.borrow_mut().attrs {
				if let Some(key) = &attr.key {
					if key.content == name {
						// find the attribute
						attr.value = value;
						return;
					}
				}
			}
			// new attribute, add it to queue.
			let quote = if value.is_some() { Some(quote) } else { None };
			meta.borrow_mut().attrs.push(Attr {
				key: Some(AttrData {
					content: name.into(),
				}),
				value,
				quote,
				need_quote,
			});
		}
	}

	/// impl `remove_attribute`
	fn remove_attribute(&mut self, name: &str) {
		if let Some(meta) = &self.node.borrow().meta {
			let find_index = meta.borrow().attrs.iter().position(|attr| {
				if let Some(key) = &attr.key {
					return key.content == name;
				}
				false
			});
			if let Some(index) = find_index {
				meta.borrow_mut().attrs.remove(index);
			}
		}
	}

	/// impl `inner_html`
	fn inner_html(&self) -> &str {
		to_static_str(self.node.borrow().build(
			&RenderOptions {
				inner_html: true,
				encode_content: true,
				..Default::default()
			},
			false,
		))
	}

	/// impl `outer_html`
	fn outer_html(&self) -> &str {
		to_static_str(self.node.borrow().build(
			&RenderOptions {
				encode_content: true,
				..Default::default()
			},
			false,
		))
	}

	/// impl `remov_child`
	fn remove_child(&mut self, ele: BoxDynElement) {
		if let Some(parent) = &ele.parent() {
			if self.is(parent) {
				// is a child
				if let Some(childs) = self.node.borrow_mut().childs.as_mut() {
					let index = ele.index();
					// if not the last child
					if index != childs.len() - 1 {
						reset_next_siblings_index(index, &childs[index + 1..]);
					}
					// remove child
					childs.remove(index);
				}
			}
		}
	}
	// append child
	fn insert_adjacent(&mut self, position: &InsertPosition, node: &BoxDynElement) {
		// base validate
		let action = position.action();
		if !self.validate_dom_change(&node, action) {
			return;
		}
		let node_type = node.node_type();
		let specified: Box<dyn Any> = node.cloned().to_node();
		if let Ok(dom) = specified.downcast::<Dom>() {
			// get the nodes
			let mut nodes = match node_type {
				INodeType::DocumentFragement => {
					if let Some(childs) = &dom.node.borrow().childs {
						childs
							.iter()
							.map(|v| Rc::clone(&v))
							.collect::<Vec<RefNode>>()
					} else {
						vec![]
					}
				}
				_ => {
					// remove current node from parent's childs
					if let Some(parent) = &mut node.parent() {
						parent.remove_child(node.cloned());
					}
					vec![dom.node]
				}
			};
			// filter the node allowed
			let tag_name = self.tag_name();
			// remove not allowed nodes
			remove_not_allowed_nodes(tag_name, &mut nodes);
			// check if is empty
			if nodes.is_empty() {
				return;
			}
			// insert
			use InsertPosition::*;
			match position {
				BeforeBegin | AfterEnd => {
					// get index first, for borrow check
					let mut index = self.index();
					let mut nexts: Vec<RefNode> = vec![];
					let insert_len = nodes.len();
					// it's insertAfter, increase the insertion index
					if *position == AfterEnd {
						index += 1;
					}
					// always reset node indexs
					reset_next_siblings_index(index, &nodes);
					// split to prev and next
					if let Some(parent) = &self.node.borrow_mut().parent {
						if let Some(parent) = &parent.upgrade() {
							if let Some(childs) = &mut parent.borrow_mut().childs {
								// split the nexts for reset index.
								if index < childs.len() {
									nexts = childs.split_off(index);
								}
								// set node parent
								for node in &nodes {
									node.borrow_mut().parent = Some(Rc::downgrade(parent));
								}
								// insert nodes at the end
								childs.extend(nodes);
							}
						}
					}
					if !nexts.is_empty() {
						// reset nexts index
						reset_next_siblings_index(index + insert_len, &nexts);
						// for borrrow check
						if let Some(parent) = &self.node.borrow_mut().parent {
							if let Some(parent) = parent.upgrade() {
								if let Some(childs) = &mut parent.borrow_mut().childs {
									//  insert nodes
									childs.extend(nexts);
								}
							}
						}
					}
				}
				AfterBegin | BeforeEnd => {
					// set nodes parent
					for node in &nodes {
						node.borrow_mut().parent = Some(Rc::downgrade(&self.node));
					}
					// prepend, append
					if let Some(childs) = &mut self.node.borrow_mut().childs {
						if *position == BeforeEnd {
							// reset nodes index
							reset_next_siblings_index(childs.len(), &nodes);
							// append nodes
							childs.extend(nodes);
						} else {
							// always reset nodes index
							reset_next_siblings_index(0, &nodes);
							// reset childs index
							reset_next_siblings_index(nodes.len(), &childs);
							// append childs to nodes
							nodes.append(childs);
							// set childs to nodes
							*childs = nodes;
						}
					} else {
						// reset nodes index
						reset_next_siblings_index(0, &nodes);
						// set nodes as childs
						self.node.borrow_mut().childs = Some(nodes);
					}
				}
			}
		} else {
			// not the Dom
			self.halt(
				action,
				&format!("Can't {} that not implemented 'Dom'", action),
			);
		}
	}

	/// impl `texts`
	fn texts<'b>(&self, limit_depth: u32) -> Option<Texts<'b>> {
		let limit_depth = if limit_depth == 0 {
			u32::MAX
		} else {
			limit_depth
		};
		let mut result: Texts = Texts::with_capacity(5);
		fn loop_handle(node: BoxDynElement, result: &mut Texts, cur_depth: u32, limit_depth: u32) {
			let child_nodes = node.child_nodes();
			if !child_nodes.is_empty() {
				let next_depth = cur_depth + 1;
				let recursive = next_depth < limit_depth;
				for node in &node.child_nodes() {
					match node.node_type() {
						INodeType::Text => {
							// append text node to result
							let node = node.clone_node();
							let text = node.typed().into_text().expect("TextNode must true");
							result.get_mut_ref().push(text);
						}
						INodeType::Element => {
							// if need recursive find the text node
							if recursive {
								let node = node.clone_node();
								let ele = node.typed().into_element().expect("ElementNode must true");
								loop_handle(ele, result, next_depth, limit_depth);
							}
						}
						_ => {}
					}
				}
			} else if is_content_tag(node.tag_name()) {
				// content tag, change the element into text type
				result.get_mut_ref().push(
					node
						.into_text()
						.expect("Content tag must be able to translate into text node"),
				);
			}
		}
		let node = Box::new(Dom {
			node: Rc::clone(&self.node),
		}) as BoxDynElement;
		loop_handle(node, &mut result, 0, limit_depth);
		if !result.is_empty() {
			return Some(result);
		}
		None
	}

	/// impl `into_text`
	fn into_text<'b>(self: Box<Self>) -> Result<BoxDynText<'b>, Box<dyn Error>> {
		if is_content_tag(self.tag_name()) {
			Ok(self as BoxDynText)
		} else {
			Err(Box::new(IError::InvalidTraitMethodCall {
				method: "into_text".into(),
				message: "Can't call 'into_text' with tags those are not content tags.".into(),
			}))
		}
	}

	/// impl `is`, is much faster than compare the `uuid`
	fn is(&self, ele: &BoxDynElement) -> bool {
		let specified: Box<dyn Any> = ele.cloned().to_node();
		if let Ok(dom) = specified.downcast::<Dom>() {
			return Node::is_same(&self.node, &dom.node);
		}
		false
	}
}

struct Document {
	doc: DocHolder,
}

impl Document {
	fn bind_error(&mut self, handle: IErrorHandle) {
		*self.doc.borrow().onerror.borrow_mut() = Some(Rc::new(handle));
	}
	fn list<'b>(&self) -> Elements<'b> {
		let root: Dom = Rc::clone(&self.doc.borrow().root).into();
		Elements::with_nodes(vec![Box::new(root)])
	}
}

impl IDocumentTrait for Document {
	// get element by id
	fn get_element_by_id<'b>(&self, id: &str) -> Option<BoxDynElement<'b>> {
		if let Some(node) = self.doc.get_element_by_id(id) {
			return Some(Box::new(Dom {
				node: Rc::clone(&node),
			}));
		}
		None
	}
	// source code
	fn source_code(&self) -> &'static str {
		to_static_str(self.doc.render(&Default::default()))
	}
	// get root node
	fn get_root_node<'b>(&self) -> BoxDynNode<'b> {
		Box::new(Dom {
			node: Rc::clone(&self.doc.borrow().root),
		})
	}
	// onerror
	fn onerror(&self) -> Option<Rc<IErrorHandle>> {
		if let Some(error_handle) = &(*self.doc.borrow().onerror.borrow()) {
			Some(Rc::clone(error_handle))
		} else {
			None
		}
	}
}

impl From<Rc<RefCell<Node>>> for Dom {
	fn from(node: Rc<RefCell<Node>>) -> Self {
		Dom {
			node: Rc::clone(&node),
		}
	}
}
/// Vis: Entry struct of the `mesdoc`'s api.
///
/// # Examples
///
/// ```
/// use visdom::Vis;
/// use std::error::Error;
/// fn main()-> Result<(), Box<dyn Error>>{
///   let html = r##"
///      <!doctype html>
///      <html>
///        <head>
///          <meta charset="utf-8" />
///        </head>
///        <body>
///           <nav id="header">
///            <ul>
///              <li>Hello,</li>
///              <li>Vis</li>
///              <li>Dom</li>
///            </ul>
///          </nav>
///        </body>
///     </html>
///   "##;
///   let doc = Vis::load(html)?;
///   // All useful css selectors are well supported.
///   let header = doc.find("#header");
///   let list_items = header.children("ul > li");
///   assert_eq!(list_items.length(), 3);
///   assert_eq!(list_items.text(), "Hello,VisDom");
///   let second_child = list_items.filter(":nth-child(2)");
///   assert_eq!(second_child.text(), "Vis");
///   // Easy to operate the nodes.
///   let mut fourth_child = Vis::load("<li>!</li>")?;
///   let mut parent = list_items.parent("");
///   assert_eq!(parent.length(), 1);
///   fourth_child.append_to(&mut parent);
///   let mut cur_list_items = header.children("ul > li");
///   assert_eq!(cur_list_items.length(), 4);
///   assert_eq!(cur_list_items.text(), "Hello,VisDom!");
///   // Powerful api for operate text nodes
///   // use append_text and prepend_text to change text
///   let mut texts = cur_list_items.texts(0);
///   texts.for_each(|_index, text_node|{
///      text_node.prepend_text("[");
///      text_node.append_text("]");
///      true
///   });
///   assert_eq!(cur_list_items.text(), "[Hello,][Vis][Dom][!]");
///   // use set_text to change text
///   texts.for_each(|_index, text_node|{
///       text_node.set_text("@");
///       true
///   });
///   assert_eq!(cur_list_items.text(), "@@@@");
///   // use set_html to mix content
///   texts.for_each(|_index, text_node|{
///       let orig_text = text_node.text();
///       let replace_html = format!("<span>{}</span><b>!</b>", orig_text);
///       // Be careful that now the text_node is destoryed by `set_html`
///       text_node.set_html(&replace_html);
///       true
///   });
///   assert_eq!(cur_list_items.children("b").length(), 4);
///   assert_eq!(cur_list_items.text(), "@!@!@!@!");
///   Ok(())
/// }
/// ```
pub struct Vis;

impl Vis {
	// init the patterns and all
	pub(crate) fn options() -> ParseOptions {
		// use the most compatible options
		ParseOptions {
			auto_fix_unclosed_tag: true,
			auto_fix_unexpected_endtag: true,
			auto_fix_unescaped_lt: true,
			allow_self_closing: true,
			..Default::default()
		}
	}
	// parse a document with options
	pub(crate) fn parse_doc_options(
		html: &str,
		options: ParseOptions,
	) -> Result<Document, Box<dyn Error>> {
		mesdoc::init();
		let doc = Doc::parse(html, options)?;
		Ok(Document { doc })
	}
	/// load the html with options, get an elements collection
	pub fn load_options(html: &str, options: ParseOptions) -> Result<Elements, Box<dyn Error>> {
		let doc = Vis::parse_doc_options(html, options)?;
		Ok(doc.list())
	}
	/// load the html with options, and catch the errors
	pub fn load_options_catch(html: &str, options: ParseOptions, handle: IErrorHandle) -> Elements {
		let doc = Vis::parse_doc_options(html, options);
		if let Ok(mut doc) = doc {
			doc.bind_error(handle);
			doc.list()
		} else {
			handle(doc.err().unwrap());
			Elements::new()
		}
	}
	/// load the html into elements
	pub fn load(html: &str) -> Result<Elements, Box<dyn Error>> {
		Vis::load_options(html, Vis::options())
	}
	/// load the html, and catch the errors
	pub fn load_catch(html: &str, handle: IErrorHandle) -> Elements {
		Vis::load_options_catch(html, Vis::options(), handle)
	}
	/// return an elements collection from an BoxDynElement
	pub fn dom<'b>(ele: &BoxDynElement) -> Elements<'b> {
		Elements::with_nodes(vec![ele.cloned()])
	}
}