Skip to main content

hexicon_host/
rich.rs

1//! The rich display's checker: turns what a program writes into a document
2//! within Hexicon's profile of HTML and CSS.
3//!
4//! A program writes text with markup in it, in pieces, as it goes: HTML
5//! TADS's tags (HTML 3.2 and its own, such as `<sound>` and `<bq>`), the
6//! profile's additions (`class`, `style`, `<span>`, `<figure>`), named and
7//! numbered entities, and the control characters strings compile to (`\n`,
8//! `\b`, `\^`). The checker reads it a character at a time, so a tag or an
9//! entity can be split between pieces, and gives out [`Item`]s:
10//!
11//! - TADS's own tags turned into the page's (`<bq>` is `<blockquote>`,
12//!   `<nobr>` a `<span>` that does not wrap), or kept as elements the page
13//!   handles itself (`<sound>`, `<title>`, `<aboutbox>`, `<body>`);
14//! - only the elements and attributes the profile lists, and in `style`
15//!   only the CSS properties it lists. Anything else is dropped: a script
16//!   and what is in it, an `onclick`, a link or a picture that names
17//!   anything outside the game's own resources;
18//! - elements opened and closed in a well-formed order, however the
19//!   program wrote them.
20//!
21//! Every rich host shows the same items, so the browser and the desktop
22//! program show the same document. [`Item::markup`] writes an item as
23//! text, which is how tests compare a game's document.
24
25use std::collections::HashSet;
26
27use crate::entities;
28
29/// What a rich display can do, and what the player has chosen.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct RichDisplay {
32    /// Pictures: JPEG, PNG, SVG, and WebP.
33    pub pictures: bool,
34    /// Sounds: WAV, Ogg, and MP3.
35    pub sounds: bool,
36    /// The player wants pictures shown.
37    pub show_pictures: bool,
38    /// The player wants sounds played.
39    pub play_sounds: bool,
40    /// The player wants music played.
41    pub play_music: bool,
42    /// The player wants links in the text.
43    pub links: bool,
44}
45
46impl RichDisplay {
47    /// A display that can do everything, with everything turned on.
48    pub fn full() -> Self {
49        RichDisplay {
50            pictures: true,
51            sounds: true,
52            show_pictures: true,
53            play_sounds: true,
54            play_music: true,
55            links: true,
56        }
57    }
58}
59
60/// An attribute, as the checker keeps it: a name in lower case, and its
61/// value with entities replaced, or `None` for one written without a
62/// value (`<img ismap>`).
63pub type Attr = (String, Option<String>);
64
65/// One piece of the checked document.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum Item {
68    /// Text, with entities replaced and nothing to escape.
69    Text(String),
70    /// An element that holds others, opened.
71    Open(String, Vec<Attr>),
72    /// The element opened most recently, and not yet closed, closed.
73    Close(String),
74    /// An element that holds nothing: `<br>`, `<img>`, `<hr>`, `<area>`,
75    /// and the page's own `<sound>`, `<body>`, and `<tab>`.
76    Void(String, Vec<Attr>),
77    /// The window's title.
78    Title(String),
79    /// A line the player typed, shown as it is.
80    Input(String),
81}
82
83impl Item {
84    /// The item as the profile's markup. Each line break, block, and
85    /// input ends a line, so that a document reads, and compares, as a
86    /// transcript does.
87    pub fn markup(&self) -> String {
88        match self {
89            Item::Text(text) => escape(text, false),
90            Item::Open(name, attrs) => format!("<{name}{}>", attrs_markup(attrs)),
91            Item::Close(name) => {
92                let end = if is_block(name) { "\n" } else { "" };
93                format!("</{name}>{end}")
94            }
95            Item::Void(name, attrs) => {
96                let end = if name == "br" || name == "hr" || name == "body" {
97                    "\n"
98                } else {
99                    ""
100                };
101                format!("<{name}{}>{end}", attrs_markup(attrs))
102            }
103            Item::Title(text) => format!("<title>{}</title>\n", escape(text, false)),
104            Item::Input(text) => format!("<kbd>{}</kbd>\n", escape(text, false)),
105        }
106    }
107}
108
109fn attrs_markup(attrs: &[Attr]) -> String {
110    let mut out = String::new();
111    for (name, value) in attrs {
112        out.push(' ');
113        out.push_str(name);
114        if let Some(value) = value {
115            out.push_str("=\"");
116            out.push_str(&escape(value, true));
117            out.push('"');
118        }
119    }
120    out
121}
122
123fn escape(text: &str, attr: bool) -> String {
124    let mut out = String::with_capacity(text.len());
125    for c in text.chars() {
126        match c {
127            '&' => out.push_str("&amp;"),
128            '<' => out.push_str("&lt;"),
129            '>' if attr => out.push_str("&gt;"),
130            '"' if attr => out.push_str("&quot;"),
131            '\u{a0}' => out.push_str("&nbsp;"),
132            _ => out.push(c),
133        }
134    }
135    out
136}
137
138// ---- the profile ----
139
140/// Elements that hold nothing.
141const VOID: &[&str] = &[
142    "br", "img", "hr", "area", "wbr", "sound", "body", "tab", "basefont",
143];
144
145/// Elements that hold others, and are kept as they are.
146const CONTAINERS: &[&str] = &[
147    // HTML 3.2, as HTML TADS has it.
148    "a",
149    "address",
150    "b",
151    "big",
152    "blockquote",
153    "caption",
154    "center",
155    "cite",
156    "code",
157    "dd",
158    "dfn",
159    "dir",
160    "div",
161    "dl",
162    "dt",
163    "em",
164    "font",
165    "h1",
166    "h2",
167    "h3",
168    "h4",
169    "h5",
170    "h6",
171    "i",
172    "kbd",
173    "li",
174    "map",
175    "menu",
176    "ol",
177    "p",
178    "pre",
179    "q",
180    "s",
181    "samp",
182    "small",
183    "strike",
184    "strong",
185    "sub",
186    "sup",
187    "table",
188    "td",
189    "th",
190    "tr",
191    "tt",
192    "u",
193    "ul",
194    "var",
195    // The profile's additions.
196    "span",
197    "figure",
198    "figcaption",
199    // The page's own: what the about box shows, and a banner's text.
200    "aboutbox",
201    "banner",
202];
203
204/// Elements dropped with everything in them.
205const DROPPED_WITH_CONTENTS: &[&str] = &[
206    "script", "style", "iframe", "object", "embed", "noscript", "template", "frameset", "frame",
207    "form", "select", "textarea", "button", "head", "svg", "math",
208];
209
210/// Attributes any kept element may have.
211const GLOBAL_ATTRS: &[&str] = &["class", "style", "title", "lang", "dir"];
212
213/// The attributes each element may have, besides the global ones.
214fn element_attrs(name: &str) -> &'static [&'static str] {
215    match name {
216        "a" => &["href", "plain", "append", "noenter"],
217        "img" => &[
218            "src", "alt", "width", "height", "border", "align", "hspace", "vspace", "usemap",
219            "ismap", "asrc", "hsrc",
220        ],
221        "area" => &[
222            "shape", "coords", "href", "nohref", "alt", "append", "noenter",
223        ],
224        "map" => &["name"],
225        "font" => &["face", "size", "color", "bgcolor"],
226        "basefont" => &["size", "face", "color"],
227        "table" => &[
228            "border",
229            "cellpadding",
230            "cellspacing",
231            "width",
232            "height",
233            "align",
234            "bgcolor",
235            "background",
236        ],
237        "tr" => &["align", "valign", "bgcolor", "background"],
238        "td" | "th" => &[
239            "align",
240            "valign",
241            "width",
242            "height",
243            "colspan",
244            "rowspan",
245            "nowrap",
246            "bgcolor",
247            "background",
248        ],
249        "caption" => &["align", "valign"],
250        "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "center" => &["align"],
251        "br" => &["clear", "height"],
252        "hr" => &["width", "size", "align", "noshade", "src"],
253        "ol" => &["start", "type", "compact"],
254        "ul" | "dir" | "menu" => &["type", "compact"],
255        "li" => &["type", "value"],
256        "dl" => &["compact"],
257        "body" => &[
258            "bgcolor",
259            "text",
260            "link",
261            "vlink",
262            "alink",
263            "hlink",
264            "background",
265        ],
266        "sound" => &[
267            "src",
268            "layer",
269            "repeat",
270            "random",
271            "cancel",
272            "interrupt",
273            "sequence",
274            "alt",
275            "volume",
276            "fadein",
277            "fadeout",
278            "gapafter",
279        ],
280        "tab" => &["id", "to", "align", "indent", "multiple", "dp"],
281        "banner" => &[
282            "id",
283            "align",
284            "width",
285            "height",
286            "border",
287            "remove",
288            "removeall",
289        ],
290        _ => &[],
291    }
292}
293
294/// Attributes that name one of the game's resources.
295const RESOURCE_ATTRS: &[&str] = &["src", "asrc", "hsrc", "background"];
296
297/// The CSS properties the profile lets `style` set.
298const CSS_PROPERTIES: &[&str] = &[
299    "color",
300    "background",
301    "background-color",
302    "background-image",
303    "background-repeat",
304    "background-position",
305    "background-size",
306    "font",
307    "font-family",
308    "font-size",
309    "font-weight",
310    "font-style",
311    "font-variant",
312    "text-align",
313    "text-decoration",
314    "text-transform",
315    "text-indent",
316    "line-height",
317    "letter-spacing",
318    "word-spacing",
319    "white-space",
320    "margin",
321    "margin-top",
322    "margin-right",
323    "margin-bottom",
324    "margin-left",
325    "padding",
326    "padding-top",
327    "padding-right",
328    "padding-bottom",
329    "padding-left",
330    "border",
331    "border-top",
332    "border-right",
333    "border-bottom",
334    "border-left",
335    "border-width",
336    "border-style",
337    "border-color",
338    "border-radius",
339    "width",
340    "height",
341    "min-width",
342    "max-width",
343    "min-height",
344    "max-height",
345    "display",
346    "float",
347    "clear",
348    "list-style",
349    "list-style-type",
350    "list-style-position",
351    "vertical-align",
352    "flex-direction",
353    "flex-wrap",
354    "justify-content",
355    "align-items",
356    "gap",
357    // A table's: how its cells' borders meet, and the space between them.
358    "border-collapse",
359    "border-spacing",
360    // A picture's: smoothed when it is drawn bigger, or kept to crisp
361    // pixels (pixelated), as a map of small tiles wants.
362    "image-rendering",
363];
364
365/// The values `display` may have.
366const DISPLAY_VALUES: &[&str] = &["block", "inline", "inline-block", "none", "flex"];
367
368/// Elements that end a line, in the text form of a document.
369fn is_block(name: &str) -> bool {
370    matches!(
371        name,
372        "p" | "div"
373            | "blockquote"
374            | "center"
375            | "h1"
376            | "h2"
377            | "h3"
378            | "h4"
379            | "h5"
380            | "h6"
381            | "ul"
382            | "ol"
383            | "dl"
384            | "li"
385            | "dt"
386            | "dd"
387            | "dir"
388            | "menu"
389            | "table"
390            | "tr"
391            | "pre"
392            | "figure"
393            | "figcaption"
394            | "address"
395            | "aboutbox"
396            | "banner"
397            | "caption"
398    )
399}
400
401/// Elements that end an open paragraph when they start.
402fn closes_paragraph(name: &str) -> bool {
403    matches!(
404        name,
405        "p" | "div"
406            | "blockquote"
407            | "center"
408            | "h1"
409            | "h2"
410            | "h3"
411            | "h4"
412            | "h5"
413            | "h6"
414            | "ul"
415            | "ol"
416            | "dl"
417            | "dir"
418            | "menu"
419            | "table"
420            | "pre"
421            | "figure"
422            | "address"
423            | "hr"
424    )
425}
426
427/// Whether a name is one of the game's resources: a relative path with
428/// no address scheme, no root, and no way out of the game's own files.
429fn is_resource_name(name: &str) -> bool {
430    !name.is_empty()
431        && !name.contains(':')
432        && !name.contains('\\')
433        && !name.starts_with('/')
434        && !name.split('/').any(|part| part == "..")
435}
436
437/// Whether a link's target is a command, which is what a link in a game
438/// is: words for the game to take as typed. An address on the web or
439/// anywhere else is not.
440fn is_command_link(href: &str) -> bool {
441    let scheme_end = href.find(':');
442    match scheme_end {
443        None => true,
444        // A colon after a space is part of the words ("say: hello").
445        Some(i) => href[..i].contains(' ') || href[..i].is_empty(),
446    }
447}
448
449/// The declarations of a `style` attribute that the profile allows, or
450/// `None` if none are left.
451fn check_style(style: &str) -> Option<String> {
452    let kept = check_declarations(style, CSS_PROPERTIES);
453    if kept.is_empty() {
454        None
455    } else {
456        Some(kept.join("; "))
457    }
458}
459
460/// The declarations, of those listed, that the profile allows, each as
461/// `property: value`. A game's `!important` is taken out: the player's
462/// own choices are the only ones that may come first.
463fn check_declarations(declarations: &str, allowed: &[&str]) -> Vec<String> {
464    let mut kept = Vec::new();
465    for decl in declarations.split(';') {
466        let Some((prop, value)) = decl.split_once(':') else {
467            continue;
468        };
469        let prop = prop.trim().to_ascii_lowercase();
470        let mut value = value.trim();
471        if let Some(i) = value.to_ascii_lowercase().find("!important") {
472            value = value[..i].trim_end();
473        }
474        if value.is_empty() || !allowed.contains(&prop.as_str()) {
475            continue;
476        }
477        if !css_value_allowed(&prop, value) {
478            continue;
479        }
480        kept.push(format!("{prop}: {value}"));
481    }
482    kept
483}
484
485/// What a `@font-face` rule may say.
486const FONT_FACE_PROPERTIES: &[&str] = &[
487    "font-family",
488    "src",
489    "font-weight",
490    "font-style",
491    "font-display",
492    "unicode-range",
493];
494
495/// The words a `@media` query may use.
496const MEDIA_WORDS: &[&str] = &[
497    "all",
498    "screen",
499    "print",
500    "and",
501    "not",
502    "only",
503    "min-width",
504    "max-width",
505    "width",
506    "orientation",
507    "portrait",
508    "landscape",
509    "prefers-color-scheme",
510    "light",
511    "dark",
512    "prefers-reduced-motion",
513    "reduce",
514    "no-preference",
515    "prefers-contrast",
516    "more",
517    "less",
518];
519
520/// A game's style sheet, held to the profile, as text: each rule with
521/// only the properties the profile lists, `@media` with only its
522/// queries, `@font-face` with fonts among the game's resources, and every
523/// other at-rule gone. Each selector is put under `scope`, the page's
524/// element for the game, so a game styles its own text and not the
525/// page's: `body`, `html`, and `:root` are `scope` itself.
526pub fn check_stylesheet(css: &str, scope: &str) -> String {
527    let css = strip_comments(css);
528    let mut out = String::new();
529    check_rules(&css, scope, &mut out, 0);
530    out
531}
532
533fn strip_comments(css: &str) -> String {
534    let mut out = String::with_capacity(css.len());
535    let mut rest = css;
536    while let Some(i) = rest.find("/*") {
537        out.push_str(&rest[..i]);
538        match rest[i + 2..].find("*/") {
539            Some(j) => rest = &rest[i + 2 + j + 2..],
540            None => return out,
541        }
542    }
543    out.push_str(rest);
544    out
545}
546
547fn check_rules(css: &str, scope: &str, out: &mut String, depth: usize) {
548    let mut rest = css;
549    loop {
550        rest = rest.trim_start();
551        if rest.is_empty() {
552            return;
553        }
554        let brace = rest.find('{');
555        // An at-rule that ends with ";" and has no block: @import,
556        // @charset, @namespace. All go.
557        if rest.starts_with('@')
558            && let Some(semi) = rest.find(';')
559            && brace.is_none_or(|b| semi < b)
560        {
561            rest = &rest[semi + 1..];
562            continue;
563        }
564        let Some(open) = brace else {
565            return;
566        };
567        let prelude = rest[..open].trim();
568        let Some(len) = block_length(&rest[open..]) else {
569            return;
570        };
571        let body = &rest[open + 1..open + len - 1];
572        rest = &rest[open + len..];
573
574        if let Some(at) = prelude.strip_prefix('@') {
575            let (keyword, query) = at.split_once(char::is_whitespace).unwrap_or((at, ""));
576            match keyword.to_ascii_lowercase().as_str() {
577                "media" if depth < 4 && media_query_allowed(query) => {
578                    let mut inner = String::new();
579                    check_rules(body, scope, &mut inner, depth + 1);
580                    if !inner.is_empty() {
581                        out.push_str(&format!("@media {} {{\n{inner}}}\n", query.trim()));
582                    }
583                }
584                "font-face" => {
585                    let kept = check_declarations(body, FONT_FACE_PROPERTIES);
586                    if kept.iter().any(|d| d.starts_with("src:")) {
587                        out.push_str(&format!("@font-face {{ {} }}\n", kept.join("; ")));
588                    }
589                }
590                _ => {}
591            }
592            continue;
593        }
594
595        let selectors = scope_selectors(prelude, scope);
596        let kept = check_declarations(body, CSS_PROPERTIES);
597        if !selectors.is_empty() && !kept.is_empty() {
598            out.push_str(&format!("{selectors} {{ {} }}\n", kept.join("; ")));
599        }
600    }
601}
602
603/// The length of the block that starts at a "{", to its matching "}"
604/// included.
605fn block_length(css: &str) -> Option<usize> {
606    let mut depth = 0;
607    for (i, c) in css.char_indices() {
608        match c {
609            '{' => depth += 1,
610            '}' => {
611                depth -= 1;
612                if depth == 0 {
613                    return Some(i + 1);
614                }
615            }
616            _ => {}
617        }
618    }
619    None
620}
621
622fn media_query_allowed(query: &str) -> bool {
623    query
624        .split(|c: char| c.is_whitespace() || "(),:".contains(c))
625        .filter(|word| !word.is_empty())
626        .all(|word| {
627            let word = word.to_ascii_lowercase();
628            MEDIA_WORDS.contains(&word.as_str())
629                || word.chars().all(|c| c.is_ascii_digit() || c == '.')
630                || ["px", "em", "rem", "ch"].iter().any(|unit| {
631                    word.strip_suffix(unit).is_some_and(|n| {
632                        !n.is_empty() && n.chars().all(|c| c.is_ascii_digit() || c == '.')
633                    })
634                })
635        })
636}
637
638/// Selectors put under the scope. One with anything that could reach
639/// outside a selector is dropped.
640fn scope_selectors(prelude: &str, scope: &str) -> String {
641    let mut kept = Vec::new();
642    for selector in prelude.split(',') {
643        let selector = selector.trim();
644        if selector.is_empty() || selector.contains(['<', '\\', ';', '@']) {
645            continue;
646        }
647        let (first, rest) = match selector.find(|c: char| c.is_whitespace() || ">+~".contains(c)) {
648            Some(i) => (&selector[..i], &selector[i..]),
649            None => (selector, ""),
650        };
651        let first_lower = first.to_ascii_lowercase();
652        let scoped = if ["body", "html", ":root"].contains(&first_lower.as_str()) {
653            format!("{scope}{rest}")
654        } else if let Some(more) = first_lower
655            .strip_prefix("body")
656            .filter(|m| m.starts_with(['.', ':', '[']))
657        {
658            // body.dark, body:hover: the scope with the rest of it.
659            format!("{scope}{}{rest}", &first[first.len() - more.len()..])
660        } else {
661            format!("{scope} {selector}")
662        };
663        kept.push(scoped);
664    }
665    kept.join(", ")
666}
667
668fn css_value_allowed(prop: &str, value: &str) -> bool {
669    let lower = value.to_ascii_lowercase();
670    if lower.contains("expression")
671        || lower.contains("javascript:")
672        || lower.contains('\\')
673        || lower.contains('<')
674        || lower.contains("/*")
675        || lower.contains('@')
676    {
677        return false;
678    }
679    if prop == "display" {
680        let v = lower.trim_end_matches("!important").trim();
681        return DISPLAY_VALUES.contains(&v);
682    }
683    // A url() names one of the game's resources, or the value goes.
684    let mut rest = lower.as_str();
685    let mut orig = value;
686    while let Some(i) = rest.find("url(") {
687        let after = &orig[i + 4..];
688        let Some(close) = after.find(')') else {
689            return false;
690        };
691        let target = after[..close].trim().trim_matches(['"', '\'']);
692        if !is_resource_name(target) {
693            return false;
694        }
695        rest = &rest[i + 4 + close + 1..];
696        orig = &orig[i + 4 + close + 1..];
697    }
698    true
699}
700
701// ---- the checker ----
702
703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
704enum State {
705    Text,
706    /// In a tag: what has been read of it is in `tag`.
707    Tag,
708    /// In an entity: what has been read of it is in `entity`.
709    Entity,
710    /// In a comment, `<!-- ... -->`.
711    Comment,
712}
713
714/// Reads what a program writes, and gives out the checked document.
715#[derive(Debug)]
716pub struct Checker {
717    state: State,
718    tag: String,
719    quote: Option<char>,
720    entity: String,
721    /// Elements open now, innermost last.
722    open: Vec<String>,
723    /// Within an element dropped with its contents: its name, and how
724    /// deep in it.
725    dropping: Option<(String, usize)>,
726    /// Within `<title>`: the title so far.
727    title: Option<String>,
728    /// Within `<log>`, whose text is for a transcript only.
729    log_depth: usize,
730    /// `\^` or `\v` is waiting for the next letter.
731    case_next: Option<bool>,
732    /// The last thing given out ended a line.
733    at_line_start: bool,
734    items: Vec<Item>,
735    /// TADS's tags that stand for an element of the page's, open now:
736    /// the names they were written with, so their end tags close them.
737    aliases: Vec<(String, String)>,
738    warned: HashSet<String>,
739}
740
741impl Default for Checker {
742    fn default() -> Self {
743        Self::new()
744    }
745}
746
747impl Checker {
748    /// A checker at the start of a document.
749    pub fn new() -> Self {
750        Checker {
751            state: State::Text,
752            tag: String::new(),
753            quote: None,
754            entity: String::new(),
755            open: Vec::new(),
756            dropping: None,
757            title: None,
758            log_depth: 0,
759            case_next: None,
760            at_line_start: true,
761            items: Vec::new(),
762            aliases: Vec::new(),
763            warned: HashSet::new(),
764        }
765    }
766
767    /// Read what the program wrote.
768    pub fn write(&mut self, markup: &str) {
769        for c in markup.chars() {
770            self.read_char(c);
771        }
772    }
773
774    /// A line the player typed, which is shown as it is and ends the line.
775    pub fn input(&mut self, text: &str) {
776        self.push(Item::Input(text.to_owned()));
777        self.at_line_start = true;
778    }
779
780    /// The items given out since the last time.
781    pub fn take(&mut self) -> Vec<Item> {
782        std::mem::take(&mut self.items)
783    }
784
785    /// The names of elements that were dropped, once each: for a host
786    /// that tells the author what the profile left out.
787    pub fn dropped(&self) -> impl Iterator<Item = &str> {
788        self.warned.iter().map(String::as_str)
789    }
790
791    fn read_char(&mut self, c: char) {
792        match self.state {
793            State::Tag => self.read_tag_char(c),
794            State::Entity => self.read_entity_char(c),
795            State::Comment => {
796                self.tag.push(c);
797                if self.tag.ends_with("-->") {
798                    self.tag.clear();
799                    self.state = State::Text;
800                }
801            }
802            State::Text => match c {
803                '<' => {
804                    self.state = State::Tag;
805                    self.tag.clear();
806                    self.quote = None;
807                }
808                '&' => {
809                    self.state = State::Entity;
810                    self.entity.clear();
811                }
812                '\n' => self.line_break(),
813                '\u{b}' => self.blank_line(),
814                '\u{f}' => self.case_next = Some(true),
815                '\u{e}' => self.case_next = Some(false),
816                '\t' => self.text_char('\u{2003}'),
817                '\u{15}' => self.text_char('\u{a0}'),
818                c if (c as u32) < 0x20 => {}
819                c => self.text_char(c),
820            },
821        }
822    }
823
824    fn read_tag_char(&mut self, c: char) {
825        if self.tag.is_empty() && c != '/' && c != '!' && !c.is_ascii_alphabetic() {
826            // Not a tag after all: a "<" in the text.
827            self.state = State::Text;
828            self.text_char('<');
829            self.read_char(c);
830            return;
831        }
832        if self.tag == "!--" {
833            self.state = State::Comment;
834            self.tag.clear();
835            self.tag.push_str("--");
836            self.read_char(c);
837            return;
838        }
839        match self.quote {
840            Some(q) if c == q => self.quote = None,
841            Some(_) => {}
842            None if c == '"' || c == '\'' => {
843                // A quote starts a value only after "=".
844                if self.tag.trim_end().ends_with('=') {
845                    self.quote = Some(c);
846                }
847            }
848            None if c == '>' => {
849                let tag = std::mem::take(&mut self.tag);
850                self.state = State::Text;
851                self.tag_done(&tag);
852                return;
853            }
854            None => {}
855        }
856        self.tag.push(c);
857    }
858
859    fn read_entity_char(&mut self, c: char) {
860        if c == ';' {
861            let name = std::mem::take(&mut self.entity);
862            self.state = State::Text;
863            match decode_entity(&name) {
864                Some(ch) => self.text_char(ch),
865                None => {
866                    self.text_str(&format!("&{name};"));
867                }
868            }
869            return;
870        }
871        let ok = c.is_ascii_alphanumeric() || (c == '#' && self.entity.is_empty());
872        if ok && self.entity.len() < 12 {
873            self.entity.push(c);
874            return;
875        }
876        // Not an entity: the "&" and what followed it are text.
877        let name = std::mem::take(&mut self.entity);
878        self.state = State::Text;
879        self.text_str(&format!("&{name}"));
880        self.read_char(c);
881    }
882
883    // ---- text ----
884
885    /// A character of text, in the case `\^` or `\v` asked for if one is
886    /// waiting: which can be more than one character ("ß" in upper case is
887    /// "SS").
888    fn text_char(&mut self, c: char) {
889        match self.case_next {
890            Some(upper) if c.is_alphabetic() => {
891                self.case_next = None;
892                let changed: String = if upper {
893                    c.to_uppercase().collect()
894                } else {
895                    c.to_lowercase().collect()
896                };
897                for c in changed.chars() {
898                    self.text_char_raw(c);
899                }
900            }
901            _ => self.text_char_raw(c),
902        }
903    }
904
905    fn text_char_raw(&mut self, c: char) {
906        if let Some(title) = &mut self.title {
907            title.push(c);
908            return;
909        }
910        if self.dropping.is_some() || self.log_depth > 0 {
911            return;
912        }
913        // Spaces at the start of a line show nothing.
914        if self.at_line_start && c == ' ' {
915            return;
916        }
917        self.at_line_start = false;
918        if let Some(Item::Text(text)) = self.items.last_mut() {
919            text.push(c);
920        } else {
921            self.items.push(Item::Text(c.to_string()));
922        }
923    }
924
925    fn text_str(&mut self, s: &str) {
926        for c in s.chars() {
927            self.text_char(c);
928        }
929    }
930
931    fn line_break(&mut self) {
932        if self.dropping.is_some() || self.log_depth > 0 || self.title.is_some() {
933            return;
934        }
935        // A newline at the start of a line adds nothing, as on a display
936        // of text: a blank line has to be asked for ("\b", <p>, <br>).
937        // In preformatted text every line counts.
938        if self.at_line_start && !self.open.iter().any(|name| name == "pre") {
939            return;
940        }
941        self.push(Item::Void("br".into(), Vec::new()));
942        self.at_line_start = true;
943    }
944
945    fn blank_line(&mut self) {
946        if self.dropping.is_some() || self.log_depth > 0 || self.title.is_some() {
947            return;
948        }
949        if !self.at_line_start {
950            self.push(Item::Void("br".into(), Vec::new()));
951        }
952        self.push(Item::Void("br".into(), Vec::new()));
953        self.at_line_start = true;
954    }
955
956    fn push(&mut self, item: Item) {
957        self.items.push(item);
958    }
959
960    // ---- tags ----
961
962    fn tag_done(&mut self, tag: &str) {
963        let (end, name, attrs) = parse_tag(tag);
964        if name.is_empty() || name.starts_with('!') || name.starts_with('?') {
965            return;
966        }
967
968        // Inside an element dropped with its contents, only its end
969        // matters.
970        if let Some((dropped, depth)) = &mut self.dropping {
971            if *dropped == name {
972                if end {
973                    if *depth == 0 {
974                        self.dropping = None;
975                    } else {
976                        *depth -= 1;
977                    }
978                } else {
979                    *depth += 1;
980                }
981            }
982            return;
983        }
984
985        match name.as_str() {
986            "title" => {
987                if end {
988                    if let Some(title) = self.title.take() {
989                        self.push(Item::Title(title.trim().to_owned()));
990                        self.at_line_start = true;
991                    }
992                } else {
993                    self.title = Some(String::new());
994                }
995                return;
996            }
997            "log" => {
998                if end {
999                    self.log_depth = self.log_depth.saturating_sub(1);
1000                } else {
1001                    self.log_depth += 1;
1002                }
1003                return;
1004            }
1005            // What is only kept out of a transcript is shown.
1006            "nolog" | "wrap" | "hiliteon" | "hiliteoff" | "noenter" => return,
1007            _ => {}
1008        }
1009        if self.title.is_some() || self.log_depth > 0 {
1010            return;
1011        }
1012
1013        if DROPPED_WITH_CONTENTS.contains(&name.as_str()) {
1014            if !end {
1015                self.warned.insert(name.clone());
1016                self.dropping = Some((name, 0));
1017            }
1018            return;
1019        }
1020
1021        // TADS's tags that are the page's under another name.
1022        let (page_name, extra_style): (&str, Option<&str>) = match name.as_str() {
1023            "bq" => ("blockquote", None),
1024            "credit" => ("cite", None),
1025            "listing" | "xmp" => ("pre", None),
1026            "nobr" => ("span", Some("white-space: nowrap")),
1027            other => (other, None),
1028        };
1029        let page_name = page_name.to_owned();
1030
1031        if end {
1032            self.end_tag(&name, &page_name);
1033            return;
1034        }
1035
1036        let is_void = VOID.contains(&page_name.as_str());
1037        if !is_void && !CONTAINERS.contains(&page_name.as_str()) {
1038            // Not in the profile: the element goes, what is in it stays.
1039            self.warned.insert(page_name);
1040            return;
1041        }
1042
1043        let mut attrs = self.check_attrs(&page_name, attrs);
1044        if let Some(style) = extra_style {
1045            attrs.push(("style".into(), Some(style.to_owned())));
1046        }
1047        // A banner that is removed has nothing in it, and no end tag.
1048        let is_void = is_void
1049            || (page_name == "banner"
1050                && attrs.iter().any(|(n, _)| n == "remove" || n == "removeall"));
1051
1052        // A picture that is not one of the game's resources goes; its
1053        // words, if it has any, stay.
1054        if page_name == "img" && !attrs.iter().any(|(n, _)| n == "src") {
1055            if let Some((_, Some(alt))) = attrs.iter().find(|(n, _)| n == "alt") {
1056                let alt = alt.clone();
1057                self.text_str(&alt);
1058            }
1059            return;
1060        }
1061        if page_name == "sound" && !attrs.iter().any(|(n, _)| n == "src" || n == "cancel") {
1062            return;
1063        }
1064
1065        if is_void {
1066            if closes_paragraph(&page_name) {
1067                self.close_paragraph();
1068            }
1069            let breaks = page_name == "br" || page_name == "hr";
1070            self.push(Item::Void(page_name, attrs));
1071            if breaks {
1072                self.at_line_start = true;
1073            }
1074            return;
1075        }
1076
1077        if closes_paragraph(&page_name) {
1078            self.close_paragraph();
1079        }
1080        self.close_siblings(&page_name);
1081        if page_name != name {
1082            self.aliases.push((name, page_name.clone()));
1083        }
1084        self.open.push(page_name.clone());
1085        let starts_line = is_block(&page_name);
1086        self.push(Item::Open(page_name, attrs));
1087        if starts_line {
1088            self.at_line_start = true;
1089        }
1090    }
1091
1092    /// An end tag: close the element it ends, and any still open inside
1093    /// it. One that ends nothing open is dropped.
1094    fn end_tag(&mut self, written: &str, page_name: &str) {
1095        let target = self
1096            .aliases
1097            .iter()
1098            .rev()
1099            .find(|(w, _)| w == written)
1100            .map(|(_, p)| p.clone())
1101            .unwrap_or_else(|| page_name.to_owned());
1102        let Some(at) = self.open.iter().rposition(|n| *n == target) else {
1103            return;
1104        };
1105        while self.open.len() > at {
1106            self.close_top();
1107        }
1108        if let Some(i) = self.aliases.iter().rposition(|(w, _)| w == written) {
1109            self.aliases.remove(i);
1110        }
1111    }
1112
1113    fn close_top(&mut self) {
1114        if let Some(name) = self.open.pop() {
1115            let ends_line = is_block(&name);
1116            self.push(Item::Close(name));
1117            if ends_line {
1118                self.at_line_start = true;
1119            }
1120        }
1121    }
1122
1123    /// A block starting ends a paragraph still open, as in HTML.
1124    fn close_paragraph(&mut self) {
1125        if let Some(at) = self.open.iter().rposition(|n| n == "p") {
1126            // Not across a table cell or a list item.
1127            if self.open[at..]
1128                .iter()
1129                .all(|n| !matches!(n.as_str(), "td" | "th" | "li" | "blockquote" | "div"))
1130            {
1131                while self.open.len() > at {
1132                    self.close_top();
1133                }
1134            }
1135        }
1136    }
1137
1138    /// Elements that end the one before them of their kind: a list item,
1139    /// a table row or cell, a term or its definition.
1140    fn close_siblings(&mut self, name: &str) {
1141        let (ends, within): (&[&str], &[&str]) = match name {
1142            "li" => (&["li"], &["ul", "ol", "dir", "menu"]),
1143            "dt" | "dd" => (&["dt", "dd"], &["dl"]),
1144            "tr" => (&["tr", "td", "th"], &["table"]),
1145            "td" | "th" => (&["td", "th"], &["tr", "table"]),
1146            _ => return,
1147        };
1148        let Some(at) = self
1149            .open
1150            .iter()
1151            .rposition(|n| ends.contains(&n.as_str()) || within.contains(&n.as_str()))
1152        else {
1153            return;
1154        };
1155        if ends.contains(&self.open[at].as_str()) {
1156            while self.open.len() > at {
1157                self.close_top();
1158            }
1159        }
1160    }
1161
1162    /// The attributes the profile lets an element keep, with what they
1163    /// name checked.
1164    fn check_attrs(&mut self, element: &str, attrs: Vec<Attr>) -> Vec<Attr> {
1165        let own = element_attrs(element);
1166        let mut kept = Vec::new();
1167        for (name, value) in attrs {
1168            if !GLOBAL_ATTRS.contains(&name.as_str()) && !own.contains(&name.as_str()) {
1169                if name.starts_with("on") {
1170                    self.warned.insert(format!("{element} {name}"));
1171                }
1172                continue;
1173            }
1174            let value = match (name.as_str(), value) {
1175                ("style", Some(v)) => match check_style(&v) {
1176                    Some(v) => Some(v),
1177                    None => continue,
1178                },
1179                ("href", Some(v)) => {
1180                    if !is_command_link(&v) {
1181                        self.warned.insert(format!("{element} href"));
1182                        continue;
1183                    }
1184                    Some(v)
1185                }
1186                (n, Some(v)) if RESOURCE_ATTRS.contains(&n) => {
1187                    if !is_resource_name(&v) {
1188                        self.warned.insert(format!("{element} {n}"));
1189                        continue;
1190                    }
1191                    Some(v)
1192                }
1193                (_, v) => v,
1194            };
1195            kept.push((name, value));
1196        }
1197        kept
1198    }
1199}
1200
1201/// A tag's parts: whether it is an end tag, its name in lower case, and
1202/// its attributes.
1203fn parse_tag(tag: &str) -> (bool, String, Vec<Attr>) {
1204    let mut rest = tag.trim();
1205    let end = rest.starts_with('/');
1206    if end {
1207        rest = &rest[1..];
1208    }
1209    let rest = rest.trim_end_matches('/');
1210    let name_len = rest
1211        .find(|c: char| c.is_whitespace() || c == '/')
1212        .unwrap_or(rest.len());
1213    let name = rest[..name_len].to_ascii_lowercase();
1214    let mut attrs = Vec::new();
1215    let chars: Vec<char> = rest[name_len..].chars().collect();
1216    let mut i = 0;
1217    while i < chars.len() {
1218        while i < chars.len() && (chars[i].is_whitespace() || chars[i] == '/') {
1219            i += 1;
1220        }
1221        let start = i;
1222        while i < chars.len() && !chars[i].is_whitespace() && chars[i] != '=' {
1223            i += 1;
1224        }
1225        if start == i {
1226            i += 1;
1227            continue;
1228        }
1229        let attr: String = chars[start..i]
1230            .iter()
1231            .collect::<String>()
1232            .to_ascii_lowercase();
1233        while i < chars.len() && chars[i].is_whitespace() {
1234            i += 1;
1235        }
1236        if i < chars.len() && chars[i] == '=' {
1237            i += 1;
1238            while i < chars.len() && chars[i].is_whitespace() {
1239                i += 1;
1240            }
1241            let value: String = if i < chars.len() && (chars[i] == '"' || chars[i] == '\'') {
1242                let q = chars[i];
1243                i += 1;
1244                let vs = i;
1245                while i < chars.len() && chars[i] != q {
1246                    i += 1;
1247                }
1248                let v = chars[vs..i].iter().collect();
1249                i += 1;
1250                v
1251            } else {
1252                let vs = i;
1253                while i < chars.len() && !chars[i].is_whitespace() {
1254                    i += 1;
1255                }
1256                chars[vs..i].iter().collect()
1257            };
1258            attrs.push((attr, Some(decode_entities(&value))));
1259        } else {
1260            attrs.push((attr, None));
1261        }
1262    }
1263    (end, name, attrs)
1264}
1265
1266/// The character an entity stands for: a name (`&mdash;`), or a number
1267/// (`&#8212;`, `&#x2014;`).
1268fn decode_entity(name: &str) -> Option<char> {
1269    if let Some(num) = name.strip_prefix('#') {
1270        let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
1271            u32::from_str_radix(hex, 16).ok()?
1272        } else {
1273            num.parse().ok()?
1274        };
1275        return char::from_u32(code);
1276    }
1277    entities::lookup(name)
1278}
1279
1280/// A value with its entities replaced.
1281fn decode_entities(value: &str) -> String {
1282    let mut out = String::with_capacity(value.len());
1283    let mut rest = value;
1284    while let Some(i) = rest.find('&') {
1285        out.push_str(&rest[..i]);
1286        let after = &rest[i + 1..];
1287        match after.find(';') {
1288            Some(j) if j <= 12 => match decode_entity(&after[..j]) {
1289                Some(c) => {
1290                    out.push(c);
1291                    rest = &after[j + 1..];
1292                }
1293                None => {
1294                    out.push('&');
1295                    rest = after;
1296                }
1297            },
1298            _ => {
1299                out.push('&');
1300                rest = after;
1301            }
1302        }
1303    }
1304    out.push_str(rest);
1305    out
1306}
1307
1308/// What happens on a rich display, in order: the main window's items, and
1309/// the panes'.
1310#[derive(Debug, Clone, PartialEq, Eq)]
1311pub enum Event {
1312    /// Something for the main window.
1313    Main(Item),
1314    /// A pane was made.
1315    PaneCreated(u32),
1316    /// A pane was removed.
1317    PaneDeleted(u32),
1318    /// A pane's text was removed.
1319    PaneCleared(u32),
1320    /// Something for a text pane: what was written to it since it was
1321    /// last shown.
1322    Pane(u32, Vec<Item>),
1323}
1324
1325impl Event {
1326    /// The event as text: a main window's item as [`Item::markup`]
1327    /// writes it, and a pane's as `<pane id="1">...</pane>`, on a line of
1328    /// its own.
1329    pub fn markup(&self) -> String {
1330        match self {
1331            Event::Main(item) => item.markup(),
1332            Event::PaneCreated(id) => format!("<pane id=\"{id}\" create></pane>\n"),
1333            Event::PaneDeleted(id) => format!("<pane id=\"{id}\" delete></pane>\n"),
1334            Event::PaneCleared(id) => format!("<pane id=\"{id}\" clear></pane>\n"),
1335            Event::Pane(id, items) => {
1336                let text: String = items.iter().map(Item::markup).collect();
1337                format!("<pane id=\"{id}\">{text}</pane>\n")
1338            }
1339        }
1340    }
1341}
1342
1343/// A rich display's document: the main window's and each pane's, checked,
1344/// as a list of [`Event`]s in the order they were shown. What is written
1345/// to a pane is gathered until the pane is shown (`pane_flush`), or until
1346/// something else is written, so that it comes as one event.
1347#[derive(Debug, Default)]
1348pub struct Document {
1349    main: Checker,
1350    panes: std::collections::HashMap<u32, Checker>,
1351    /// The panes written to since they were last shown, in the order
1352    /// they were first written to.
1353    written: Vec<u32>,
1354    events: Vec<Event>,
1355}
1356
1357impl Document {
1358    /// A document with nothing in it.
1359    pub fn new() -> Self {
1360        Self::default()
1361    }
1362
1363    /// What the program wrote to the main window.
1364    pub fn write(&mut self, markup: &str) {
1365        self.show_panes();
1366        self.main.write(markup);
1367        self.take_main();
1368    }
1369
1370    /// A line the player typed.
1371    pub fn input(&mut self, text: &str) {
1372        self.show_panes();
1373        self.main.input(text);
1374        self.take_main();
1375    }
1376
1377    /// What the program wrote to a text pane.
1378    pub fn pane_write(&mut self, id: u32, markup: &str) {
1379        self.panes.entry(id).or_default().write(markup);
1380        if !self.written.contains(&id) {
1381            self.written.push(id);
1382        }
1383    }
1384
1385    /// The panes are to show what they have been given.
1386    pub fn pane_flush(&mut self) {
1387        self.show_panes();
1388    }
1389
1390    /// A pane was made.
1391    pub fn pane_created(&mut self, id: u32) {
1392        self.show_panes();
1393        self.events.push(Event::PaneCreated(id));
1394    }
1395
1396    /// A pane was removed.
1397    pub fn pane_deleted(&mut self, id: u32) {
1398        self.show_panes();
1399        self.panes.remove(&id);
1400        self.events.push(Event::PaneDeleted(id));
1401    }
1402
1403    /// A pane's text was removed: what it is given next starts afresh.
1404    pub fn pane_cleared(&mut self, id: u32) {
1405        self.show_panes();
1406        self.panes.insert(id, Checker::new());
1407        self.events.push(Event::PaneCleared(id));
1408    }
1409
1410    /// The events since the last time.
1411    pub fn take(&mut self) -> Vec<Event> {
1412        std::mem::take(&mut self.events)
1413    }
1414
1415    /// The events since the last time, as text.
1416    pub fn take_text(&mut self) -> String {
1417        self.take().iter().map(Event::markup).collect()
1418    }
1419
1420    fn take_main(&mut self) {
1421        let items = self.main.take();
1422        self.events.extend(items.into_iter().map(Event::Main));
1423    }
1424
1425    fn show_panes(&mut self) {
1426        for id in std::mem::take(&mut self.written) {
1427            if let Some(checker) = self.panes.get_mut(&id) {
1428                let items = checker.take();
1429                if !items.is_empty() {
1430                    self.events.push(Event::Pane(id, items));
1431                }
1432            }
1433        }
1434    }
1435}
1436
1437/// Check a whole piece of markup at once, and give its document as text:
1438/// for tests, and for a host that checks a page at a time.
1439pub fn check(markup: &str) -> String {
1440    let mut checker = Checker::new();
1441    checker.write(markup);
1442    checker.take().iter().map(Item::markup).collect()
1443}
1444
1445#[cfg(test)]
1446mod tests {
1447    use super::*;
1448
1449    #[test]
1450    fn plain_text_and_entities() {
1451        assert_eq!(
1452            check("Fish &amp; chips&mdash;&#33; &bogus; a < b"),
1453            "Fish &amp; chips\u{2014}! &amp;bogus; a &lt; b"
1454        );
1455    }
1456
1457    #[test]
1458    fn control_characters() {
1459        assert_eq!(
1460            check("one\ntwo\u{b}\u{f}three \u{e}FOUR"),
1461            "one<br>\ntwo<br>\n<br>\nThree fOUR"
1462        );
1463    }
1464
1465    #[test]
1466    fn tads_tags_become_the_pages() {
1467        assert_eq!(
1468            check("<bq>Quoted.</bq><nobr>12:30</nobr>"),
1469            "<blockquote>Quoted.</blockquote>\n<span style=\"white-space: nowrap\">12:30</span>"
1470        );
1471    }
1472
1473    #[test]
1474    fn a_newline_at_the_start_of_a_line_adds_nothing() {
1475        // As on a display of text: a blank line is asked for, not made of
1476        // newlines; but preformatted text keeps every line.
1477        assert_eq!(check("one\n\n\ntwo"), "one<br>\ntwo");
1478        assert_eq!(check("<div>a</div>\nb"), "<div>a</div>\nb");
1479        assert_eq!(check("one\u{b}two"), "one<br>\n<br>\ntwo");
1480        assert_eq!(check("<pre>a\n\nb</pre>"), "<pre>a<br>\n<br>\nb</pre>\n");
1481    }
1482
1483    #[test]
1484    fn a_banner_removed_holds_nothing() {
1485        assert_eq!(
1486            check("<banner id=map align=left width=20%>Map</banner><banner remove id=map>After."),
1487            "<banner id=\"map\" align=\"left\" width=\"20%\">Map</banner>\n<banner remove id=\"map\">After."
1488        );
1489    }
1490
1491    #[test]
1492    fn the_pages_own_elements_are_kept() {
1493        assert_eq!(
1494            check(
1495                "<title>The Skull</title><sound src='drip.wav' layer=ambient random=3><body bgcolor=black>Dark."
1496            ),
1497            "<title>The Skull</title>\n<sound src=\"drip.wav\" layer=\"ambient\" random=\"3\"><body bgcolor=\"black\">\nDark."
1498        );
1499    }
1500
1501    #[test]
1502    fn scripts_and_handlers_are_dropped() {
1503        assert_eq!(
1504            check(
1505                "A<script>alert('x')</script>B<b onclick=\"steal()\">C</b><iframe src=x>D</iframe>E"
1506            ),
1507            "AB<b>C</b>E"
1508        );
1509    }
1510
1511    #[test]
1512    fn only_the_games_resources_and_commands() {
1513        assert_eq!(
1514            check(
1515                "<img src='http://evil/x.png' alt='a cave'><img src='../x.png'><img src='cave.jpg'>"
1516            ),
1517            "a cave<img src=\"cave.jpg\">"
1518        );
1519        assert_eq!(
1520            check("<a href='north'>north</a> <a href='https://example.com'>web</a>"),
1521            "<a href=\"north\">north</a> <a>web</a>"
1522        );
1523    }
1524
1525    #[test]
1526    fn style_keeps_only_the_profile() {
1527        assert_eq!(
1528            check(
1529                "<span style=\"color: red; position: fixed; background: url(http://x/y.png); background-image: url('stone.png'); display: grid\">x</span>"
1530            ),
1531            "<span style=\"color: red; background-image: url('stone.png')\">x</span>"
1532        );
1533        assert_eq!(
1534            check("<span style='behavior: url(x.htc)'>x</span>"),
1535            "<span>x</span>"
1536        );
1537    }
1538
1539    #[test]
1540    fn elements_outside_the_profile_go_but_their_text_stays() {
1541        assert_eq!(check("<marquee>Hello</marquee>"), "Hello");
1542    }
1543
1544    #[test]
1545    fn a_tag_split_between_writes() {
1546        let mut checker = Checker::new();
1547        checker.write("<img src='clock/");
1548        checker.write("9");
1549        checker.write(".jpg' border=0>after &md");
1550        checker.write("ash; done");
1551        let doc: String = checker.take().iter().map(Item::markup).collect();
1552        assert_eq!(
1553            doc,
1554            "<img src=\"clock/9.jpg\" border=\"0\">after \u{2014} done"
1555        );
1556    }
1557
1558    #[test]
1559    fn elements_are_closed_in_order() {
1560        assert_eq!(
1561            check("<b>bold <i>both</b> plain</i>"),
1562            "<b>bold <i>both</i></b> plain"
1563        );
1564        assert_eq!(
1565            check("<ol><li>One<li>Two</ol>"),
1566            "<ol><li>One</li>\n<li>Two</li>\n</ol>\n"
1567        );
1568        assert_eq!(check("<p>One<p>Two"), "<p>One</p>\n<p>Two");
1569    }
1570
1571    #[test]
1572    fn the_players_input() {
1573        let mut checker = Checker::new();
1574        checker.write(">");
1575        checker.input("look <b>");
1576        let doc: String = checker.take().iter().map(Item::markup).collect();
1577        assert_eq!(doc, "><kbd>look &lt;b></kbd>\n");
1578    }
1579
1580    #[test]
1581    fn a_style_attribute_loses_important() {
1582        assert_eq!(
1583            check("<span style='color: red !important; font-size: 2em'>x</span>"),
1584            "<span style=\"color: red; font-size: 2em\">x</span>"
1585        );
1586    }
1587
1588    #[test]
1589    fn a_stylesheet_is_scoped_and_held_to_the_profile() {
1590        let css = "@import url(http://x/y.css);\n\
1591                   /* the page */ body { background: #000; position: absolute; color: #eee }\n\
1592                   .roomname, h1 { font-variant: small-caps !important }\n\
1593                   @media (max-width: 40em) { p { margin: 0 } }\n\
1594                   @media (hover: hover) { p { color: red } }\n\
1595                   @font-face { font-family: Uncial; src: url('uncial.woff2') format('woff2') }\n\
1596                   @font-face { font-family: Far; src: url(https://x/y.woff2) }\n\
1597                   @keyframes spin { from { color: red } }\n\
1598                   a { color: blue; behavior: url(x.htc) }";
1599        assert_eq!(
1600            check_stylesheet(css, "#game"),
1601            "#game { background: #000; color: #eee }\n\
1602             #game .roomname, #game h1 { font-variant: small-caps }\n\
1603             @media (max-width: 40em) {\n#game p { margin: 0 }\n}\n\
1604             @font-face { font-family: Uncial; src: url('uncial.woff2') format('woff2') }\n\
1605             #game a { color: blue }\n"
1606        );
1607    }
1608
1609    #[test]
1610    fn a_transcript_only_text_and_comments() {
1611        assert_eq!(check("A<log>for the log</log>B<!-- a <b> note -->C"), "ABC");
1612    }
1613}