Skip to main content

flm_core/stdlib/backends/html/
sink.rs

1//! The HTML sink: the only interface through which this library writes HTML
2//! bytes.
3//!
4//! An [`HtmlSink`] holds the HTML being written. An emitter never holds the
5//! output string: it writes through the sink, which has one entry point per
6//! *kind of content*, and each entry point escapes what that kind of content
7//! needs escaped. This is the whole of the HTML backend's escaping:
8//!
9//! - [`text`](HtmlSink::text) — document text, escaped
10//!   ([`super::escape::escape_text_into`]);
11//! - a **tag**: [`open_block`](HtmlSink::open_block) or
12//!   [`open_inline`](HtmlSink::open_inline) hands back a [`TagBuilder`] whose
13//!   [`attr`](TagBuilder::attr) escapes every value and always writes it
14//!   inside double quotation marks, whose
15//!   [`attr_json`](TagBuilder::attr_json) does the same inside single
16//!   quotation marks for a JSON value, and
17//!   [`close`](HtmlSink::close) closes the element the sink last opened;
18//!   [`void_block`](HtmlSink::void_block) and
19//!   [`void_inline`](HtmlSink::void_inline) write an element that has no
20//!   content and is never closed, such as `<img>`;
21//! - [`markup`](HtmlSink::markup) — a [`Markup`] value, HTML written through
22//!   unchanged (that type's documentation states what its creator must
23//!   ensure), and
24//!   [`markup_block`](HtmlSink::markup_block), which writes such a value where
25//!   a block-level element could be placed, on a line of its own;
26//! - [`raw_text_element`](HtmlSink::raw_text_element) — a `<style>` or a
27//!   `<script>`, the two elements whose content a browser reads as raw text
28//!   and which therefore cannot be escaped at all; the entry point writes
29//!   those two tags and no other, and refuses content that holds the
30//!   element's own closing tag, since that and nothing else would end the
31//!   element early.
32//!
33//! These last two are the only entry points that write bytes unescaped: a
34//! [`Markup`] value, and the content of a `<style>` or a `<script>`.
35//!
36//! Text a document wrote reaches a page through `text`, `attr` and
37//! `attr_json`, and through no other entry point. Each of the three escapes
38//! what its place needs escaped, so text that reaches one of them cannot leave
39//! it. No entry point takes an already-escaped string, and
40//! nothing reads the buffer back: the sink offers no accessor to the bytes
41//! written before [`finish`](HtmlSink::finish) takes them — its `Debug` form
42//! shows how much has been written and which elements are open, never the
43//! bytes — so no decision can depend on output and no escaping can run over
44//! output. Escaping twice, or escaping inside an element whose content must not
45//! be escaped, therefore cannot be written at all.
46//!
47//! The sink checks nothing about document input: it escapes what it is
48//! given.
49//! What must be checked before it is written — a tag or attribute name from a
50//! construct node ([`is_valid_tag_name`]), an address
51//! ([`check_address`](super::address::check_address)) — is checked by the
52//! emitter, which can report the node it refused. Checking a name is the
53//! caller's responsibility: every entry point taking one states that as its
54//! precondition and checks it again in a debug build, where a name that fails
55//! is a programming error in the calling code and not document input
56//! ([panics](crate::guide::panics) lists these checks).
57//!
58//! # How the bytes are laid out
59//!
60//! The sink introduces a line break and two spaces of indentation per level
61//! between **block-level** elements, and introduces nothing anywhere else.
62//! Inline content is written exactly as it comes, because whitespace between
63//! inline elements is text a reader sees; and there is no pass over the
64//! finished output, which would mean reading it back.
65//!
66//! Whether an element is block-level is decided by the call that opened it —
67//! [`open_block`](HtmlSink::open_block) against
68//! [`open_inline`](HtmlSink::open_inline) — and never by its tag name. A
69//! construct node's tag is chosen by its rule's author, and its payload states
70//! which of the two it is (the `block` field of
71//! [`HtmlTagPayload`](super::HtmlTagPayload)).
72//!
73//! A **preformatted region** — the content of `<pre>`, where every space and
74//! line break is text the reader sees — is marked when the element is opened
75//! ([`TagBuilder::preformatted`]) and nothing is introduced inside it.
76//!
77//! Only the innermost open element decides whether a position is in inline
78//! flow, so a block-level element opened inside an inline one writes no line
79//! break before itself, and its own children are broken and indented again.
80//! The HTML emitter never produces that case, since a block-level element
81//! inside an inline one is invalid HTML. A preformatted region, by contrast,
82//! applies to everything inside it, however deeply nested: it is how a caller
83//! asks for no whitespace anywhere inside an element.
84//!
85//! # Examples
86//!
87//! ```
88//! use flm_core::stdlib::backends::html::HtmlSink;
89//!
90//! let mut sink = HtmlSink::new();
91//! sink.open_block("div").class(["flm-pres-block"]).finish();
92//! sink.open_block("p").class(["flm-pres-par"]).finish();
93//! sink.text("Hello ");
94//! sink.open_inline("em").finish();
95//! sink.text("there");
96//! sink.close();
97//! sink.close();
98//! sink.close();
99//! assert_eq!(
100//!     sink.finish(),
101//!     "<div class=\"flm-pres-block\">\n  <p class=\"flm-pres-par\">Hello <em>there</em></p>\n</div>",
102//! );
103//! ```
104
105use std::fmt;
106
107use super::escape::{escape_attr_into, escape_attr_single_quoted_into, escape_text_into};
108use super::markup::Markup;
109use super::names::{is_valid_attribute_name, is_valid_tag_name};
110
111/// What one level of block-level nesting is indented by.
112const INDENT: &str = "  ";
113
114/// The two elements whose content a browser reads as raw text: the only tags
115/// [`HtmlSink::raw_text_element`] accepts.
116const RAW_TEXT_TAGS: [&str; 2] = ["style", "script"];
117
118/// An element the sink has opened and not yet closed.
119#[derive(Debug, Clone)]
120struct OpenElement {
121    /// The tag name, for the closing tag.
122    tag: String,
123    /// Whether the element was opened as block-level.
124    block: bool,
125    /// Whether a block-level child was written inside it; if so, its closing
126    /// tag goes on a line of its own.
127    block_children: bool,
128    /// Whether the element's content is a preformatted region.
129    preformatted: bool,
130}
131
132/// The error [`HtmlSink::raw_text_element`] returns for content that holds the
133/// closing tag of the element it would be written into.
134///
135/// The content of a `<style>` or a `<script>` is **raw text**: a browser reads
136/// it character by character up to the element's closing tag and reads no
137/// character reference on the way, so nothing in it can be escaped, and the
138/// only sequence that must not appear in it is that closing tag (`</style` or
139/// `</script`, in any letter case, followed by anything). Content holding one
140/// would end the element early and leave the rest of it in the page as markup.
141///
142/// It reports a mistake in the definition or in the configuration that
143/// supplied the content, never anything a document can write. The HTML
144/// backend reports it as
145/// [`flm.html.definition-not-inlinable`](super::defs::DefinitionNotInlinable).
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct RawTextRefused {
148    /// The element's tag name, as the call gave it.
149    pub tag: String,
150    /// The byte offset, in the content, of the `</` that begins the closing
151    /// tag found there.
152    pub at: usize,
153}
154
155impl fmt::Display for RawTextRefused {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        write!(
158            f,
159            "the content of a `<{}>` element holds its own closing tag at byte {}, which would \
160             end the element there",
161            self.tag, self.at
162        )
163    }
164}
165
166/// The byte offset of the first `</<tag>` in `content`, comparing the tag name
167/// without regard to letter case; `None` when the content holds none.
168///
169/// What follows the name does not matter: a browser ends a raw text element at
170/// `</` plus the name plus any character that can follow a tag name, and
171/// refusing every `</name` keeps the rule one sentence long.
172fn closing_tag_at(content: &str, tag: &str) -> Option<usize> {
173    let needle_len = 2 + tag.len();
174    content.match_indices("</").find_map(|(at, _)| {
175        let name = content.get(at + 2..at + needle_len)?;
176        name.eq_ignore_ascii_case(tag).then_some(at)
177    })
178}
179
180/// The HTML sink: the only interface through which an HTML emitter writes
181/// bytes (see [the module documentation](self)).
182///
183/// A sink is created empty, written into through its entry points, and handed
184/// over as a string by [`finish`](HtmlSink::finish).
185///
186/// The bytes leave the sink through `finish` and by no other way: the `Debug`
187/// form of a sink shows how many bytes have been written, how deep the
188/// block-level nesting is and which elements are open, and never the bytes
189/// themselves, so that no output can be read back through it — see [the module
190/// documentation](self) for why that matters.
191#[derive(Clone, Default)]
192pub struct HtmlSink {
193    out: String,
194    open: Vec<OpenElement>,
195    /// How many open elements were marked as preformatted regions.
196    preformatted: usize,
197    /// How many open elements are block-level, which is the indentation level
198    /// of the next block-level element written.
199    depth: usize,
200}
201
202impl fmt::Debug for HtmlSink {
203    /// The sink's state — the bytes written so far counted, the block-level
204    /// depth, the open elements by tag name and how many of them are
205    /// preformatted regions — and never the bytes written.
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        f.debug_struct("HtmlSink")
208            .field("bytes_written", &self.out.len())
209            .field("depth", &self.depth)
210            .field("open", &self.open.iter().map(|element| &element.tag).collect::<Vec<_>>())
211            .field("preformatted", &self.preformatted)
212            .finish()
213    }
214}
215
216impl HtmlSink {
217    /// An empty sink.
218    pub fn new() -> HtmlSink {
219        HtmlSink::default()
220    }
221
222    /// Writes document text, escaped
223    /// ([`super::escape::escape_text_into`]).
224    ///
225    /// Text is escaped the same way everywhere, a preformatted region
226    /// included: a preformatted region changes how a browser lays text out,
227    /// not how it reads markup.
228    pub fn text(&mut self, text: &str) {
229        escape_text_into(&mut self.out, text);
230    }
231
232    /// Writes a [`Markup`] value: HTML that is written unchanged, without
233    /// escaping.
234    ///
235    /// It is one of the two entry points that write bytes unescaped; the other
236    /// is [`raw_text_element`](HtmlSink::raw_text_element), for the content of
237    /// a `<style>` or a `<script>`. See [`Markup`] for what the creator of the
238    /// value must ensure.
239    pub fn markup(&mut self, markup: &Markup) {
240        self.out.push_str(markup.as_str());
241    }
242
243    /// Writes a [`Markup`] value as **block-level** content: on a line of its
244    /// own, at the indentation of the place where it is written, and with the
245    /// closing tag of the enclosing element written on a line of its own too.
246    ///
247    /// This is how HTML that this library already wrote is placed inside other
248    /// HTML: the page assembly writes each document tree's HTML into
249    /// the page through it, so that the line break between two block-level
250    /// tags is there at the join as it is everywhere else: after the opening
251    /// tag of the element the trees are written into, between two trees, and
252    /// before that element's closing tag.
253    ///
254    /// The bytes themselves are written unchanged. The
255    /// indentation *inside* them is not touched: changing it would mean
256    /// reading finished output back and rewriting it, which this sink offers
257    /// no way to do. The line break and the indentation *before* them are
258    /// written as the bytes are placed, as for every block-level element
259    /// written through this sink.
260    ///
261    /// This is not a second path for unescaped bytes. What it writes is a
262    /// [`Markup`] value, created under the requirement that type's
263    /// documentation states, and this entry point changes nothing about that
264    /// requirement: it decides where the bytes are placed and nothing about
265    /// what they are. Everything [`markup`](HtmlSink::markup) says therefore
266    /// holds here too.
267    ///
268    /// Nothing is introduced inside a preformatted region or in inline flow,
269    /// exactly as when a block-level element is opened; the caller places the
270    /// markup where a block-level element could be placed.
271    ///
272    /// # Examples
273    ///
274    /// ```
275    /// use flm_core::stdlib::backends::html::{HtmlSink, Markup};
276    ///
277    /// let mut sink = HtmlSink::new();
278    /// sink.open_block("main").finish();
279    /// sink.markup_block(&Markup::trusted("<p>one</p>\n<p>two</p>"));
280    /// sink.close();
281    /// // The markup begins on a line of its own, at the indentation of the
282    /// // place where it is written, and keeps its own line breaks inside.
283    /// assert_eq!(sink.finish(), "<main>\n  <p>one</p>\n<p>two</p>\n</main>");
284    /// ```
285    pub fn markup_block(&mut self, markup: &Markup) {
286        self.begin_block_position();
287        self.markup(markup);
288    }
289
290    /// Opens a **block-level** element with the tag name `tag` and hands back
291    /// the [`TagBuilder`] that writes its attributes.
292    ///
293    /// Block-level is what the line breaks and the indentation are written
294    /// between (see [the module documentation](self)). The element stays open
295    /// until [`close`](HtmlSink::close).
296    ///
297    /// # Preconditions
298    ///
299    /// The caller has validated `tag` with [`is_valid_tag_name`]; the tag
300    /// name is then written unchanged. A name that fails that check is a
301    /// programming error in the calling code, never document input, since a
302    /// name that came from a [construct node](super::construct) is checked by
303    /// the emitter, which reports the node it refused.
304    ///
305    /// # Panics
306    ///
307    /// *Debug builds only*: `tag` fails that check. A release build writes the
308    /// name unchanged, which may produce markup the caller did not intend.
309    pub fn open_block(&mut self, tag: &str) -> TagBuilder<'_> {
310        self.open_element(tag, true)
311    }
312
313    /// Opens an **inline** element with the tag name `tag` and hands back the
314    /// [`TagBuilder`] that writes its attributes.
315    ///
316    /// No whitespace is ever introduced around or inside an inline element:
317    /// whitespace there is text a reader sees. The element stays open until
318    /// [`close`](HtmlSink::close).
319    ///
320    /// # Preconditions
321    ///
322    /// The caller has validated `tag`, as for
323    /// [`open_block`](HtmlSink::open_block).
324    ///
325    /// # Panics
326    ///
327    /// *Debug builds only*: `tag` fails that check.
328    pub fn open_inline(&mut self, tag: &str) -> TagBuilder<'_> {
329        self.open_element(tag, false)
330    }
331
332    /// Writes a block-level element that has no content and is never closed —
333    /// `<hr>`, `<meta>` — and hands back the [`TagBuilder`] that writes its
334    /// attributes.
335    ///
336    /// # Preconditions
337    ///
338    /// The caller has validated `tag`, as for
339    /// [`open_block`](HtmlSink::open_block).
340    ///
341    /// # Panics
342    ///
343    /// *Debug builds only*: `tag` fails that check.
344    pub fn void_block(&mut self, tag: &str) -> TagBuilder<'_> {
345        self.void_element(tag, true)
346    }
347
348    /// Writes an inline element that has no content and is never closed —
349    /// `<img>`, `<br>` — and hands back the [`TagBuilder`] that writes its
350    /// attributes.
351    ///
352    /// # Preconditions
353    ///
354    /// The caller has validated `tag`, as for
355    /// [`open_block`](HtmlSink::open_block).
356    ///
357    /// # Panics
358    ///
359    /// *Debug builds only*: `tag` fails that check.
360    pub fn void_inline(&mut self, tag: &str) -> TagBuilder<'_> {
361        self.void_element(tag, false)
362    }
363
364    /// Closes the element the sink opened last.
365    ///
366    /// Elements therefore close in the order they were opened, by
367    /// construction: there is no way to name another one.
368    ///
369    /// # Panics
370    ///
371    /// When no element is open. That is a mistake in the emitter — it closed
372    /// something it did not open — and never anything a document can cause.
373    pub fn close(&mut self) {
374        let element =
375            self.open.pop().expect("the emitter closed an element the sink had not opened");
376        if element.preformatted {
377            self.preformatted -= 1;
378        }
379        if element.block {
380            self.depth -= 1;
381            if element.block_children {
382                self.break_line();
383            }
384        }
385        self.out.push_str("</");
386        self.out.push_str(&element.tag);
387        self.out.push('>');
388    }
389
390    /// Writes a **raw text element** — a `<style>` or a `<script>` — with the
391    /// attributes given and `content` as its content, written byte for byte.
392    ///
393    /// A browser reads the content of such an element as raw text up to the
394    /// element's closing tag, so nothing in it can be escaped: this is where
395    /// the text of a style or script definition, and what a host put in its
396    /// place, is written.
397    ///
398    /// `style` and `script` are the two elements HTML reads that way, and this
399    /// entry point writes those two tags and no other: an element whose
400    /// content a browser does read as markup — `<textarea>`, `<title>` — is
401    /// written through [`open_block`](HtmlSink::open_block) or
402    /// [`open_inline`](HtmlSink::open_inline) and [`text`](HtmlSink::text),
403    /// which escape what they write.
404    ///
405    /// The attributes are written in the order given, each value escaped as
406    /// any other attribute value.
407    ///
408    /// This is one of the two entry points that write bytes unescaped; the
409    /// other is [`markup`](HtmlSink::markup).
410    ///
411    /// # Errors
412    ///
413    /// [`RawTextRefused`] when `content` holds the element's own closing tag,
414    /// in any letter case, which would end the element there; nothing is
415    /// written then.
416    ///
417    /// # Preconditions
418    ///
419    /// The content is written without escaping, so the caller must ensure that
420    /// it does not come from a document or from any other input the caller does
421    /// not control (this library passes only the text of style and script
422    /// definitions here).
423    ///
424    /// The caller has validated every attribute name with
425    /// [`is_valid_attribute_name`]; a name that fails that check is a
426    /// programming error in the calling code, never document input.
427    ///
428    /// # Panics
429    ///
430    /// When `tag` is neither `style` nor `script`. The content of this element
431    /// is written unescaped, so writing it into an element a browser parses
432    /// some other way would put unescaped bytes where they are read as markup;
433    /// that is a programming error in the calling code, and the method panics
434    /// in every build rather than only in a debug build.
435    ///
436    /// *Debug builds only*: an attribute name fails the check above.
437    ///
438    /// # Examples
439    ///
440    /// ```
441    /// use flm_core::stdlib::backends::html::HtmlSink;
442    ///
443    /// let mut sink = HtmlSink::new();
444    /// sink.raw_text_element("style", &[("media", "screen")], ".flm-pres-par { margin: 0 }\n")
445    ///     .expect("the stylesheet holds no closing tag");
446    /// assert_eq!(
447    ///     sink.finish(),
448    ///     "<style media=\"screen\">.flm-pres-par { margin: 0 }\n</style>",
449    /// );
450    /// ```
451    pub fn raw_text_element(
452        &mut self,
453        tag: &str,
454        attributes: &[(&str, &str)],
455        content: &str,
456    ) -> Result<(), RawTextRefused> {
457        assert!(
458            RAW_TEXT_TAGS.contains(&tag),
459            "a raw text element is a <style> or a <script>, not a <{tag}>: the content of any \
460             other element is escaped where it is written"
461        );
462        if let Some(at) = closing_tag_at(content, tag) {
463            return Err(RawTextRefused { tag: tag.to_string(), at });
464        }
465        self.begin_block_position();
466        self.out.push('<');
467        self.out.push_str(tag);
468        for (name, value) in attributes {
469            self.write_attribute(name, value);
470        }
471        self.out.push('>');
472        // The content enters the page unescaped, as this element demands, and
473        // it does so through the one door for unescaped bytes.
474        self.markup(&Markup::from_library(content));
475        self.out.push_str("</");
476        self.out.push_str(tag);
477        self.out.push('>');
478        Ok(())
479    }
480
481    /// How many bytes have been written so far.
482    ///
483    /// This is a count, not content: the sink still offers no way to read what
484    /// it wrote, so no decision can depend on the bytes and no escaping can run
485    /// over them a second time. The count exists because an emitter has to be
486    /// able to say *where* in its output something was written — the HTML
487    /// emitter
488    /// records the offset at which a document tree placed in another tree
489    /// belongs, so that the page assembly can write that tree's HTML there.
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// use flm_core::stdlib::backends::html::HtmlSink;
495    ///
496    /// let mut sink = HtmlSink::new();
497    /// assert_eq!(sink.len(), 0);
498    /// sink.text("a<b");
499    /// assert_eq!(sink.len(), "a&lt;b".len());
500    /// ```
501    pub fn len(&self) -> usize {
502        self.out.len()
503    }
504
505    /// Whether nothing has been written yet.
506    pub fn is_empty(&self) -> bool {
507        self.out.is_empty()
508    }
509
510    /// The tag of the element the sink would close next — the one it opened
511    /// last — or `None` when no element is open.
512    ///
513    /// Like [`len`](HtmlSink::len), this returns a fact about the sink's state
514    /// and never the bytes written. It lets an emitter that keeps its own
515    /// record of the elements it has opened (the HTML emitter keeps one for the
516    /// elements inside a formula, which it may have to write a second time)
517    /// check, in a debug build, that its record and the sink's agree.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use flm_core::stdlib::backends::html::HtmlSink;
523    ///
524    /// let mut sink = HtmlSink::new();
525    /// assert_eq!(sink.open_tag(), None);
526    /// sink.open_inline("em").finish();
527    /// assert_eq!(sink.open_tag(), Some("em"));
528    /// sink.close();
529    /// assert_eq!(sink.open_tag(), None);
530    /// ```
531    pub fn open_tag(&self) -> Option<&str> {
532        self.open.last().map(|element| element.tag.as_str())
533    }
534
535    /// Returns the HTML written, ending the sink.
536    ///
537    /// # Panics
538    ///
539    /// When an element is still open. That is a mistake in the emitter — it
540    /// would hand over a page with an unclosed element — and never anything a
541    /// document can cause.
542    pub fn finish(self) -> String {
543        assert!(
544            self.open.is_empty(),
545            "the emitter finished the sink with {} element(s) still open: {}",
546            self.open.len(),
547            self.open.iter().map(|e| e.tag.as_str()).collect::<Vec<_>>().join(", ")
548        );
549        self.out
550    }
551
552    // --- the writing the entry points share ------------------------------------------
553
554    /// Opens an element and pushes it on the stack of open elements.
555    ///
556    /// The tag name is the caller's to validate; the check is repeated here in
557    /// a debug build.
558    fn open_element(&mut self, tag: &str, block: bool) -> TagBuilder<'_> {
559        debug_assert!(
560            is_valid_tag_name(tag),
561            "the caller opened an element whose tag name is not writable: {tag:?}"
562        );
563        if block {
564            self.begin_block_position();
565        }
566        self.out.push('<');
567        self.out.push_str(tag);
568        self.open.push(OpenElement {
569            tag: tag.to_string(),
570            block,
571            block_children: false,
572            preformatted: false,
573        });
574        if block {
575            self.depth += 1;
576        }
577        TagBuilder { sink: self, opened: true }
578    }
579
580    /// Writes an element that has no content and closes nothing.
581    ///
582    /// The tag name is the caller's to validate; the check is repeated here in
583    /// a debug build.
584    fn void_element(&mut self, tag: &str, block: bool) -> TagBuilder<'_> {
585        debug_assert!(
586            is_valid_tag_name(tag),
587            "the caller wrote an element whose tag name is not writable: {tag:?}"
588        );
589        if block {
590            self.begin_block_position();
591        }
592        self.out.push('<');
593        self.out.push_str(tag);
594        TagBuilder { sink: self, opened: false }
595    }
596
597    /// Prepares the place a block-level element is about to be written at: the
598    /// line break and the indentation before it, and the record on the
599    /// enclosing element that its closing tag goes on a line of its own.
600    ///
601    /// Nothing is introduced inside a preformatted region, nor in inline flow
602    /// — inside an element opened as inline — where introduced whitespace
603    /// would be text.
604    fn begin_block_position(&mut self) {
605        if self.preformatted > 0 || self.open.last().is_some_and(|element| !element.block) {
606            return;
607        }
608        self.break_line();
609        if let Some(parent) = self.open.last_mut() {
610            parent.block_children = true;
611        }
612    }
613
614    /// Writes a line break and the indentation of the current level, unless
615    /// nothing has been written yet.
616    fn break_line(&mut self) {
617        if self.out.is_empty() {
618            return;
619        }
620        self.out.push('\n');
621        for _ in 0..self.depth {
622            self.out.push_str(INDENT);
623        }
624    }
625
626    /// Writes ` name="value"`, the value escaped.
627    ///
628    /// The name is the caller's to validate, at every entry point that takes
629    /// one; the check is repeated here in a debug build.
630    fn write_attribute(&mut self, name: &str, value: &str) {
631        debug_assert!(
632            is_valid_attribute_name(name),
633            "the caller wrote an attribute whose name is not writable: {name:?}"
634        );
635        self.out.push(' ');
636        self.out.push_str(name);
637        self.out.push_str("=\"");
638        escape_attr_into(&mut self.out, value);
639        self.out.push('"');
640    }
641
642    /// Writes ` name='value'`, the value escaped for a single-quoted attribute.
643    ///
644    /// The name is the caller's to validate, as
645    /// [`write_attribute`](HtmlSink::write_attribute) states.
646    fn write_json_attribute(&mut self, name: &str, value: &str) {
647        debug_assert!(
648            is_valid_attribute_name(name),
649            "the caller wrote an attribute whose name is not writable: {name:?}"
650        );
651        self.out.push(' ');
652        self.out.push_str(name);
653        self.out.push_str("='");
654        escape_attr_single_quoted_into(&mut self.out, value);
655        self.out.push('\'');
656    }
657}
658
659/// The attributes of the element being opened, written one by one, and the
660/// [`finish`](TagBuilder::finish) that ends the opening tag.
661///
662/// A builder is obtained from [`HtmlSink::open_block`],
663/// [`HtmlSink::open_inline`], [`HtmlSink::void_block`] or
664/// [`HtmlSink::void_inline`], and its calls chain:
665///
666/// ```
667/// use flm_core::stdlib::backends::html::HtmlSink;
668///
669/// let mut sink = HtmlSink::new();
670/// sink.void_inline("img")
671///     .class(["flm-pres-image"])
672///     .attr("src", "plot.png")
673///     .attr("alt", "a \"plot\"")
674///     .finish();
675/// assert_eq!(sink.finish(), "<img class=\"flm-pres-image\" src=\"plot.png\" alt=\"a &quot;plot&quot;\">");
676/// ```
677///
678/// Attributes are written in the order the calls are made, and the sink
679/// neither reorders them nor checks that a name occurs once: the order is the
680/// emitter's, which fixes it so that output can be compared byte for byte.
681///
682/// # Preconditions
683///
684/// Attribute *names* are written unchanged, so the caller has validated
685/// every one of them with [`is_valid_attribute_name`]; a name that comes from
686/// a [construct node](super::construct) is checked by the
687/// emitter, which reports the node it refused. A name that fails the check is
688/// a programming error in the calling code, never document input, and the
689/// builder's entry points check it again in a debug build.
690#[must_use = "the opening tag is unfinished until finish() is called"]
691pub struct TagBuilder<'s> {
692    sink: &'s mut HtmlSink,
693    /// Whether the element was pushed on the sink's stack of open elements,
694    /// which a void element is not.
695    opened: bool,
696}
697
698impl<'s> TagBuilder<'s> {
699    /// Writes the `class` attribute holding `classes`, separated by single
700    /// spaces.
701    ///
702    /// Call it once per element, before the other attributes: the class comes
703    /// first in every element this backend writes. It exists beside
704    /// [`attr`](TagBuilder::attr) because the class attribute is the only one
705    /// whose value this backend builds from several names (the element's, the
706    /// role's), and joining them here keeps every caller from writing the
707    /// separator.
708    pub fn class<I, S>(self, classes: I) -> TagBuilder<'s>
709    where
710        I: IntoIterator<Item = S>,
711        S: AsRef<str>,
712    {
713        let mut value = String::new();
714        for class in classes {
715            if !value.is_empty() {
716                value.push(' ');
717            }
718            value.push_str(class.as_ref());
719        }
720        self.attr("class", &value)
721    }
722
723    /// Writes ` name="value"`, the value escaped
724    /// ([`super::escape::escape_attr_into`]) and always inside double
725    /// quotation marks.
726    ///
727    /// This, [`attr_json`](TagBuilder::attr_json) and [`HtmlSink::text`] are
728    /// the three entry points document-derived text reaches a page through.
729    ///
730    /// # Preconditions
731    ///
732    /// The caller has validated `name`, as [the builder](TagBuilder) states.
733    ///
734    /// # Panics
735    ///
736    /// *Debug builds only*: `name` fails that check. A release build writes
737    /// the name unchanged, which may produce markup the caller did not
738    /// intend.
739    pub fn attr(self, name: &str, value: &str) -> TagBuilder<'s> {
740        self.sink.write_attribute(name, value);
741        self
742    }
743
744    /// Writes ` name='value'`, the value escaped
745    /// ([`super::escape::escape_attr_single_quoted_into`]) and always inside
746    /// single quotation marks.
747    ///
748    /// This is how an attribute whose value is **JSON** is written.
749    /// HTML allows either quotation mark around an attribute value; inside
750    /// single ones a double quotation mark is written as itself, so the raw page
751    /// shows the JSON as JSON —
752    /// `data-flm-source-span='["book/ch1.flm",0,8]'` — instead of a run of
753    /// `&quot;`. Only `&` and `'` are rewritten, and unconditionally: like
754    /// [`attr`](TagBuilder::attr), this is a place document-derived text
755    /// reaches a page through, and text that reaches it cannot leave the
756    /// attribute.
757    ///
758    /// The sink neither builds the JSON nor checks that the value is JSON:
759    /// the caller is responsible for that, and this backend's only such
760    /// attribute is built by its emitter.
761    ///
762    /// # Preconditions
763    ///
764    /// The caller has validated `name`, as [the builder](TagBuilder) states.
765    ///
766    /// # Panics
767    ///
768    /// *Debug builds only*: `name` fails that check. A release build writes
769    /// the name unchanged, which may produce markup the caller did not
770    /// intend.
771    pub fn attr_json(self, name: &str, value: &str) -> TagBuilder<'s> {
772        self.sink.write_json_attribute(name, value);
773        self
774    }
775
776    /// Writes ` name`, an attribute whose presence is the whole of what it
777    /// says — `hidden`, `defer` — and which therefore has no value.
778    ///
779    /// # Preconditions
780    ///
781    /// The caller has validated `name`, as [the builder](TagBuilder) states.
782    ///
783    /// # Panics
784    ///
785    /// *Debug builds only*: `name` fails that check.
786    pub fn flag(self, name: &str) -> TagBuilder<'s> {
787        debug_assert!(
788            is_valid_attribute_name(name),
789            "the caller wrote an attribute whose name is not writable: {name:?}"
790        );
791        self.sink.out.push(' ');
792        self.sink.out.push_str(name);
793        self
794    }
795
796    /// Marks the element's content as a **preformatted region**: every space
797    /// and line break inside it is text a reader sees, so the sink introduces
798    /// no line break and no indentation anywhere inside it, down to the
799    /// element's closing tag.
800    ///
801    /// This is what `<pre>` is opened with. A void element has no content, so
802    /// there is no region to mark and the call does nothing.
803    pub fn preformatted(self) -> TagBuilder<'s> {
804        if !self.opened {
805            // A void element has no content, so there is no region to mark.
806            return self;
807        }
808        let Some(element) = self.sink.open.last_mut() else { return self };
809        if !element.preformatted {
810            element.preformatted = true;
811            self.sink.preformatted += 1;
812        }
813        self
814    }
815
816    /// Ends the opening tag, writing `>`.
817    pub fn finish(self) {
818        self.sink.out.push('>');
819    }
820}
821
822impl fmt::Debug for TagBuilder<'_> {
823    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824        f.debug_struct("TagBuilder").field("opened", &self.opened).finish_non_exhaustive()
825    }
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831
832    #[test]
833    fn blocks_are_broken_and_indented_and_inline_content_is_not() {
834        let mut sink = HtmlSink::new();
835        sink.open_block("div").class(["flm-pres-block", "flm-heading"]).finish();
836        sink.open_block("p").finish();
837        sink.text("a ");
838        sink.open_inline("em").finish();
839        sink.text("b");
840        sink.close();
841        sink.text(" c");
842        sink.close();
843        sink.open_block("div").finish();
844        sink.open_block("p").finish();
845        sink.text("d");
846        sink.close();
847        sink.close();
848        sink.close();
849        assert_eq!(
850            sink.finish(),
851            "<div class=\"flm-pres-block flm-heading\">\n  <p>a <em>b</em> c</p>\n  <div>\n    \
852             <p>d</p>\n  </div>\n</div>"
853        );
854    }
855
856    #[test]
857    fn a_block_with_only_inline_content_closes_on_its_own_line_start() {
858        let mut sink = HtmlSink::new();
859        sink.open_block("p").finish();
860        sink.text("only text");
861        sink.close();
862        assert_eq!(sink.finish(), "<p>only text</p>");
863    }
864
865    #[test]
866    fn a_void_element_is_never_closed_and_takes_its_position_from_its_call() {
867        let mut sink = HtmlSink::new();
868        sink.open_block("p").finish();
869        sink.text("see ");
870        sink.void_inline("img").attr("src", "a.png").finish();
871        sink.close();
872        sink.void_block("hr").finish();
873        assert_eq!(sink.finish(), "<p>see <img src=\"a.png\"></p>\n<hr>");
874    }
875
876    #[test]
877    fn nothing_is_introduced_inside_a_preformatted_region() {
878        let mut sink = HtmlSink::new();
879        sink.open_block("pre").class(["flm-pres-verbatim"]).preformatted().finish();
880        sink.open_block("code").finish();
881        sink.text("if a < b:\n    return");
882        sink.close();
883        sink.close();
884        sink.open_block("p").finish();
885        sink.text("after");
886        sink.close();
887        assert_eq!(
888            sink.finish(),
889            "<pre class=\"flm-pres-verbatim\"><code>if a &lt; b:\n    return</code></pre>\n\
890             <p>after</p>"
891        );
892    }
893
894    #[test]
895    fn an_inline_root_is_written_as_it_comes() {
896        let mut sink = HtmlSink::new();
897        sink.text("a ");
898        sink.open_inline("strong").attr("data-flm-style", "bold").finish();
899        sink.text("b");
900        sink.close();
901        assert_eq!(sink.finish(), "a <strong data-flm-style=\"bold\">b</strong>");
902    }
903
904    #[test]
905    fn every_value_is_escaped_and_quoted_and_a_flag_has_none() {
906        let mut sink = HtmlSink::new();
907        sink.void_block("meta").attr("content", "a\"b&c<d>").flag("hidden").finish();
908        assert_eq!(sink.finish(), "<meta content=\"a&quot;b&amp;c&lt;d&gt;\" hidden>");
909    }
910
911    #[test]
912    fn a_json_value_stands_between_single_quotation_marks_with_its_own_escaping() {
913        let mut sink = HtmlSink::new();
914        sink.open_block("p")
915            .attr("title", "a'b")
916            .attr_json("data-flm-source-span", "[\"book/ch1.flm\",0,8]")
917            .finish();
918        sink.close();
919        assert_eq!(
920            sink.finish(),
921            "<p title=\"a'b\" data-flm-source-span='[\"book/ch1.flm\",0,8]'></p>"
922        );
923    }
924
925    #[test]
926    fn a_raw_text_element_refuses_its_own_closing_tag_in_any_letter_case() {
927        let mut sink = HtmlSink::new();
928        let refused = sink
929            .raw_text_element("script", &[], "var a = \"</ScRiPt>\";")
930            .expect_err("the content ends the element");
931        assert_eq!(refused, RawTextRefused { tag: String::from("script"), at: 9 });
932        // Nothing was written for the refused element.
933        assert_eq!(sink.clone().finish(), "");
934        // Another element's closing tag is ordinary content.
935        sink.raw_text_element("script", &[], "var a = \"</style>\";").expect("not its own");
936        assert_eq!(sink.finish(), "<script>var a = \"</style>\";</script>");
937    }
938
939    #[test]
940    fn a_raw_text_element_stands_between_blocks() {
941        let mut sink = HtmlSink::new();
942        sink.open_block("head").finish();
943        sink.raw_text_element("style", &[], "p { margin: 0 }\n").expect("no closing tag");
944        sink.close();
945        assert_eq!(sink.finish(), "<head>\n  <style>p { margin: 0 }\n</style>\n</head>");
946    }
947
948    #[test]
949    fn a_markup_block_stands_on_its_own_line_and_keeps_its_own_indentation() {
950        let mut sink = HtmlSink::new();
951        sink.open_block("main").finish();
952        sink.markup_block(&Markup::trusted("<p>one</p>\n<p>two</p>"));
953        sink.markup_block(&Markup::trusted("<p>three</p>"));
954        sink.close();
955        // Each piece begins on a line of its own at the current indentation,
956        // the closing tag of the element they stand in goes on a line of its
957        // own, and the line breaks inside a piece are the piece's own.
958        assert_eq!(
959            sink.finish(),
960            "<main>\n  <p>one</p>\n<p>two</p>\n  <p>three</p>\n</main>"
961        );
962    }
963
964    #[test]
965    fn a_markup_block_introduces_nothing_in_inline_flow_or_inside_a_preformatted_region() {
966        let mut sink = HtmlSink::new();
967        sink.open_block("p").finish();
968        sink.open_inline("span").finish();
969        sink.markup_block(&Markup::trusted("<b>x</b>"));
970        sink.close();
971        sink.close();
972        assert_eq!(sink.finish(), "<p><span><b>x</b></span></p>");
973
974        let mut sink = HtmlSink::new();
975        sink.open_block("pre").preformatted().finish();
976        sink.markup_block(&Markup::trusted("<code>x</code>"));
977        sink.close();
978        assert_eq!(sink.finish(), "<pre><code>x</code></pre>");
979    }
980
981    #[test]
982    fn the_debug_form_shows_the_state_and_never_the_bytes() {
983        let mut sink = HtmlSink::new();
984        sink.open_block("p").finish();
985        sink.text("secret");
986        sink.open_inline("em").finish();
987        let shown = format!("{sink:?}");
988        assert!(!shown.contains("secret"), "{shown}");
989        assert!(!shown.contains("<p>"), "{shown}");
990        assert_eq!(
991            shown,
992            "HtmlSink { bytes_written: 13, depth: 1, open: [\"p\", \"em\"], preformatted: 0 }"
993        );
994    }
995
996    #[test]
997    #[should_panic]
998    fn a_raw_text_element_is_a_style_or_a_script_and_no_other_tag() {
999        let mut sink = HtmlSink::new();
1000        // `<textarea>`'s content is read as markup, so writing it unescaped
1001        // would put markup where the caller meant text.
1002        let _ = sink.raw_text_element("textarea", &[], "x");
1003    }
1004
1005    #[test]
1006    #[cfg(debug_assertions)]
1007    #[should_panic]
1008    fn a_raw_text_element_checks_its_attribute_names_while_testing() {
1009        // A debug assertion: the test suite is built in debug mode, so the
1010        // check runs here. A release build writes the name as it stands.
1011        let mut sink = HtmlSink::new();
1012        let _ = sink.raw_text_element("style", &[("x\">", "y")], "p{}");
1013    }
1014
1015    #[test]
1016    #[should_panic]
1017    fn closing_what_was_never_opened_is_an_emitter_mistake() {
1018        let mut sink = HtmlSink::new();
1019        sink.open_block("p").finish();
1020        sink.close();
1021        sink.close();
1022    }
1023
1024    #[test]
1025    #[should_panic]
1026    fn finishing_with_an_element_open_is_an_emitter_mistake() {
1027        let mut sink = HtmlSink::new();
1028        sink.open_block("p").finish();
1029        let _ = sink.finish();
1030    }
1031}