1#![allow(clippy::too_many_lines, clippy::collapsible_if)]
2use std::collections::VecDeque;
14
15pub const KEEP_DATA_DIVISOR: usize = 2;
16const MIN_HTML_BYTES: usize = 5000;
17const MAX_EXTRACTED_TOKENS: usize = 8000;
18const CHARS_PER_TOKEN_ESTIMATE: usize = 4;
19const TRACKING_QUERY_KEYS: &[&str] = &["fbclid", "gclid", "mc_cid", "mc_eid", "_ga", "ref_src"];
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct CodeBlock {
24 pub language: String,
26 pub content: String,
28}
29
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct ArticleMeta {
33 pub author: Option<String>,
34 pub date: Option<String>,
35 pub url: Option<String>,
36}
37
38#[derive(Debug, Clone, PartialEq)]
40pub struct ExtractionResult {
41 pub title: Option<String>,
42 pub content: String,
43 pub code_blocks: Vec<CodeBlock>,
44 pub metadata: ArticleMeta,
45 pub token_reduction: f64,
47}
48
49impl ExtractionResult {
50 #[must_use]
52 pub fn metadata_line(&self) -> Option<String> {
53 let mut fields = Vec::new();
54 if let Some(url) = self.metadata.url.as_deref() {
55 fields.push(url);
56 }
57 if let Some(title) = self.title.as_deref() {
58 fields.push(title);
59 }
60 if let Some(date) = self.metadata.date.as_deref() {
61 fields.push(date);
62 }
63 (!fields.is_empty()).then(|| format!("Source: {}", fields.join(" | ")))
64 }
65}
66
67#[derive(Debug, Clone)]
68pub struct CrushResult {
69 pub text: String,
70 pub lossless: bool,
71 pub original_bytes: usize,
72 pub extracted_tokens: usize,
73}
74
75pub fn is_html_content(content: &str) -> bool {
76 let trimmed = content.trim_start().to_ascii_lowercase();
77 trimmed.starts_with("<!doctype")
78 || trimmed.starts_with("<html")
79 || trimmed.starts_with("<?xml")
80 || (trimmed.contains("<head") && trimmed.contains("<body"))
81}
82
83pub fn crush_if_beneficial(html: &str) -> Option<CrushResult> {
84 if html.len() < MIN_HTML_BYTES {
85 return None;
86 }
87 if !is_html_content(html) {
88 return None;
89 }
90
91 let extraction = extract_article_content(html);
92 if extraction.content.is_empty() {
93 return None;
94 }
95 let extracted = match extraction.metadata_line() {
96 Some(line) => format!("{line}\n\n{}", extraction.content),
97 None => extraction.content,
98 };
99
100 let original_tokens = html.len() / CHARS_PER_TOKEN_ESTIMATE;
101 let extracted_tokens = extracted.len() / CHARS_PER_TOKEN_ESTIMATE;
102
103 if extracted_tokens * KEEP_DATA_DIVISOR >= original_tokens {
104 return None;
105 }
106 if extracted_tokens > MAX_EXTRACTED_TOKENS {
107 let char_budget = MAX_EXTRACTED_TOKENS * CHARS_PER_TOKEN_ESTIMATE;
108 let mut end = char_budget.min(extracted.len());
109 while !extracted.is_char_boundary(end) && end > 0 {
110 end -= 1;
111 }
112 let truncated = format!(
113 "{}\n\n[… truncated, {} more tokens in original]",
114 &extracted[..end],
115 original_tokens - MAX_EXTRACTED_TOKENS
116 );
117 return Some(CrushResult {
118 text: truncated,
119 lossless: false,
120 original_bytes: html.len(),
121 extracted_tokens: MAX_EXTRACTED_TOKENS,
122 });
123 }
124
125 Some(CrushResult {
126 text: extracted,
127 lossless: false,
128 original_bytes: html.len(),
129 extracted_tokens,
130 })
131}
132
133pub fn extract_article(html: &str) -> String {
134 extract_article_content(html).content
135}
136
137pub fn extract_article_content(html: &str) -> ExtractionResult {
139 let tokens = tokenize(html);
140 let nodes = build_tree(&tokens);
141 let article = select_main_content(&nodes);
142 let content = nodes_to_markdown(&article);
143 let (title, metadata) = extract_metadata(&nodes, &article);
144 let code_blocks = collect_code_blocks(&article);
145 let token_reduction = if html.is_empty() {
146 0.0
147 } else {
148 (1.0 - content.len() as f64 / html.len() as f64).clamp(0.0, 1.0)
149 };
150 ExtractionResult {
151 title,
152 content,
153 code_blocks,
154 metadata,
155 token_reduction,
156 }
157}
158
159#[derive(Debug, Clone, PartialEq)]
162enum HtmlToken {
163 OpenTag {
164 name: String,
165 attrs: Vec<(String, String)>,
166 self_closing: bool,
167 },
168 CloseTag {
169 name: String,
170 },
171 Text(String),
172}
173
174fn tokenize(html: &str) -> Vec<HtmlToken> {
175 let mut tokens = Vec::new();
176 let mut chars = html.chars().peekable();
177 let mut text_buf = String::new();
178
179 while let Some(&ch) = chars.peek() {
180 if ch == '<' {
181 if !text_buf.is_empty() {
182 let t = std::mem::take(&mut text_buf);
183 tokens.push(HtmlToken::Text(decode_entities(&t)));
184 }
185 chars.next();
186 if chars.peek() == Some(&'!') {
187 skip_comment_or_doctype(&mut chars);
188 continue;
189 }
190 let is_close = chars.peek() == Some(&'/');
191 if is_close {
192 chars.next();
193 }
194 let tag_name = consume_tag_name(&mut chars);
195 if tag_name.is_empty() {
196 text_buf.push('<');
197 if is_close {
198 text_buf.push('/');
199 }
200 continue;
201 }
202 if is_close {
203 skip_until_gt(&mut chars);
204 tokens.push(HtmlToken::CloseTag {
205 name: tag_name.to_ascii_lowercase(),
206 });
207 } else {
208 let (attrs, self_closing) = parse_attrs(&mut chars);
209 let name = tag_name.to_ascii_lowercase();
210 if is_raw_text_element(&name) {
211 skip_raw_content(&mut chars, &name);
212 }
213 tokens.push(HtmlToken::OpenTag {
214 name,
215 attrs,
216 self_closing,
217 });
218 }
219 } else {
220 text_buf.push(ch);
221 chars.next();
222 }
223 }
224 if !text_buf.is_empty() {
225 tokens.push(HtmlToken::Text(decode_entities(&text_buf)));
226 }
227 tokens
228}
229
230fn is_raw_text_element(name: &str) -> bool {
231 matches!(name, "script" | "style" | "noscript" | "template")
232}
233
234fn skip_raw_content(chars: &mut std::iter::Peekable<std::str::Chars>, tag: &str) {
235 let close_tag = format!("</{tag}");
236 let mut buf = String::new();
237 for ch in chars.by_ref() {
238 buf.push(ch);
239 if buf.ends_with(&close_tag) {
240 skip_until_gt(chars);
241 return;
242 }
243 if buf.len() > close_tag.len() + 100 {
244 buf.drain(..buf.len() - close_tag.len());
245 }
246 }
247}
248
249fn skip_comment_or_doctype(chars: &mut std::iter::Peekable<std::str::Chars>) {
250 for ch in chars.by_ref() {
251 if ch == '>' {
252 return;
253 }
254 }
255}
256
257fn consume_tag_name(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
258 let mut name = String::new();
259 while let Some(&ch) = chars.peek() {
260 if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
261 name.push(ch);
262 chars.next();
263 } else {
264 break;
265 }
266 }
267 name
268}
269
270fn parse_attrs(chars: &mut std::iter::Peekable<std::str::Chars>) -> (Vec<(String, String)>, bool) {
271 let mut attrs = Vec::new();
272 let mut self_closing = false;
273
274 loop {
275 skip_whitespace(chars);
276 match chars.peek() {
277 None => break,
278 Some(&'>') => {
279 chars.next();
280 break;
281 }
282 Some(&'/') => {
283 chars.next();
284 if chars.peek() == Some(&'>') {
285 chars.next();
286 self_closing = true;
287 }
288 break;
289 }
290 _ => {}
291 }
292 let key = consume_attr_name(chars);
293 if key.is_empty() {
294 chars.next();
295 continue;
296 }
297 skip_whitespace(chars);
298 let value = if chars.peek() == Some(&'=') {
299 chars.next();
300 skip_whitespace(chars);
301 consume_attr_value(chars)
302 } else {
303 String::new()
304 };
305 attrs.push((key.to_ascii_lowercase(), value));
306 }
307 (attrs, self_closing)
308}
309
310fn consume_attr_name(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
311 let mut name = String::new();
312 while let Some(&ch) = chars.peek() {
313 if ch == '=' || ch == '>' || ch == '/' || ch.is_ascii_whitespace() {
314 break;
315 }
316 name.push(ch);
317 chars.next();
318 }
319 name
320}
321
322fn consume_attr_value(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
323 let mut value = String::new();
324 match chars.peek() {
325 Some(&'"') => {
326 chars.next();
327 for ch in chars.by_ref() {
328 if ch == '"' {
329 break;
330 }
331 value.push(ch);
332 }
333 }
334 Some(&'\'') => {
335 chars.next();
336 for ch in chars.by_ref() {
337 if ch == '\'' {
338 break;
339 }
340 value.push(ch);
341 }
342 }
343 _ => {
344 while let Some(&ch) = chars.peek() {
345 if ch.is_ascii_whitespace() || ch == '>' {
346 break;
347 }
348 value.push(ch);
349 chars.next();
350 }
351 }
352 }
353 value
354}
355
356fn skip_whitespace(chars: &mut std::iter::Peekable<std::str::Chars>) {
357 while chars.peek().is_some_and(char::is_ascii_whitespace) {
358 chars.next();
359 }
360}
361
362fn skip_until_gt(chars: &mut std::iter::Peekable<std::str::Chars>) {
363 for ch in chars.by_ref() {
364 if ch == '>' {
365 return;
366 }
367 }
368}
369
370fn decode_entities(text: &str) -> String {
371 text.replace("&", "&")
372 .replace("<", "<")
373 .replace(">", ">")
374 .replace(""", "\"")
375 .replace("'", "'")
376 .replace("'", "'")
377 .replace(" ", " ")
378 .replace("'", "'")
379 .replace("/", "/")
380}
381
382#[derive(Debug, Clone)]
385struct HtmlNode {
386 tag: String,
387 attrs: Vec<(String, String)>,
388 children: Vec<HtmlNodeChild>,
389}
390
391#[derive(Debug, Clone)]
392enum HtmlNodeChild {
393 Element(HtmlNode),
394 Text(String),
395}
396
397const VOID_ELEMENTS: &[&str] = &[
398 "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source",
399 "track", "wbr",
400];
401
402fn build_tree(tokens: &[HtmlToken]) -> Vec<HtmlNodeChild> {
403 let mut stack: VecDeque<HtmlNode> = VecDeque::new();
404 stack.push_back(HtmlNode {
405 tag: "root".into(),
406 attrs: vec![],
407 children: vec![],
408 });
409
410 for token in tokens {
411 match token {
412 HtmlToken::OpenTag {
413 name,
414 attrs,
415 self_closing,
416 } => {
417 if *self_closing || VOID_ELEMENTS.contains(&name.as_str()) {
418 let node = HtmlNode {
419 tag: name.clone(),
420 attrs: attrs.clone(),
421 children: vec![],
422 };
423 if let Some(parent) = stack.back_mut() {
424 parent.children.push(HtmlNodeChild::Element(node));
425 }
426 } else {
427 stack.push_back(HtmlNode {
428 tag: name.clone(),
429 attrs: attrs.clone(),
430 children: vec![],
431 });
432 }
433 }
434 HtmlToken::CloseTag { name } => {
435 if let Some(pos) = stack.iter().rposition(|n| n.tag == *name) {
436 while stack.len() > pos + 1 {
437 let child = stack
438 .pop_back()
439 .expect("stack.len() > pos + 1 guarantees an element");
440 if let Some(parent) = stack.back_mut() {
441 parent.children.push(HtmlNodeChild::Element(child));
442 }
443 }
444 let child = stack
445 .pop_back()
446 .expect("matching open tag guarantees a closable element");
447 if let Some(parent) = stack.back_mut() {
448 parent.children.push(HtmlNodeChild::Element(child));
449 }
450 }
451 }
452 HtmlToken::Text(text) => {
453 let trimmed = text.trim();
454 if !trimmed.is_empty()
455 && let Some(parent) = stack.back_mut()
456 {
457 parent.children.push(HtmlNodeChild::Text(text.clone()));
458 }
459 }
460 }
461 }
462
463 while stack.len() > 1 {
464 let child = stack
465 .pop_back()
466 .expect("stack.len() > 1 guarantees an element");
467 if let Some(parent) = stack.back_mut() {
468 parent.children.push(HtmlNodeChild::Element(child));
469 }
470 }
471
472 stack.pop_back().map(|r| r.children).unwrap_or_default()
473}
474
475const BOILERPLATE_TAGS: &[&str] = &["nav", "footer", "header", "aside", "menu", "menuitem"];
478
479const BOILERPLATE_ROLES: &[&str] = &[
480 "navigation",
481 "banner",
482 "contentinfo",
483 "complementary",
484 "menu",
485];
486
487const BOILERPLATE_CLASSES: &[&str] = &[
488 "nav",
489 "navbar",
490 "footer",
491 "sidebar",
492 "menu",
493 "cookie",
494 "banner",
495 "advertisement",
496 "ad",
497 "social",
498 "share",
499 "comment",
500 "related",
501];
502
503fn select_main_content(nodes: &[HtmlNodeChild]) -> Vec<HtmlNodeChild> {
504 if let Some(main) = find_element_by_tag_or_role(nodes, "main", "main") {
505 return main.children.clone();
506 }
507 if let Some(article) = find_element_by_tag_or_role(nodes, "article", "") {
508 return article.children.clone();
509 }
510 if let Some(content) = find_element_by_id_class(
511 nodes,
512 &[
513 "content",
514 "main-content",
515 "post-content",
516 "entry-content",
517 "article-body",
518 ],
519 ) {
520 return content.children.clone();
521 }
522 if let Some(body) = find_element_by_tag(nodes, "body") {
523 return filter_boilerplate(&body.children);
524 }
525 filter_boilerplate(nodes)
526}
527
528fn find_element_by_tag_or_role<'a>(
529 nodes: &'a [HtmlNodeChild],
530 tag: &str,
531 role: &str,
532) -> Option<&'a HtmlNode> {
533 for child in nodes {
534 if let HtmlNodeChild::Element(el) = child {
535 if el.tag == tag {
536 return Some(el);
537 }
538 if !role.is_empty() && el.attrs.iter().any(|(k, v)| k == "role" && v == role) {
539 return Some(el);
540 }
541 if let Some(found) = find_element_by_tag_or_role(&el.children, tag, role) {
542 return Some(found);
543 }
544 }
545 }
546 None
547}
548
549fn find_element_by_tag<'a>(nodes: &'a [HtmlNodeChild], tag: &str) -> Option<&'a HtmlNode> {
550 for child in nodes {
551 if let HtmlNodeChild::Element(el) = child {
552 if el.tag == tag {
553 return Some(el);
554 }
555 if let Some(found) = find_element_by_tag(&el.children, tag) {
556 return Some(found);
557 }
558 }
559 }
560 None
561}
562
563fn find_element_by_id_class<'a>(
564 nodes: &'a [HtmlNodeChild],
565 candidates: &[&str],
566) -> Option<&'a HtmlNode> {
567 for child in nodes {
568 if let HtmlNodeChild::Element(el) = child {
569 let id = el
570 .attrs
571 .iter()
572 .find(|(k, _)| k == "id")
573 .map_or("", |(_, v)| v.as_str());
574 let class = el
575 .attrs
576 .iter()
577 .find(|(k, _)| k == "class")
578 .map_or("", |(_, v)| v.as_str());
579 if candidates
580 .iter()
581 .any(|c| id == *c || class.split_whitespace().any(|cls| cls == *c))
582 {
583 return Some(el);
584 }
585 if let Some(found) = find_element_by_id_class(&el.children, candidates) {
586 return Some(found);
587 }
588 }
589 }
590 None
591}
592
593fn attribute<'a>(el: &'a HtmlNode, name: &str) -> Option<&'a str> {
594 el.attrs
595 .iter()
596 .find(|(key, _)| key.eq_ignore_ascii_case(name))
597 .map(|(_, value)| value.as_str())
598}
599
600fn node_text(nodes: &[HtmlNodeChild]) -> String {
601 let mut text = String::new();
602 raw_text(nodes, &mut text);
603 normalize_whitespace(&text).trim().to_string()
604}
605
606fn raw_text(nodes: &[HtmlNodeChild], out: &mut String) {
607 for child in nodes {
608 match child {
609 HtmlNodeChild::Text(text) => out.push_str(text),
610 HtmlNodeChild::Element(el) => raw_text(&el.children, out),
611 }
612 }
613}
614
615fn find_meta_value(nodes: &[HtmlNodeChild], names: &[&str]) -> Option<String> {
616 for child in nodes {
617 let HtmlNodeChild::Element(el) = child else {
618 continue;
619 };
620 if el.tag == "meta"
621 && let Some(value) = attribute(el, "content")
622 && !value.trim().is_empty()
623 && names.iter().any(|name| {
624 attribute(el, "name")
625 .or_else(|| attribute(el, "property"))
626 .is_some_and(|actual| actual.eq_ignore_ascii_case(name))
627 })
628 {
629 return Some(value.trim().to_string());
630 }
631 if let Some(value) = find_meta_value(&el.children, names) {
632 return Some(value);
633 }
634 }
635 None
636}
637
638fn find_canonical_url(nodes: &[HtmlNodeChild]) -> Option<String> {
639 for child in nodes {
640 let HtmlNodeChild::Element(el) = child else {
641 continue;
642 };
643 if el.tag == "link"
644 && attribute(el, "rel").is_some_and(|rel| {
645 rel.split_whitespace()
646 .any(|v| v.eq_ignore_ascii_case("canonical"))
647 })
648 && let Some(href) = attribute(el, "href")
649 && !href.trim().is_empty()
650 {
651 return Some(href.trim().to_string());
652 }
653 if let Some(value) = find_canonical_url(&el.children) {
654 return Some(value);
655 }
656 }
657 None
658}
659
660fn extract_metadata(
661 nodes: &[HtmlNodeChild],
662 article: &[HtmlNodeChild],
663) -> (Option<String>, ArticleMeta) {
664 let title = find_element_by_tag(nodes, "title")
665 .map(|el| node_text(&el.children))
666 .filter(|value| !value.is_empty())
667 .or_else(|| {
668 find_element_by_tag(article, "h1")
669 .map(|el| node_text(&el.children))
670 .filter(|value| !value.is_empty())
671 });
672 let author = find_meta_value(nodes, &["author", "article:author"]);
673 let date = find_meta_value(
674 nodes,
675 &[
676 "date",
677 "article:published_time",
678 "article:modified_time",
679 "pubdate",
680 ],
681 )
682 .or_else(|| {
683 find_element_by_tag(nodes, "time").and_then(|el| {
684 attribute(el, "datetime").map(str::to_string).or_else(|| {
685 let text = node_text(&el.children);
686 (!text.is_empty()).then_some(text)
687 })
688 })
689 });
690 let url = find_meta_value(nodes, &["og:url", "twitter:url", "url"])
691 .or_else(|| find_canonical_url(nodes));
692 (title, ArticleMeta { author, date, url })
693}
694
695fn collect_code_blocks(nodes: &[HtmlNodeChild]) -> Vec<CodeBlock> {
696 let mut blocks = Vec::new();
697 collect_code_blocks_inner(nodes, &mut blocks);
698 blocks
699}
700
701fn collect_code_blocks_inner(nodes: &[HtmlNodeChild], blocks: &mut Vec<CodeBlock>) {
702 for child in nodes {
703 let HtmlNodeChild::Element(el) = child else {
704 continue;
705 };
706 if el.tag == "pre" || el.tag == "code" {
707 let mut content = String::new();
708 raw_text(&el.children, &mut content);
709 blocks.push(CodeBlock {
710 language: if el.tag == "pre" {
711 detect_code_language(el)
712 } else {
713 code_language(el)
714 },
715 content,
716 });
717 if el.tag == "pre" {
718 continue;
719 }
720 }
721 collect_code_blocks_inner(&el.children, blocks);
722 }
723}
724
725fn filter_boilerplate(nodes: &[HtmlNodeChild]) -> Vec<HtmlNodeChild> {
726 nodes
727 .iter()
728 .filter(|child| {
729 if let HtmlNodeChild::Element(el) = child {
730 !is_boilerplate(el)
731 } else {
732 true
733 }
734 })
735 .cloned()
736 .collect()
737}
738
739fn is_boilerplate(el: &HtmlNode) -> bool {
740 if BOILERPLATE_TAGS.contains(&el.tag.as_str()) {
741 return true;
742 }
743 let role = el
744 .attrs
745 .iter()
746 .find(|(k, _)| k == "role")
747 .map_or("", |(_, v)| v.as_str());
748 if BOILERPLATE_ROLES.contains(&role) {
749 return true;
750 }
751 let class = el
752 .attrs
753 .iter()
754 .find(|(k, _)| k == "class")
755 .map_or("", |(_, v)| v.as_str());
756 BOILERPLATE_CLASSES
757 .iter()
758 .any(|bc| class.split_whitespace().any(|cls| cls.contains(bc)))
759}
760
761fn nodes_to_markdown(nodes: &[HtmlNodeChild]) -> String {
764 let mut output = String::new();
765 render_nodes(nodes, &mut output, &mut RenderState::default());
766 collapse_whitespace(&output)
767}
768
769#[derive(Default)]
770struct RenderState {
771 list_depth: usize,
772 ordered_counter: Vec<usize>,
773 in_pre: bool,
774}
775
776fn render_nodes(nodes: &[HtmlNodeChild], out: &mut String, state: &mut RenderState) {
777 for child in nodes {
778 match child {
779 HtmlNodeChild::Text(text) => {
780 if state.in_pre {
781 out.push_str(text);
782 } else {
783 let normalized = normalize_whitespace(text);
784 if !normalized.is_empty() {
785 out.push_str(&normalized);
786 }
787 }
788 }
789 HtmlNodeChild::Element(el) => render_element(el, out, state),
790 }
791 }
792}
793
794fn collapse_tracking_parameters(href: &str) -> String {
795 let Some((base, query_and_fragment)) = href.split_once('?') else {
796 return href.to_string();
797 };
798 let (query, fragment) = query_and_fragment
799 .split_once('#')
800 .unwrap_or((query_and_fragment, ""));
801 let kept: Vec<&str> = query
802 .split('&')
803 .filter(|part| {
804 let key = part.split_once('=').map_or(*part, |(key, _)| key);
805 let lower = key.to_ascii_lowercase();
806 !lower.starts_with("utm_") && !TRACKING_QUERY_KEYS.contains(&lower.as_str())
807 })
808 .collect();
809 let mut result = base.to_string();
810 if !kept.is_empty() {
811 result.push('?');
812 result.push_str(&kept.join("&"));
813 }
814 if !fragment.is_empty() {
815 result.push('#');
816 result.push_str(fragment);
817 }
818 result
819}
820
821fn render_element(el: &HtmlNode, out: &mut String, state: &mut RenderState) {
822 match el.tag.as_str() {
823 "h1" => {
824 ensure_newlines(out, 2);
825 out.push_str("# ");
826 render_nodes(&el.children, out, state);
827 ensure_newlines(out, 2);
828 }
829 "h2" => {
830 ensure_newlines(out, 2);
831 out.push_str("## ");
832 render_nodes(&el.children, out, state);
833 ensure_newlines(out, 2);
834 }
835 "h3" => {
836 ensure_newlines(out, 2);
837 out.push_str("### ");
838 render_nodes(&el.children, out, state);
839 ensure_newlines(out, 2);
840 }
841 "h4" => {
842 ensure_newlines(out, 2);
843 out.push_str("#### ");
844 render_nodes(&el.children, out, state);
845 ensure_newlines(out, 2);
846 }
847 "h5" => {
848 ensure_newlines(out, 2);
849 out.push_str("##### ");
850 render_nodes(&el.children, out, state);
851 ensure_newlines(out, 2);
852 }
853 "h6" => {
854 ensure_newlines(out, 2);
855 out.push_str("###### ");
856 render_nodes(&el.children, out, state);
857 ensure_newlines(out, 2);
858 }
859 "p" | "div" | "section" | "article" => {
860 ensure_newlines(out, 2);
861 render_nodes(&el.children, out, state);
862 ensure_newlines(out, 2);
863 }
864 "br" => {
865 out.push('\n');
866 }
867 "hr" => {
868 ensure_newlines(out, 2);
869 out.push_str("---");
870 ensure_newlines(out, 2);
871 }
872 "strong" | "b" => {
873 out.push_str("**");
874 render_nodes(&el.children, out, state);
875 out.push_str("**");
876 }
877 "em" | "i" => {
878 out.push('*');
879 render_nodes(&el.children, out, state);
880 out.push('*');
881 }
882 "code" if !state.in_pre => {
883 out.push('`');
884 render_nodes(&el.children, out, state);
885 out.push('`');
886 }
887 "pre" => {
888 ensure_newlines(out, 2);
889 let lang = detect_code_language(el);
890 out.push_str("```");
891 out.push_str(&lang);
892 out.push('\n');
893 state.in_pre = true;
894 render_nodes(&el.children, out, state);
895 state.in_pre = false;
896 if !out.ends_with('\n') {
897 out.push('\n');
898 }
899 out.push_str("```");
900 ensure_newlines(out, 2);
901 }
902 "a" => {
903 let href = el
904 .attrs
905 .iter()
906 .find(|(k, _)| k == "href")
907 .map_or("", |(_, v)| v.as_str());
908 let mut link_text = String::new();
909 render_nodes(&el.children, &mut link_text, state);
910 let link_text = link_text.trim().to_string();
911 if !link_text.is_empty()
912 && !href.is_empty()
913 && !href.starts_with('#')
914 && !href.starts_with("javascript:")
915 {
916 out.push('[');
917 out.push_str(&link_text);
918 out.push_str("](");
919 out.push_str(&collapse_tracking_parameters(href));
920 out.push(')');
921 } else if !link_text.is_empty() {
922 out.push_str(&link_text);
923 }
924 }
925 "ul" => {
926 ensure_newlines(out, 2);
927 state.list_depth += 1;
928 render_nodes(&el.children, out, state);
929 state.list_depth -= 1;
930 ensure_newlines(out, 2);
931 }
932 "ol" => {
933 ensure_newlines(out, 2);
934 state.list_depth += 1;
935 state.ordered_counter.push(0);
936 render_nodes(&el.children, out, state);
937 state.ordered_counter.pop();
938 state.list_depth -= 1;
939 ensure_newlines(out, 2);
940 }
941 "li" => {
942 ensure_newlines(out, 1);
943 let indent = " ".repeat(state.list_depth.saturating_sub(1));
944 out.push_str(&indent);
945 if let Some(counter) = state.ordered_counter.last_mut() {
946 *counter += 1;
947 out.push_str(&format!("{counter}. "));
948 } else {
949 out.push_str("- ");
950 }
951 render_nodes(&el.children, out, state);
952 }
953 "blockquote" => {
954 ensure_newlines(out, 2);
955 let mut inner = String::new();
956 render_nodes(&el.children, &mut inner, state);
957 for line in inner.trim().lines() {
958 out.push_str("> ");
959 out.push_str(line);
960 out.push('\n');
961 }
962 ensure_newlines(out, 2);
963 }
964 "table" => {
965 ensure_newlines(out, 2);
966 render_table(el, out, state);
967 ensure_newlines(out, 2);
968 }
969 "img" => {
970 let alt = el
971 .attrs
972 .iter()
973 .find(|(k, _)| k == "alt")
974 .map_or("", |(_, v)| v.as_str());
975 let src = el
976 .attrs
977 .iter()
978 .find(|(k, _)| k == "src")
979 .map_or("", |(_, v)| v.as_str());
980 if !alt.is_empty() && !src.is_empty() {
981 out.push_str(&format!(""));
982 }
983 }
984 _ => {
985 render_nodes(&el.children, out, state);
986 }
987 }
988}
989
990fn render_table(el: &HtmlNode, out: &mut String, state: &mut RenderState) {
991 let rows = collect_table_rows(el);
992 if rows.is_empty() {
993 return;
994 }
995
996 let col_count = rows.iter().map(Vec::len).max().unwrap_or(0);
997 if col_count == 0 {
998 return;
999 }
1000
1001 for (i, row) in rows.iter().enumerate() {
1002 out.push('|');
1003 for col in 0..col_count {
1004 let cell = row.get(col).map_or("", String::as_str);
1005 out.push(' ');
1006 out.push_str(cell.trim());
1007 out.push_str(" |");
1008 }
1009 out.push('\n');
1010 if i == 0 {
1011 out.push('|');
1012 for _ in 0..col_count {
1013 out.push_str(" --- |");
1014 }
1015 out.push('\n');
1016 }
1017 }
1018 let _ = state;
1019}
1020
1021fn collect_table_rows(el: &HtmlNode) -> Vec<Vec<String>> {
1022 let mut rows = Vec::new();
1023 collect_rows_recursive(el, &mut rows);
1024 rows
1025}
1026
1027fn collect_rows_recursive(el: &HtmlNode, rows: &mut Vec<Vec<String>>) {
1028 if el.tag == "tr" {
1029 let cells: Vec<String> = el
1030 .children
1031 .iter()
1032 .filter_map(|child| {
1033 if let HtmlNodeChild::Element(cell) = child {
1034 if cell.tag == "td" || cell.tag == "th" {
1035 let mut text = String::new();
1036 render_nodes(&cell.children, &mut text, &mut RenderState::default());
1037 return Some(text.trim().to_string());
1038 }
1039 }
1040 None
1041 })
1042 .collect();
1043 if !cells.is_empty() {
1044 rows.push(cells);
1045 }
1046 }
1047 for child in &el.children {
1048 if let HtmlNodeChild::Element(child_el) = child {
1049 collect_rows_recursive(child_el, rows);
1050 }
1051 }
1052}
1053
1054fn code_language(el: &HtmlNode) -> String {
1055 let class = attribute(el, "class").unwrap_or("");
1056 for cls in class.split_whitespace() {
1057 if let Some(lang) = cls.strip_prefix("language-") {
1058 return lang.to_string();
1059 }
1060 if let Some(lang) = cls.strip_prefix("lang-") {
1061 return lang.to_string();
1062 }
1063 if matches!(
1064 cls,
1065 "rust"
1066 | "python"
1067 | "javascript"
1068 | "typescript"
1069 | "go"
1070 | "java"
1071 | "c"
1072 | "cpp"
1073 | "ruby"
1074 | "bash"
1075 | "sh"
1076 | "json"
1077 | "yaml"
1078 | "toml"
1079 | "sql"
1080 | "html"
1081 | "css"
1082 ) {
1083 return cls.to_string();
1084 }
1085 }
1086 String::new()
1087}
1088
1089fn detect_code_language(pre: &HtmlNode) -> String {
1090 for child in &pre.children {
1091 if let HtmlNodeChild::Element(code) = child {
1092 if code.tag == "code" {
1093 let language = code_language(code);
1094 if !language.is_empty() {
1095 return language;
1096 }
1097 }
1098 }
1099 }
1100 code_language(pre)
1101}
1102
1103fn normalize_whitespace(text: &str) -> String {
1104 let mut result = String::with_capacity(text.len());
1105 let mut last_was_space = false;
1106 for ch in text.chars() {
1107 if ch.is_ascii_whitespace() {
1108 if !last_was_space {
1109 result.push(' ');
1110 last_was_space = true;
1111 }
1112 } else {
1113 result.push(ch);
1114 last_was_space = false;
1115 }
1116 }
1117 result
1118}
1119
1120fn ensure_newlines(out: &mut String, count: usize) {
1121 let trailing_newlines = out.chars().rev().take_while(|&c| c == '\n').count();
1122 for _ in trailing_newlines..count {
1123 out.push('\n');
1124 }
1125}
1126
1127fn collapse_whitespace(text: &str) -> String {
1128 let mut result = String::with_capacity(text.len());
1129 let mut consecutive_newlines = 0u32;
1130
1131 for ch in text.chars() {
1132 if ch == '\n' {
1133 consecutive_newlines += 1;
1134 if consecutive_newlines <= 2 {
1135 result.push('\n');
1136 }
1137 } else {
1138 consecutive_newlines = 0;
1139 result.push(ch);
1140 }
1141 }
1142 result.trim().to_string()
1143}
1144
1145#[cfg(test)]
1146pub mod tests {
1147 use super::*;
1148
1149 #[test]
1150 fn detects_html_content() {
1151 assert!(is_html_content(
1152 "<!DOCTYPE html><html><body>hi</body></html>"
1153 ));
1154 assert!(is_html_content(
1155 " <html lang='en'><head></head><body></body></html>"
1156 ));
1157 assert!(!is_html_content("just plain text"));
1158 assert!(!is_html_content("{\"json\": true}"));
1159 }
1160
1161 #[test]
1162 fn extracts_article_element() {
1163 let html = r"
1164 <html><body>
1165 <nav>Navigation stuff</nav>
1166 <article>
1167 <h1>Title</h1>
1168 <p>Important content here.</p>
1169 </article>
1170 <footer>Footer junk</footer>
1171 </body></html>
1172 ";
1173 let result = extract_article(html);
1174 assert!(result.contains("# Title"));
1175 assert!(result.contains("Important content here."));
1176 assert!(!result.contains("Navigation stuff"));
1177 assert!(!result.contains("Footer junk"));
1178 }
1179
1180 #[test]
1181 fn extracts_main_element() {
1182 let html = r"
1183 <html><body>
1184 <header>Header</header>
1185 <main>
1186 <h2>Main Content</h2>
1187 <p>The real stuff.</p>
1188 </main>
1189 <aside>Sidebar</aside>
1190 </body></html>
1191 ";
1192 let result = extract_article(html);
1193 assert!(result.contains("## Main Content"));
1194 assert!(result.contains("The real stuff."));
1195 assert!(!result.contains("Header"));
1196 assert!(!result.contains("Sidebar"));
1197 }
1198
1199 #[test]
1200 fn preserves_code_blocks() {
1201 let html = r#"
1202 <html><body><article>
1203 <p>Example:</p>
1204 <pre><code class="language-rust">fn main() {
1205 println!("hello");
1206}</code></pre>
1207 </article></body></html>
1208 "#;
1209 let result = extract_article(html);
1210 assert!(result.contains("```rust"));
1211 assert!(result.contains("fn main()"));
1212 assert!(result.contains("```"));
1213 }
1214
1215 #[test]
1216 fn converts_links() {
1217 let html = r#"<html><body><article><p>See <a href="https://example.com">docs</a></p></article></body></html>"#;
1218 let result = extract_article(html);
1219 assert!(result.contains("[docs](https://example.com)"));
1220 }
1221
1222 #[test]
1223 fn converts_tables() {
1224 let html = r"
1225 <html><body><article>
1226 <table>
1227 <tr><th>Name</th><th>Value</th></tr>
1228 <tr><td>foo</td><td>42</td></tr>
1229 </table>
1230 </article></body></html>
1231 ";
1232 let result = extract_article(html);
1233 assert!(result.contains("| Name | Value |"));
1234 assert!(result.contains("| foo | 42 |"));
1235 }
1236
1237 #[test]
1238 fn crush_rejects_small_input() {
1239 let small = "<html><body><p>hi</p></body></html>";
1240 assert!(crush_if_beneficial(small).is_none());
1241 }
1242
1243 #[test]
1244 fn crush_is_deterministic() {
1245 let html = format!(
1246 "<html><body><nav>{}</nav><article><h1>Title</h1><p>{}</p></article><footer>{}</footer></body></html>",
1247 "x".repeat(3000),
1248 "content ".repeat(200),
1249 "y".repeat(3000)
1250 );
1251 let r1 = crush_if_beneficial(&html);
1252 let r2 = crush_if_beneficial(&html);
1253 assert_eq!(r1.as_ref().map(|r| &r.text), r2.as_ref().map(|r| &r.text));
1254 }
1255}
1256
1257#[cfg(test)]
1258pub mod edge_tests {
1259 use super::*;
1260
1261 #[test]
1262 fn handles_malformed_html_gracefully() {
1263 let broken = "<html><body><div><p>Unclosed paragraph<div>Nested wrong</p></div>";
1264 let result = extract_article(broken);
1265 assert!(result.contains("Unclosed paragraph") || result.contains("Nested wrong"));
1266 }
1267
1268 #[test]
1269 fn handles_empty_html() {
1270 let empty = "<html><body></body></html>";
1271 assert!(crush_if_beneficial(empty).is_none());
1272 }
1273
1274 #[test]
1275 fn handles_unicode_content() {
1276 let html = "<html><body><article><h1>\u{65E5}\u{672C}\u{8A9E}</h1><p>\u{00DC}nic\u{00F6}d\u{00E9} with emojis \u{1F680}</p></article></body></html>";
1277 let result = extract_article(html);
1278 assert!(result.contains("\u{65E5}\u{672C}\u{8A9E}"));
1279 assert!(result.contains("\u{1F680}"));
1280 }
1281
1282 #[test]
1283 fn handles_deeply_nested_structures() {
1284 let mut html = String::from("<html><body><article>");
1285 for i in 0..50 {
1286 html.push_str(&format!("<div><p>Level {i}</p>"));
1287 }
1288 for _ in 0..50 {
1289 html.push_str("</div>");
1290 }
1291 html.push_str("</article></body></html>");
1292 let result = extract_article(&html);
1293 assert!(result.contains("Level 0"));
1294 assert!(result.contains("Level 49"));
1295 }
1296
1297 #[test]
1298 fn handles_script_and_style_exclusion() {
1299 let html = "<html><body><article><script>var x = 'not content';</script><style>.foo{}</style><p>Real content.</p></article></body></html>";
1300 let result = extract_article(html);
1301 assert!(result.contains("Real content."));
1302 assert!(!result.contains("not content"));
1303 assert!(!result.contains(".foo"));
1304 }
1305
1306 #[test]
1307 fn handles_entities_correctly() {
1308 let html =
1309 "<html><body><article><p>5 > 3 && 2 < 4</p></article></body></html>";
1310 let result = extract_article(html);
1311 assert!(result.contains("5 > 3 && 2 < 4"));
1312 }
1313
1314 #[test]
1315 fn handles_empty_article() {
1316 let html = "<html><body><article> \n\t </article></body></html>";
1317 let result = extract_article(html);
1318 assert!(result.trim().is_empty());
1319 }
1320}