forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

markdown.rs991 lines, 30.4 KiBHistoryRawDownload
1use std::borrow::Cow;
2use std::collections::{HashMap, HashSet};
3use std::ops::Range;
4use std::sync::LazyLock;
5
6use ammonia::{Builder, UrlRelative};
7use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue};
8use comrak::{Arena, Options, format_html, parse_document};
9use forge_core::issue_refs;
10
11use crate::render::emoji::emojify;
12
13const ID_PREFIX: &str = "user-content-";
14
15const MAX_MENTION_LEN: usize = 39;
16
17const ISSUE_REF_TITLE: &str = "forge-issue-ref";
18const USER_MENTION_TITLE: &str = "forge-user-mention";
19
20const EXTERNAL_REL: &str = "nofollow noopener noreferrer";
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct LinkContext {
24 pub tree_base: String,
25 pub blob_base: String,
26 pub raw_base: String,
27 pub issues_base: Option<String>,
28}
29
30pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String {
31 let options = markdown_options();
32 let arena = Arena::new();
33 let root = parse_document(&arena, src, &options);
34
35 emojify_text(root);
36 if let Some(ctx) = ctx {
37 rewrite_links(root, &Resolver::new(ctx));
38 if let Some(issues_base) = &ctx.issues_base {
39 link_refs(&arena, root, issues_base);
40 }
41 }
42
43 let mut html = String::new();
44 if format_html(root, &options, &mut html).is_err() {
45 return String::new();
46 }
47 SANITIZER.clean(&apply_link_classes(&html)).to_string()
48}
49
50fn markdown_options() -> Options<'static> {
51 let mut options = Options::default();
52 options.extension.table = true;
53 options.extension.tasklist = true;
54 options.extension.strikethrough = true;
55 options.extension.autolink = true;
56 options.extension.footnotes = true;
57 options.extension.alerts = true;
58 options.extension.math_dollars = true;
59 options.extension.header_id_prefix = Some(ID_PREFIX.to_string());
60 options.render.r#unsafe = true;
61 options
62}
63
64struct Resolver {
65 tree_root: String,
66 blob_root: String,
67 raw_root: String,
68 dir: Vec<String>,
69}
70
71impl Resolver {
72 fn new(ctx: &LinkContext) -> Self {
73 let blob = ctx.blob_base.trim_end_matches('/');
74 let depth = dir_depth(blob);
75 let segments: Vec<&str> = blob.split('/').collect();
76 let dir: Vec<String> = segments[segments.len() - depth..]
77 .iter()
78 .filter(|seg| !seg.is_empty())
79 .map(|s| s.to_string())
80 .collect();
81 Self {
82 tree_root: strip_segments(&ctx.tree_base, depth),
83 blob_root: strip_segments(&ctx.blob_base, depth),
84 raw_root: strip_segments(&ctx.raw_base, depth),
85 dir,
86 }
87 }
88
89 fn rewrite(&self, url: &str, image: bool) -> Option<String> {
90 if url.is_empty()
91 || url.starts_with("//")
92 || has_scheme(url)
93 || url.starts_with("/attachments/")
94 {
95 return None;
96 }
97 if let Some(fragment) = url.strip_prefix('#') {
98 if fragment.is_empty() {
99 return None;
100 }
101 return Some(format!("#{ID_PREFIX}{fragment}"));
102 }
103
104 let split = url.find(['?', '#']).unwrap_or(url.len());
105 let (path, suffix) = url.split_at(split);
106 let start: &[String] = if path.starts_with('/') {
107 &[]
108 } else {
109 &self.dir
110 };
111 let segments = normalize(start, path);
112
113 if image {
114 return Some(join(&self.raw_root, &segments, suffix));
115 }
116 if segments.is_empty() || path.ends_with('/') {
117 Some(join(&self.tree_root, &segments, suffix))
118 } else {
119 Some(join(&self.blob_root, &segments, suffix))
120 }
121 }
122}
123
124fn dir_depth(base: &str) -> usize {
125 let segments: Vec<&str> = base.split('/').collect();
126 segments
127 .iter()
128 .enumerate()
129 .skip(3)
130 .find(|(i, seg)| (**seg == "blob" || **seg == "tree") && i + 1 < segments.len())
131 .map_or(0, |(i, _)| segments.len() - (i + 2))
132}
133
134fn strip_segments(base: &str, n: usize) -> String {
135 let mut out = base.trim_end_matches('/');
136 for _ in 0..n {
137 match out.rfind('/') {
138 Some(i) => out = &out[..i],
139 None => break,
140 }
141 }
142 out.to_string()
143}
144
145fn normalize(start: &[String], path: &str) -> Vec<String> {
146 let mut out = start.to_vec();
147 for seg in path.split('/') {
148 match seg {
149 "" | "." => {}
150 ".." => {
151 out.pop();
152 }
153 other => out.push(other.to_string()),
154 }
155 }
156 out
157}
158
159fn join(root: &str, segments: &[String], suffix: &str) -> String {
160 if segments.is_empty() {
161 format!("{root}{suffix}")
162 } else {
163 format!("{root}/{}{suffix}", segments.join("/"))
164 }
165}
166
167fn has_scheme(url: &str) -> bool {
168 match url.find(':') {
169 Some(i) if i > 0 => {
170 let scheme = &url[..i];
171 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
172 && scheme
173 .chars()
174 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
175 }
176 _ => false,
177 }
178}
179
180fn emojify_text<'a>(root: &'a AstNode<'a>) {
181 for node in root.descendants() {
182 let in_link = node
183 .parent()
184 .is_some_and(|parent| matches!(parent.data.borrow().value, NodeValue::Link(_)));
185 if in_link {
186 continue;
187 }
188 let mut ast = node.data.borrow_mut();
189 if let NodeValue::Text(text) = &mut ast.value {
190 let replaced = match emojify(text.as_ref()) {
191 Cow::Owned(s) => Some(s),
192 Cow::Borrowed(_) => None,
193 };
194 if let Some(s) = replaced {
195 *text = s.into();
196 }
197 }
198 }
199}
200
201fn rewrite_links<'a>(root: &'a AstNode<'a>, resolver: &Resolver) {
202 for node in root.descendants() {
203 let mut ast = node.data.borrow_mut();
204 match &mut ast.value {
205 NodeValue::Link(link) => {
206 if let Some(url) = resolver.rewrite(&link.url, false) {
207 link.url = url;
208 }
209 }
210 NodeValue::Image(link) => {
211 if let Some(url) = resolver.rewrite(&link.url, true) {
212 link.url = url;
213 }
214 }
215 _ => {}
216 }
217 }
218}
219
220fn apply_link_classes(html: &str) -> String {
221 html.replace(
222 &format!("title=\"{ISSUE_REF_TITLE}\""),
223 "class=\"issue-ref\"",
224 )
225 .replace(
226 &format!("title=\"{USER_MENTION_TITLE}\""),
227 "class=\"user-mention\"",
228 )
229}
230
231fn link_refs<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>, issues_base: &str) {
232 let targets: Vec<&'a AstNode<'a>> = root
233 .descendants()
234 .filter(|node| {
235 matches!(
236 node.data.borrow().value,
237 NodeValue::Text(_) | NodeValue::HtmlBlock(_)
238 ) && !node.ancestors().skip(1).any(|ancestor| {
239 matches!(
240 ancestor.data.borrow().value,
241 NodeValue::Link(_) | NodeValue::Image(_)
242 )
243 })
244 })
245 .collect();
246
247 for node in targets {
248 let (sourcepos, value) = {
249 let ast = node.data.borrow();
250 (ast.sourcepos, ast.value.clone())
251 };
252 match value {
253 NodeValue::Text(text) => {
254 if let Some(nodes) = text_with_links(arena, sourcepos, &text, issues_base) {
255 for new in nodes {
256 node.insert_before(new);
257 }
258 node.detach();
259 }
260 }
261 NodeValue::HtmlBlock(block) => {
262 let literal = block.literal.trim_end_matches('\n').to_string();
263 let mut children = Vec::new();
264 let mut linked = false;
265 for piece in split_html(&literal) {
266 match piece {
267 HtmlPiece::Html(html) => {
268 children.push(new_node(arena, sourcepos, NodeValue::HtmlInline(html)))
269 }
270 HtmlPiece::Text(raw) => {
271 let text = decode_entities(&raw);
272 match text_with_links(arena, sourcepos, &text, issues_base) {
273 Some(nodes) => {
274 linked = true;
275 children.extend(nodes);
276 }
277 None => children.push(new_node(
278 arena,
279 sourcepos,
280 NodeValue::Text(text.into()),
281 )),
282 }
283 }
284 }
285 }
286 if linked {
287 node.data.borrow_mut().value = NodeValue::Paragraph;
288 for child in children {
289 node.append(child);
290 }
291 }
292 }
293 _ => {}
294 }
295 }
296}
297
298fn text_with_links<'a>(
299 arena: &'a Arena<'a>,
300 sourcepos: comrak::nodes::Sourcepos,
301 text: &str,
302 issues_base: &str,
303) -> Option<Vec<&'a AstNode<'a>>> {
304 let mut spans: Vec<(Range<usize>, Option<i64>)> = issue_refs::issue_ref_spans(text)
305 .into_iter()
306 .map(|(range, n)| (range, Some(n)))
307 .chain(mention_spans(text).into_iter().map(|range| (range, None)))
308 .collect();
309 if spans.is_empty() {
310 return None;
311 }
312 spans.sort_by_key(|(range, _)| range.start);
313
314 let mut out = Vec::new();
315 let mut cursor = 0;
316 for (range, issue) in spans {
317 if range.start > cursor {
318 out.push(new_node(
319 arena,
320 sourcepos,
321 NodeValue::Text(text[cursor..range.start].to_string().into()),
322 ));
323 }
324 let label = &text[range.clone()];
325 let link = match issue {
326 Some(n) => new_node(
327 arena,
328 sourcepos,
329 NodeValue::Link(Box::new(NodeLink::new(
330 format!("{issues_base}/{n}"),
331 ISSUE_REF_TITLE.to_string(),
332 ))),
333 ),
334 None => new_node(
335 arena,
336 sourcepos,
337 NodeValue::Link(Box::new(NodeLink::new(
338 format!("/{}", &label[1..]),
339 USER_MENTION_TITLE.to_string(),
340 ))),
341 ),
342 };
343 link.append(new_node(
344 arena,
345 sourcepos,
346 NodeValue::Text(label.to_string().into()),
347 ));
348 out.push(link);
349 cursor = range.end;
350 }
351 if cursor < text.len() {
352 out.push(new_node(
353 arena,
354 sourcepos,
355 NodeValue::Text(text[cursor..].to_string().into()),
356 ));
357 }
358 Some(out)
359}
360
361#[derive(Debug, PartialEq, Eq)]
362enum HtmlPiece {
363 Html(String),
364 Text(String),
365}
366
367const RAW_TEXT_TAGS: &[&str] = &["script", "style", "textarea", "title"];
368
369const NO_LINK_TAGS: &[&str] = &["a", "code", "pre"];
370
371fn split_html(src: &str) -> Vec<HtmlPiece> {
372 let lower = src.to_ascii_lowercase();
373 let mut segments: Vec<(bool, Range<usize>)> = Vec::new();
374 let mut prev = 0;
375 let mut depth = 0usize;
376 let mut i = 0;
377 while let Some(off) = src[i..].find('<') {
378 let lt = i + off;
379 let end = if src[lt..].starts_with("<!--") {
380 src[lt..].find("-->").map_or(src.len(), |p| lt + p + 3)
381 } else {
382 match src[lt..].find('>') {
383 Some(p) => lt + p + 1,
384 None => break,
385 }
386 };
387 let inner = src[lt + 1..end].trim_end_matches('>');
388 let closing = inner.starts_with('/');
389 let name: String = inner
390 .trim_start_matches('/')
391 .chars()
392 .take_while(|c| c.is_ascii_alphanumeric())
393 .collect::<String>()
394 .to_ascii_lowercase();
395
396 if lt > prev {
397 segments.push((depth == 0, prev..lt));
398 }
399 let mut tag_end = end;
400 if !closing && RAW_TEXT_TAGS.contains(&name.as_str()) {
401 let close = format!("</{name}");
402 if let Some(p) = lower[end..].find(&close) {
403 let close_start = end + p;
404 tag_end = lower[close_start..]
405 .find('>')
406 .map_or(src.len(), |g| close_start + g + 1);
407 }
408 }
409 segments.push((false, lt..tag_end));
410 if NO_LINK_TAGS.contains(&name.as_str()) {
411 if closing {
412 depth = depth.saturating_sub(1);
413 } else {
414 depth += 1;
415 }
416 }
417 prev = tag_end;
418 i = tag_end;
419 }
420 if prev < src.len() {
421 segments.push((depth == 0, prev..src.len()));
422 }
423
424 let mut out: Vec<HtmlPiece> = Vec::new();
425 for (is_text, range) in segments {
426 let piece = &src[range];
427 let next = if is_text {
428 HtmlPiece::Text(piece.to_string())
429 } else {
430 HtmlPiece::Html(piece.to_string())
431 };
432 match (out.last_mut(), next) {
433 (Some(HtmlPiece::Html(prev_html)), HtmlPiece::Html(html)) => prev_html.push_str(&html),
434 (Some(HtmlPiece::Text(prev_text)), HtmlPiece::Text(text)) => prev_text.push_str(&text),
435 (_, next) => out.push(next),
436 }
437 }
438 out
439}
440
441fn decode_entities(text: &str) -> String {
442 let mut out = String::with_capacity(text.len());
443 let mut rest = text;
444 while let Some(amp) = rest.find('&') {
445 out.push_str(&rest[..amp]);
446 let from_amp = &rest[amp..];
447 match decode_entity(from_amp) {
448 Some((ch, len)) => {
449 out.push(ch);
450 rest = &from_amp[len..];
451 }
452 None => {
453 out.push('&');
454 rest = &from_amp[1..];
455 }
456 }
457 }
458 out.push_str(rest);
459 out
460}
461
462fn decode_entity(s: &str) -> Option<(char, usize)> {
463 let end = s.find(';')?;
464 if end > 12 {
465 return None;
466 }
467 let body = &s[1..end];
468 let ch = if let Some(hex) = body.strip_prefix("#x").or_else(|| body.strip_prefix("#X")) {
469 if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
470 return None;
471 }
472 char::from_u32(u32::from_str_radix(hex, 16).ok()?)?
473 } else if let Some(dec) = body.strip_prefix('#') {
474 if dec.is_empty() || !dec.bytes().all(|b| b.is_ascii_digit()) {
475 return None;
476 }
477 char::from_u32(dec.parse().ok()?)?
478 } else {
479 match body {
480 "amp" => '&',
481 "lt" => '<',
482 "gt" => '>',
483 "quot" => '"',
484 "apos" => '\'',
485 "nbsp" => '\u{a0}',
486 _ => return None,
487 }
488 };
489 Some((ch, end + 1))
490}
491
492fn new_node<'a>(
493 arena: &'a Arena<'a>,
494 sourcepos: comrak::nodes::Sourcepos,
495 value: NodeValue,
496) -> &'a AstNode<'a> {
497 arena.alloc(comrak::arena_tree::Node::new(std::cell::RefCell::new(
498 Ast::new_with_sourcepos(value, sourcepos),
499 )))
500}
501
502fn mention_spans(text: &str) -> Vec<Range<usize>> {
503 let bytes = text.as_bytes();
504 let mut out = Vec::new();
505 for (at, _) in text.match_indices('@') {
506 if text[..at]
507 .chars()
508 .next_back()
509 .is_some_and(|c| !c.is_whitespace())
510 {
511 continue;
512 }
513 let run = bytes[at + 1..]
514 .iter()
515 .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
516 .count();
517 let name = text[at + 1..at + 1 + run].trim_end_matches('.');
518 if name.is_empty() || name.len() > MAX_MENTION_LEN {
519 continue;
520 }
521 out.push(at..at + 1 + name.len());
522 }
523 out
524}
525
526pub fn mentioned_usernames(text: &str) -> Vec<String> {
527 let options = markdown_options();
528 let arena = Arena::new();
529 let root = parse_document(&arena, text, &options);
530
531 let mut found: Vec<String> = Vec::new();
532 for node in root.descendants() {
533 let ast = node.data.borrow();
534 let inside_link = node.ancestors().skip(1).any(|ancestor| {
535 matches!(
536 ancestor.data.borrow().value,
537 NodeValue::Link(_) | NodeValue::Image(_)
538 )
539 });
540 if inside_link {
541 continue;
542 }
543 match &ast.value {
544 NodeValue::Text(literal) => collect_mentions(literal, &mut found),
545 NodeValue::HtmlBlock(block) => {
546 let literal = block.literal.trim_end_matches('\n');
547 for piece in split_html(literal) {
548 if let HtmlPiece::Text(raw) = piece {
549 collect_mentions(&decode_entities(&raw), &mut found);
550 }
551 }
552 }
553 _ => {}
554 }
555 }
556 found
557}
558
559fn task_marks(src: &str) -> Vec<(usize, bool)> {
560 let options = markdown_options();
561 let arena = Arena::new();
562 let root = parse_document(&arena, src, &options);
563 let mut line_starts = vec![0usize];
564 for (i, b) in src.bytes().enumerate() {
565 if b == b'\n' {
566 line_starts.push(i + 1);
567 }
568 }
569 let mut out = Vec::new();
570 for node in root.descendants() {
571 if let NodeValue::TaskItem(item) = &node.data.borrow().value {
572 let pos = item.symbol_sourcepos.start;
573 let Some(line) = line_starts.get(pos.line.wrapping_sub(1)) else {
574 continue;
575 };
576 let at = line + pos.column.saturating_sub(1);
577 if at < src.len() && src.is_char_boundary(at) {
578 out.push((at, item.symbol.is_some()));
579 }
580 }
581 }
582 out
583}
584
585pub fn task_progress(src: &str) -> (usize, usize) {
586 let marks = task_marks(src);
587 (marks.iter().filter(|(_, done)| *done).count(), marks.len())
588}
589
590pub fn set_task(src: &str, index: usize, checked: bool) -> Option<String> {
591 let (at, _) = *task_marks(src).get(index)?;
592 let mark = src[at..].chars().next()?;
593 let before = src[..at].chars().next_back()?;
594 if before != '[' || !(mark == ' ' || mark == 'x' || mark == 'X') {
595 return None;
596 }
597 let mut out = String::with_capacity(src.len());
598 out.push_str(&src[..at]);
599 out.push(if checked { 'x' } else { ' ' });
600 out.push_str(&src[at + mark.len_utf8()..]);
601 Some(out)
602}
603
604fn collect_mentions(text: &str, found: &mut Vec<String>) {
605 for range in mention_spans(text) {
606 let name = text[range.start + 1..range.end].to_ascii_lowercase();
607 if !found.contains(&name) {
608 found.push(name);
609 }
610 }
611}
612
613const TAGS: &[&str] = &[
614 "h1",
615 "h2",
616 "h3",
617 "h4",
618 "h5",
619 "h6",
620 "p",
621 "a",
622 "img",
623 "ul",
624 "ol",
625 "li",
626 "input",
627 "table",
628 "thead",
629 "tbody",
630 "tr",
631 "th",
632 "td",
633 "pre",
634 "code",
635 "blockquote",
636 "hr",
637 "br",
638 "em",
639 "strong",
640 "del",
641 "sup",
642 "sub",
643 "details",
644 "summary",
645 "kbd",
646 "div",
647 "span",
648 "section",
649];
650
651const CLASSES: &[&str] = &[
652 "markdown-alert",
653 "markdown-alert-note",
654 "markdown-alert-tip",
655 "markdown-alert-important",
656 "markdown-alert-warning",
657 "markdown-alert-caution",
658 "markdown-alert-title",
659 "footnote-ref",
660 "footnote-backref",
661 "footnotes",
662 "task-list-item",
663 "sr-only",
664 "anchor",
665 "issue-ref",
666 "user-mention",
667];
668
669const SCRIPT_LIKE: &[&str] = &[
670 "script", "style", "iframe", "object", "embed", "noscript", "template", "textarea", "title",
671 "svg", "math", "form",
672];
673
674static SANITIZER: LazyLock<Builder<'static>> = LazyLock::new(sanitizer);
675
676fn sanitizer() -> Builder<'static> {
677 let tags: HashSet<&'static str> = TAGS.iter().copied().collect();
678 let clean_content: HashSet<&'static str> = SCRIPT_LIKE.iter().copied().collect();
679 let classes: HashSet<&'static str> = CLASSES.iter().copied().collect();
680 let allowed_classes: HashMap<&'static str, HashSet<&'static str>> =
681 TAGS.iter().map(|tag| (*tag, classes.clone())).collect();
682
683 let attrs: HashMap<&'static str, HashSet<&'static str>> = [
684 ("h1", &["id"][..]),
685 ("h2", &["id"]),
686 ("h3", &["id"]),
687 ("h4", &["id"]),
688 ("h5", &["id"]),
689 ("h6", &["id"]),
690 (
691 "a",
692 &[
693 "href",
694 "title",
695 "id",
696 "data-footnote-ref",
697 "data-footnote-backref",
698 ],
699 ),
700 ("img", &["src", "alt", "title", "width", "height"]),
701 ("ol", &["start"]),
702 ("li", &["id"]),
703 ("sup", &["id"]),
704 ("section", &["id", "data-footnotes"]),
705 ("pre", &["lang"]),
706 ("td", &["align"]),
707 ("th", &["align"]),
708 ("input", &["type", "checked", "disabled"]),
709 ("details", &["open"]),
710 ("span", &["data-math-style"]),
711 ]
712 .into_iter()
713 .map(|(tag, names)| (tag, names.iter().copied().collect()))
714 .collect();
715
716 let mut builder = Builder::empty();
717 builder
718 .tags(tags)
719 .clean_content_tags(clean_content)
720 .tag_attributes(attrs)
721 .generic_attributes(HashSet::from([
722 "aria-label",
723 "aria-describedby",
724 "aria-hidden",
725 ]))
726 .allowed_classes(allowed_classes)
727 .url_schemes(HashSet::from(["http", "https", "mailto"]))
728 .url_relative(UrlRelative::PassThrough)
729 .link_rel(Some(EXTERNAL_REL))
730 .set_tag_attribute_value("input", "type", "checkbox");
731 builder
732}
733
734#[cfg(test)]
735mod tests {
736 use super::*;
737
738 fn ctx() -> LinkContext {
739 LinkContext {
740 tree_base: "https://forge.test/o/r/tree/main/guide".to_string(),
741 blob_base: "https://forge.test/o/r/blob/main/guide".to_string(),
742 raw_base: "https://raw.test/o/r/main/guide".to_string(),
743 issues_base: None,
744 }
745 }
746
747 fn issue_ctx() -> LinkContext {
748 LinkContext {
749 issues_base: Some("/o/r/issues".to_string()),
750 ..ctx()
751 }
752 }
753
754 const CONTAINS_CASES: &[(&str, bool, &[&str])] = &[
755 (
756 "$x^2$ and ![a](/attachments/abc/a.png)",
757 true,
758 &[
759 "data-math-style=\"inline\"",
760 "src=\"/attachments/abc/a.png\"",
761 ],
762 ),
763 (
764 "| a | b |\n|:-|-:|\n| 1 | 2 |\n\n- [x] done\n- [ ] todo\n",
765 false,
766 &["<table>", "<td", "type=\"checkbox\"", "checked"],
767 ),
768 (
769 "<details><summary>More</summary>\n\nHidden text\n\n</details>\n",
770 false,
771 &["<details>", "<summary>More</summary>"],
772 ),
773 ("# Hello World", false, &["id=\"user-content-hello-world\""]),
774 (
775 "[t](#hello-world)",
776 true,
777 &["href=\"#user-content-hello-world\""],
778 ),
779 (
780 "[x](docs/a.md)",
781 true,
782 &["href=\"https://forge.test/o/r/blob/main/guide/docs/a.md\""],
783 ),
784 (
785 "[d](../sub/)\n\n[e](../../../../x.md)",
786 true,
787 &[
788 "href=\"https://forge.test/o/r/tree/main/sub\"",
789 "href=\"https://forge.test/o/r/blob/main/x.md\"",
790 ],
791 ),
792 (
793 "![i](../img.png)",
794 true,
795 &["src=\"https://raw.test/o/r/main/img.png\""],
796 ),
797 (
798 "[r](/README.md#top) [s](/a/../b.md)",
799 true,
800 &[
801 "href=\"https://forge.test/o/r/blob/main/README.md#top\"",
802 "href=\"https://forge.test/o/r/blob/main/b.md\"",
803 ],
804 ),
805 (
806 "[g](https://example.com/a?b=1)",
807 true,
808 &[
809 "href=\"https://example.com/a?b=1\"",
810 "rel=\"nofollow noopener noreferrer\"",
811 ],
812 ),
813 ("[x](docs/a.md)", false, &["href=\"docs/a.md\""]),
814 ];
815
816 #[test]
817 fn rendered_html_contains_expected_fragments() {
818 for (src, with_ctx, needles) in CONTAINS_CASES {
819 let lc = ctx();
820 let html = render_markdown(src, with_ctx.then_some(&lc));
821 for needle in needles.iter() {
822 assert!(
823 html.contains(needle),
824 "case {src:?} missing {needle:?}: {html}"
825 );
826 }
827 }
828 }
829
830 #[test]
831 fn tasks_are_counted_and_toggled() {
832 let src = "- [ ] one\n- [x] two\n - [ ] nested\n\n```\n- [ ] code\n```\n";
833 assert_eq!(task_progress(src), (1, 3));
834 let on = set_task(src, 0, true).unwrap();
835 assert!(on.starts_with("- [x] one\n"), "{on}");
836 let off = set_task(&on, 1, false).unwrap();
837 assert!(off.contains("- [ ] two"), "{off}");
838 assert_eq!(set_task(src, 2, true).unwrap().matches("[x]").count(), 2);
839 assert!(set_task(src, 3, true).is_none());
840 assert!(set_task("no tasks", 0, true).is_none());
841 }
842
843 #[test]
844 fn issue_refs_and_mentions_are_linked() {
845 let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx()));
846 assert!(html.contains("href=\"/o/r/issues/12\""), "{html}");
847 assert!(html.contains("class=\"issue-ref\""), "{html}");
848 assert!(html.contains(">#12</a>"), "{html}");
849 assert!(html.contains("href=\"/o/r/issues/3\""), "{html}");
850 assert!(html.contains(">#3</a>"), "{html}");
851 assert!(html.contains("href=\"/tahinli\""), "{html}");
852 assert!(html.contains("class=\"user-mention\""), "{html}");
853 assert!(html.contains(">@tahinli</a>."), "{html}");
854 assert!(!html.contains("title="), "{html}");
855 }
856
857 fn assert_all_links_have_rel(html: &str) {
858 let mut count = 0;
859 for (at, _) in html.match_indices("<a") {
860 if !matches!(html[at + 2..].chars().next(), Some(' ' | '>')) {
861 continue;
862 }
863 count += 1;
864 let tag_end = html[at..].find('>').expect("unclosed tag");
865 let tag = &html[at..at + tag_end];
866 assert!(
867 tag.contains("rel=\"nofollow noopener noreferrer\""),
868 "{html}"
869 );
870 }
871 assert!(count > 0, "{html}");
872 }
873
874 #[test]
875 fn raw_html_links_always_get_rel() {
876 let html = render_markdown(
877 "<a title=\"x\" href='https://spam.example'>s</a>\n\n\
878 <a href=\"https://x.example\">x</a>\n\n<a href=\"/internal\">i</a>\n",
879 Some(&ctx()),
880 );
881 assert_all_links_have_rel(&html);
882 assert!(html.contains("href=\"https://spam.example\""), "{html}");
883 assert_all_links_have_rel(&render_markdown(
884 "<a title=\"x\" href='https://spam.example'>s</a>\n\n<a href=\"https://x.example\">x</a>",
885 None,
886 ));
887 }
888
889 #[test]
890 fn html_block_entities_are_not_double_escaped() {
891 let html = render_markdown("<div>Tom &amp; Jerry #3</div>\n", Some(&issue_ctx()));
892 assert!(html.contains("Tom &amp; Jerry"), "{html}");
893 assert!(!html.contains("&amp;amp;"), "{html}");
894 assert!(html.contains("class=\"issue-ref\""), "{html}");
895 assert!(html.contains(">#3</a>"), "{html}");
896 }
897
898 #[test]
899 fn decode_entities_handles_known_and_unknown() {
900 assert_eq!(
901 decode_entities("a &amp; b &lt;&#39;&#x41;&gt;"),
902 "a & b <'A>"
903 );
904 assert_eq!(decode_entities("&nbsp;&quot;&apos;"), "\u{a0}\"'");
905 assert_eq!(
906 decode_entities("&bogus; & &#; &#xZZ; &"),
907 "&bogus; & &#; &#xZZ; &"
908 );
909 assert_eq!(decode_entities("&#0;"), "\0");
910 }
911
912 #[test]
913 fn refs_in_code_are_not_linked() {
914 let html = render_markdown(
915 "`#12` and @bob\n\n```\n#13 @carol\n```\n",
916 Some(&issue_ctx()),
917 );
918 assert!(!html.contains("issue-ref"), "{html}");
919 assert_eq!(html.matches("user-mention").count(), 1, "{html}");
920 assert!(html.contains(">@bob</a>"), "{html}");
921 assert!(!html.contains("@carol</a>"), "{html}");
922 assert!(html.contains("<code>#12</code>"), "{html}");
923 }
924
925 #[test]
926 fn refs_inside_existing_links_are_not_doubled() {
927 let html = render_markdown("[see #5 and @dan](https://example.com)", Some(&issue_ctx()));
928 assert!(!html.contains("issue-ref"), "{html}");
929 assert!(!html.contains("user-mention"), "{html}");
930 assert_eq!(html.matches("<a ").count(), 1, "{html}");
931 }
932
933 #[test]
934 fn script_is_still_stripped_with_linking_on() {
935 let html = render_markdown("<script>alert(1)</script> #7", Some(&issue_ctx()));
936 assert!(!html.contains("script"), "{html}");
937 assert!(html.contains("class=\"issue-ref\""), "{html}");
938 assert!(html.contains(">#7</a>"), "{html}");
939 }
940
941 #[test]
942 fn no_issues_base_means_no_linking() {
943 let html = render_markdown("#12 @tahinli", Some(&ctx()));
944 assert!(!html.contains("issue-ref"), "{html}");
945 assert!(!html.contains("user-mention"), "{html}");
946 assert!(html.contains("#12 @tahinli"), "{html}");
947 }
948
949 #[test]
950 fn email_is_not_a_mention() {
951 let html = render_markdown("write to a@b.com or @ alone", Some(&issue_ctx()));
952 assert!(!html.contains("user-mention"), "{html}");
953 assert!(html.contains("a@b.com"), "{html}");
954 }
955
956 #[test]
957 fn mention_names_follow_the_rules() {
958 assert_eq!(mention_spans("@bob."), vec![0..4]);
959 assert!(mention_spans(&format!("@{}", "a".repeat(40))).is_empty());
960 assert_eq!(mention_spans(&format!("@{}", "a".repeat(39))), vec![0..40]);
961 assert!(mention_spans("@.").is_empty());
962 assert_eq!(mention_spans("x @a, @b_c-d"), vec![2..4, 6..12]);
963 }
964
965 #[test]
966 fn dangerous_markup_is_stripped() {
967 let html = render_markdown(
968 "<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n\
969 <img src=x onerror=alert(1)>\n\n<span style=\"color:red\">s</span>\n",
970 None,
971 );
972 assert!(!html.contains("script"), "{html}");
973 assert!(!html.contains("javascript:"), "{html}");
974 assert!(!html.contains("onerror"), "{html}");
975 assert!(!html.contains("style"), "{html}");
976 assert!(html.contains(">x</a>"), "{html}");
977 }
978
979 #[test]
980 fn emoji_shortcodes_convert_outside_code() {
981 let html = render_markdown(
982 "party :tada: and `:tada:` and\n\n```\n:tada:\n```\n\n:spark:\n",
983 None,
984 );
985 assert!(html.contains("party 🎉 and"), "{html}");
986 assert!(html.contains("<code>:tada:</code>"), "{html}");
987 assert!(html.contains("<pre"), "{html}");
988 assert!(html.contains(":spark:"), "{html}");
989 assert!(!html.contains("<code>🎉</code>"), "{html}");
990 }
991}