about summary refs log tree commit diff
path: root/src/tag.rs
blob: 43c4e0cdc6e09251b60c2f7c0084e05cca39b465 (plain)
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
use core::fmt;
use std::{iter::Peekable, str::CharIndices};

use crate::Node;

#[derive(Clone, Debug, PartialEq)]
pub struct Tag {
	pub name: String,
	/// Everything inside the tag that's not it's name. Includes a
	/// self-close if there is one.
	pub body: Option<String>,
	pub self_closing: bool,
	pub children: Vec<Node>,
}

impl Tag {
	pub fn self_closing(&self) -> bool {
		self.self_closing
	}

	pub fn get_attribute<'a>(&'a self, key: &str) -> Option<&'a str> {
		let body = match self.body.as_deref() {
			None => return None,
			Some(body) => body,
		};

		// get rid of potential self-close
		let trimmed = if let Some(suffix) = body.trim().strip_suffix('/') {
			suffix
		} else {
			body.trim()
		};

		let mut wrk = trimmed;
		loop {
			let key_end_idx = wrk.find(|c: char| c == ' ' || c == '=');

			match key_end_idx {
				None => {
					// boolean ends body
					if wrk == key {
						return Some("");
					} else {
						break;
					}
				}
				Some(idx) => match &wrk[idx..idx + 1] {
					" " => {
						// boolean
						if &wrk[..idx] == key {
							return Some("");
						} else {
							wrk = &wrk[idx + 1..];
						}
					}
					"=" => {
						// key-value
						let found_name = &wrk[..idx];

						// we're just assuming the attributes are properly
						// formed right now. Skips the `=` and the `"` that
						// should be there but we don't check for
						wrk = &wrk[idx + 2..];
						let end = wrk.find('"').unwrap();
						let value = &wrk[..end];
						wrk = &wrk[end + 1..].trim_start();

						if found_name == key {
							return Some(value);
						}
					}
					_ => unreachable!(),
				},
			}
		}

		None
	}

	pub fn id(&self) -> Option<&str> {
		match self.get_attribute("id") {
			None => None,
			Some("") => None,
			Some(id) => Some(id),
		}
	}

	pub fn has_class(&self, name: &str) -> bool {
		match self.get_attribute("class") {
			None => false,
			Some(classes) => {
				for class in classes.split(' ') {
					if class == name {
						return true;
					}
				}

				false
			}
		}
	}

	pub fn append_child<N: Into<Node>>(&mut self, node: N) {
		let node = node.into();
		self.children.push(node);
	}

	/// Replace all children with one [Node::Text]
	pub fn set_inner_text<S: Into<String>>(&mut self, txt: S) {
		self.children = vec![Node::Text(txt.into())];
	}

	pub fn child_tags(&self) -> TagIterator {
		TagIterator {
			inner: self.children.iter(),
		}
	}

	pub fn child_tags_mut(&mut self) -> TagIteratorMut {
		TagIteratorMut {
			inner: self.children.iter_mut(),
		}
	}

	pub fn has_tag(&self, tag: &str) -> bool {
		self.child_tags().any(|t| t.name == tag)
	}

	pub fn by_tag_mut<'a>(&'a mut self, looking: &str) -> Option<&'a mut Tag> {
		for tag in self.child_tags_mut() {
			if tag.name == looking {
				return Some(tag);
			}

			if let Some(found) = tag.by_tag_mut(looking) {
				return Some(found);
			}
		}

		None
	}
}

impl fmt::Display for Tag {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let Tag {
			name,
			body,
			self_closing,
			children,
		} = self;

		let formatted_body = if let Some(body) = body {
			format!(" {body}")
		} else {
			String::from("")
		};

		if *self_closing {
			// we ignore our children if we're self-closing.
			write!(f, "<{name} {}/>", body.as_deref().unwrap_or_default())
		} else {
			write!(f, "<{name}{formatted_body}>")?;
			for child in children {
				write!(f, "{}", child)?;
			}
			write!(f, "</{name}>")
		}
	}
}

pub struct TagIterator<'a> {
	pub(crate) inner: std::slice::Iter<'a, Node>,
}

impl<'a> Iterator for TagIterator<'a> {
	type Item = &'a Tag;

	fn next(&mut self) -> Option<Self::Item> {
		loop {
			match self.inner.next() {
				None => break None,
				Some(Node::Tag(ref tag)) => break Some(tag),
				Some(_) => continue,
			}
		}
	}
}

pub struct TagIteratorMut<'a> {
	pub(crate) inner: std::slice::IterMut<'a, Node>,
}

impl<'a> Iterator for TagIteratorMut<'a> {
	type Item = &'a mut Tag;

	fn next(&mut self) -> Option<Self::Item> {
		loop {
			match self.inner.next() {
				None => break None,
				Some(Node::Tag(ref mut tag)) => break Some(tag),
				Some(_) => continue,
			}
		}
	}
}

#[cfg(test)]
mod test {
	use crate::Tag;

	use super::peek_skip_while;

	#[test]
	fn tag_finds_boolen_attribute() {
		let tag = Tag {
			name: "div".into(),
			body: Some("contenteditable".into()),
			self_closing: false,
			children: vec![],
		};
		assert!(tag.get_attribute("contenteditable").is_some())
	}

	#[test]
	fn tag_finds_kv_attribute() {
		let tag = Tag {
			name: "script".into(),
			body: Some("src=\"script.js\"".into()),
			self_closing: false,
			children: vec![],
		};
		assert_eq!(tag.get_attribute("src"), Some("script.js"))
	}

	#[test]
	fn tag_finds_boolean_in_centre() {
		let tag = Tag {
			name: "div".into(),
			body: Some("id=\"divy\" contenteditable style=\"display: none;\"".into()),
			self_closing: false,
			children: vec![],
		};
		assert!(tag.get_attribute("contenteditable").is_some());
	}

	// yes, this is a bad name.
	#[test]
	fn peek_skip_while_works() {
		let str = "\t    no whitespace";
		let mut chari = str.char_indices().peekable();

		peek_skip_while(&mut chari, |c| c.is_whitespace());

		let next_idx = chari.next().unwrap().0;
		assert_eq!(&str[next_idx..], "no whitespace");
	}
}

struct Attribute<'body> {
	name: &'body str,
	content: Option<&'body str>,
	start: usize,
	len: usize,
}

fn find_attribute<'body>(body: &'body str, attribute: &str) -> Option<Attribute<'body>> {
	let mut chari = body.char_indices().peekable();

	'big: loop {
		// skip whitespace
		peek_skip_while(&mut chari, |c| c.is_whitespace());

		let key_start = chari.next().unwrap();
		// find end of key
		peek_skip_while(&mut chari, |c| c.is_alphanumeric());

		let key_after = chari.next().unwrap();
	}

	todo!()
}

fn peek_skip_while<P>(iter: &mut Peekable<CharIndices>, mut predicate: P)
where
	P: FnMut(&char) -> bool,
{
	loop {
		match iter.peek() {
			Some((_, c)) if predicate(c) => {
				iter.next();
			}
			_ => break,
		}
	}
}