Skip to main content

makeover_webview/
facet.rs

1//! A dimension a set is narrowed by, rendered as a list of values.
2//!
3//! The fourth phase-B emitter, beside [`form`](crate::form),
4//! [`list`](crate::list) and [`meter`](crate::meter). Same split as those: this
5//! owns the structure of the panel and the app owns the routes. A value's
6//! identifier leaves in `data-facet-value`, which is the hook an app wires its
7//! own request onto, exactly as [`list`](crate::list) writes `data-column` and
8//! lets the app decide what pressing a heading calls.
9//!
10//! # Why this is markup and not only CSS
11//!
12//! Phase A's rule is that an app keeps its markup and gains the classes, and
13//! that rule works because the markup already existed. Here it mostly does not:
14//! a facet panel is the shape MNW's discover page reached by writing a tick box
15//! and a chevron per row because filtering and browsing were two mechanisms, and
16//! the whole point of [`makeover_layout::Selecting::Subtree`] is that they stop
17//! being two. There is nothing to keep.
18//!
19//! # The one thing drawn that no flat control has
20//!
21//! An exclude affordance beside each value, in a subtree facet only. It is a
22//! visible control rather than a modifier or a long press, and that was ruled
23//! rather than chosen here: a gesture a terminal cannot express is a gesture
24//! half the renderers leave out, and an affordance nothing teaches is one users
25//! do not find. The glyph is this renderer's pick, and it takes the standing
26//! preference for the heavier, simpler mark.
27//!
28//! # What the depth does and does not do
29//!
30//! `--facet-depth` carries the tree level as a number, and the indent rule
31//! multiplies it by one geometry step. That keeps the whole tree one flat list
32//! in the DOM rather than nested lists, which is what lets a renderer draw the
33//! same description as a breadcrumb or a column of panes without the markup
34//! disagreeing. It is not a size: the number is the level, and the step is
35//! `makeover-geometry`'s.
36
37use crate::form::escape_into;
38use crate::reset::Reset;
39use crate::{Emit, class, push_class};
40use makeover_layout::{Depth, Facet, FacetValue, GroupRank, Join, Selecting, Standing};
41use std::fmt::Write as _;
42
43/// The classes this module can put in markup.
44///
45/// [`crate::list::ROW_PART_CLASSES`]' obligation, and it exists for the same
46/// reason: every class here is also ruled by `facet_rules`, so the vocabulary
47/// seal picks them up from the generated sheet, and this list is what a test
48/// checks that against.
49pub const FACET_CLASSES: &[&str] = &[
50    "facet",
51    "facet-name",
52    "facet-values",
53    "facet-value",
54    "facet-take",
55    "facet-count",
56    "facet-prune",
57    "facet-rank",
58    "facet-start",
59    "facet-cut",
60    "facet-join",
61    "facet-join-word",
62];
63
64/// What a value is to a reader, as `data-kind` says it: a pick, a group's
65/// heading (pressing opens it), or a link row (pressing is its whole meaning).
66#[must_use]
67pub const fn kind_name(value: &FacetValue<'_>) -> &'static str {
68    if value.pickable {
69        "value"
70    } else if value.branching {
71        "heading"
72    } else {
73        "link"
74    }
75}
76
77/// The name a selection mode goes by in `data-selecting`.
78///
79/// An attribute rather than a class, for `data-selector`'s reason on a selector
80/// group: the mode changes what the panel *means*, not how one value is
81/// painted, and a class there would read as the styling hook the value's class
82/// actually is.
83#[must_use]
84pub const fn selecting_name(mode: Selecting) -> &'static str {
85    match mode {
86        Selecting::OneOf => "one-of",
87        Selecting::AnyOf => "any-of",
88        Selecting::Range => "range",
89        Selecting::Text => "text",
90        Selecting::Subtree => "subtree",
91        // A mode added to the description since this renderer was built.
92        // `Selecting` is `#[non_exhaustive]`, and an unknown mode reads as the
93        // one that offers no values and prunes nothing: drawing a value list
94        // for a mode whose values mean something else is the worse mistake.
95        _ => "unknown",
96    }
97}
98
99/// The name a standing goes by in `data-standing`.
100#[must_use]
101pub const fn standing_name(standing: Standing) -> &'static str {
102    match standing {
103        Standing::Open => "open",
104        Standing::Taken => "taken",
105        Standing::Inherited => "inherited",
106        Standing::Pruned => "pruned",
107        Standing::PrunedAbove => "pruned-above",
108        // Unknown reads as open, which is the state that claims nothing about
109        // the set.
110        _ => "open",
111    }
112}
113
114/// A facet as a labelled list of values.
115///
116/// ```
117/// use makeover_layout::{Facet, FacetValue, Nesting, Selecting, Standing};
118/// use makeover_webview::{Emit, facet::facet_html};
119///
120/// let values = [
121///     FacetValue::new("music", "Music")
122///         .standing(Standing::Taken)
123///         .counted(128)
124///         .at(Nesting::at(0), true),
125///     FacetValue::new("music/synths", "Synths").at(Nesting::at(1), false),
126/// ];
127/// let facet = Facet::new("Tag", Selecting::Subtree, &values);
128/// let html = facet_html(&facet, &Emit::default());
129///
130/// assert!(html.contains(r#"data-selecting="subtree""#));
131/// assert!(html.contains(r#"data-facet-value="music/synths""#));
132/// // A subtree is the one mode that offers a way to prune a branch out.
133/// assert!(html.contains("facet-prune"));
134/// ```
135///
136/// A [`Selecting::Text`] or [`Selecting::Range`] facet lists nothing, so what
137/// comes back is the panel and its name with an empty list inside it. That is
138/// deliberate rather than an empty string: the app puts its own box in the
139/// panel, and the panel is what gives the box the group label and the shared
140/// geometry.
141#[must_use]
142pub fn facet_html(facet: &Facet<'_>, opts: &Emit) -> String {
143    let mut html = String::new();
144    facet_html_into(facet, opts, &mut html);
145    html
146}
147
148/// A facet, written into a buffer the caller already has.
149///
150/// [`facet_html`]'s streaming form, byte-identical to it.
151pub fn facet_html_into(facet: &Facet<'_>, opts: &Emit, out: &mut String) {
152    emit_facet(facet, opts, &mut Buttons, out, None);
153}
154
155/// A facet whose controls the caller finishes, written into its buffer.
156///
157/// The anatomy is [`facet_html_into`]'s, class for class; `controls` decides
158/// what tag each control is, how it says it is in force, which attributes it
159/// carries beyond the emitter's own, and whether it is drawn at all.
160pub fn facet_html_with(
161    facet: &Facet<'_>,
162    opts: &Emit,
163    controls: &mut impl FacetControls,
164    out: &mut String,
165) {
166    emit_facet(facet, opts, controls, out, None);
167}
168
169/// A facet, saying where each value landed.
170///
171/// Byte-identical to [`facet_html_into`], and it appends one entry to `placed`
172/// per value drawn, in order: the offsets in `out` between which that value's
173/// whole `<li>` was written. For a caller compiling this markup into a
174/// template: a value's label may appear elsewhere in the document, so the
175/// writer is the only source for which bytes one value produced.
176pub fn facet_html_placed(
177    facet: &Facet<'_>,
178    opts: &Emit,
179    out: &mut String,
180    placed: &mut Vec<core::ops::Range<usize>>,
181) {
182    emit_facet(facet, opts, &mut Buttons, out, Some(placed));
183}
184
185/// One of the controls a value draws.
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum FacetControl {
189    /// The value's own control.
190    Take,
191    /// One of an open group's two join words.
192    Join(Join),
193    /// The exclude control, in a mode that prunes.
194    Prune,
195}
196
197/// What an app decides about each control [`facet_html_with`] draws.
198///
199/// `index` is the value's position in [`Facet::values`]. Every method defaults
200/// to what [`facet_html`] writes: a button, `aria-pressed`, nothing more.
201pub trait FacetControls {
202    /// Whether the control is drawn at all.
203    fn draws(&mut self, _index: usize, _control: FacetControl) -> bool {
204        true
205    }
206
207    /// Open the control's tag up to its class, and return the tag that closes
208    /// it.
209    fn open(&mut self, _index: usize, _control: FacetControl, out: &mut String) -> &'static str {
210        out.push_str("<button type=\"button\"");
211        "</button>"
212    }
213
214    /// Say whether the control is in force, as an attribute.
215    fn state(&mut self, _index: usize, _control: FacetControl, on: bool, out: &mut String) {
216        out.push_str(if on {
217            " aria-pressed=\"true\""
218        } else {
219            " aria-pressed=\"false\""
220        });
221    }
222
223    /// Attributes written after the emitter's own, before the tag closes.
224    fn attrs(&mut self, _index: usize, _control: FacetControl, _out: &mut String) {}
225}
226
227struct Buttons;
228
229impl FacetControls for Buttons {}
230
231fn emit_facet(
232    facet: &Facet<'_>,
233    opts: &Emit,
234    controls: &mut impl FacetControls,
235    out: &mut String,
236    mut placed: Option<&mut Vec<core::ops::Range<usize>>>,
237) {
238    out.push_str("<div class=\"");
239    push_class(out, "facet", opts);
240    out.push_str("\" role=\"group\" data-selecting=\"");
241    out.push_str(selecting_name(facet.mode));
242    // The gutter an indenting renderer reserves before it draws anything, so
243    // the panel does not widen as deeper values arrive. "First paint is final
244    // paint" applied to a tree.
245    let _ = write!(
246        out,
247        "\" {}=\"--facet-reach: {}\">",
248        crate::VARS_ATTR,
249        facet.reach()
250    );
251
252    out.push_str("<p class=\"");
253    push_class(out, "facet-name", opts);
254    out.push_str("\">");
255    escape_into(facet.name, out);
256    out.push_str("</p>");
257
258    out.push_str("<ul class=\"");
259    push_class(out, "facet-values", opts);
260    out.push_str("\">");
261    if facet.mode.offers_values() {
262        for (index, value) in facet.values.iter().enumerate() {
263            let at = out.len();
264            value_html_into(facet, index, value, opts, controls, out);
265            if let Some(placed) = placed.as_deref_mut() {
266                placed.push(at..out.len());
267            }
268        }
269    }
270    out.push_str("</ul></div>");
271}
272
273/// Open a control through `controls`: its tag, its class and the value it
274/// stands for. Returns the tag that closes it.
275fn control_open(
276    controls: &mut impl FacetControls,
277    index: usize,
278    control: FacetControl,
279    class: &str,
280    value: &FacetValue<'_>,
281    opts: &Emit,
282    out: &mut String,
283) -> &'static str {
284    let close = controls.open(index, control, out);
285    out.push_str(" class=\"");
286    push_class(out, class, opts);
287    out.push_str("\" data-facet-value=\"");
288    escape_into(value.value, out);
289    out.push('"');
290    close
291}
292
293/// A value at rest counted at zero: picking it would answer nothing. An
294/// uncounted value is never empty, and a value in force or pruned stands as
295/// decided, so its control stays.
296fn is_empty(value: &FacetValue<'_>) -> bool {
297    value.pickable && value.count == Some(0) && value.standing == Standing::Open
298}
299
300fn value_html_into(
301    facet: &Facet<'_>,
302    index: usize,
303    value: &FacetValue<'_>,
304    opts: &Emit,
305    controls: &mut impl FacetControls,
306    out: &mut String,
307) {
308    out.push_str("<li class=\"");
309    push_class(out, "facet-value", opts);
310    out.push_str("\" data-standing=\"");
311    out.push_str(standing_name(value.standing));
312    out.push_str("\" data-kind=\"");
313    out.push_str(kind_name(value));
314    let _ = write!(
315        out,
316        "\" {}=\"--facet-depth: {}\">",
317        crate::VARS_ATTR,
318        value.depth.level
319    );
320
321    // An empty value is drawn where its control would be and answers no
322    // press, so it takes the disabled ink and offers no exclude either.
323    if is_empty(value) {
324        out.push_str("<span class=\"");
325        push_class(out, "facet-take", opts);
326        out.push_str("\" aria-disabled=\"true\" data-facet-value=\"");
327        escape_into(value.value, out);
328        out.push_str("\">");
329        escape_into(value.label, out);
330        out.push_str("<span class=\"");
331        push_class(out, "facet-count", opts);
332        out.push_str("\">0</span></span></li>");
333        return;
334    }
335
336    let take = FacetControl::Take;
337    let close = control_open(controls, index, take, "facet-take", value, opts, out);
338    // In force and not picked by hand: an inherited value is pressed in fact
339    // even though nobody pressed it, which is `Standing::in_force`. A heading
340    // or a link row picks nothing, so it is not a toggle at all.
341    if value.pickable {
342        controls.state(index, take, value.standing.in_force(), out);
343    }
344    // A branch that opens says so, so a reader is told there is more before
345    // pressing rather than after. Open is its own state where the app keeps
346    // one, since opening a group is not picking it.
347    if value.branching {
348        out.push_str(" aria-expanded=\"");
349        out.push_str(if value.is_open() { "true\"" } else { "false\"" });
350    }
351    controls.attrs(index, take, out);
352    out.push('>');
353    escape_into(value.label, out);
354
355    // Absent rather than zero when it was not measured, which is the
356    // description's own position: a written zero reads as "none of them". A
357    // gain is what picking adds beside a pick already made under the same
358    // parent, so it carries its sign.
359    if let Some(count) = value.count {
360        out.push_str("<span class=\"");
361        push_class(out, "facet-count", opts);
362        let sign = if value.gain { "+" } else { "" };
363        let _ = write!(out, "\">{sign}{count}</span>");
364    } else if let Some(rank) = value.rank {
365        rank_html_into(rank, opts, out);
366    }
367    out.push_str(close);
368
369    if !value.pickable
370        && value.is_open()
371        && let Some(join) = value.join
372    {
373        join_html_into(index, value, join, opts, controls, out);
374    }
375
376    let prune = FacetControl::Prune;
377    if facet.mode.prunes() && value.pickable && controls.draws(index, prune) {
378        let close = control_open(controls, index, prune, "facet-prune", value, opts, out);
379        // Pressed for the value's own prune only: a value out by a prune above
380        // it is not pressed here, because the decision is not here.
381        controls.state(index, prune, value.standing == Standing::Pruned, out);
382        // The accessible name is built here rather than described: a tooltip
383        // wants a sentence and a terminal wants a glyph, and a description
384        // shipping either would choose for both.
385        out.push_str(" aria-label=\"");
386        escape_into(opts.exclude_label, out);
387        out.push(' ');
388        escape_into(value.label, out);
389        out.push('"');
390        controls.attrs(index, prune, out);
391        // The heavier, simpler mark. It is the glyph and not a class, because a
392        // renderer that swaps it is not changing what the control means.
393        // U+2718 because the house faces draw it (quasi-type's BODY_SURFACE);
394        // U+2715 is in no served face and drew as a missing glyph.
395        out.push_str(">\u{2718}");
396        out.push_str(close);
397    }
398
399    out.push_str("</li>");
400}
401
402/// Where a group ranks, at the end of its heading: the start mark, then a bar
403/// whose length is the cut, or a word when the group is in use or dead.
404///
405/// The bar is drawn, not written: its length is `--facet-cut` through
406/// [`VARS_ATTR`](crate::VARS_ATTR), as the depth is, so a strict style policy
407/// refuses nothing. It is hidden from the accessibility tree, since the order
408/// of the groups already says what the bars do.
409pub fn rank_html_into(rank: GroupRank, opts: &Emit, out: &mut String) {
410    out.push_str("<span class=\"");
411    push_class(out, "facet-rank", opts);
412    out.push_str("\">");
413    if rank.start {
414        out.push_str("<span class=\"");
415        push_class(out, "facet-start", opts);
416        out.push_str("\">");
417        escape_into(opts.start_label, out);
418        out.push_str("</span>");
419    }
420    if rank.in_use || !rank.live {
421        out.push_str("<span class=\"");
422        push_class(out, "facet-count", opts);
423        out.push_str("\">");
424        escape_into(
425            if rank.in_use {
426                opts.in_use_label
427            } else {
428                opts.dead_label
429            },
430            out,
431        );
432        out.push_str("</span>");
433    } else {
434        out.push_str("<span class=\"");
435        push_class(out, "facet-cut", opts);
436        let _ = write!(
437            out,
438            "\" aria-hidden=\"true\" {}=\"--facet-cut: {}%\"></span>",
439            crate::VARS_ATTR,
440            rank.cut
441        );
442    }
443    out.push_str("</span>");
444}
445
446/// The toggle on an open group: how the picks under it combine. Two words, the
447/// one in force pressed, each naming the group in `data-facet-value` and its
448/// word in `data-facet-join` for the app to wire, as the take and the prune do.
449fn join_html_into(
450    index: usize,
451    value: &FacetValue<'_>,
452    join: Join,
453    opts: &Emit,
454    controls: &mut impl FacetControls,
455    out: &mut String,
456) {
457    let words = [(Join::Any, opts.any_label), (Join::All, opts.all_label)];
458    if !words
459        .iter()
460        .all(|&(word, _)| controls.draws(index, FacetControl::Join(word)))
461    {
462        return;
463    }
464    out.push_str("<span class=\"");
465    push_class(out, "facet-join", opts);
466    out.push_str("\" role=\"group\" aria-label=\"");
467    escape_into(opts.join_label, out);
468    out.push(' ');
469    escape_into(value.label, out);
470    out.push_str("\">");
471    for (word, label) in words {
472        let control = FacetControl::Join(word);
473        let close = control_open(
474            controls,
475            index,
476            control,
477            "facet-join-word",
478            value,
479            opts,
480            out,
481        );
482        out.push_str(" data-facet-join=\"");
483        out.push_str(join_name(word));
484        out.push('"');
485        controls.state(index, control, word == join, out);
486        controls.attrs(index, control, out);
487        out.push('>');
488        escape_into(label, out);
489        out.push_str(close);
490    }
491    out.push_str("</span>");
492}
493
494/// The name a join goes by in `data-facet-join`.
495#[must_use]
496pub const fn join_name(join: Join) -> &'static str {
497    match join {
498        Join::All => "all",
499        // Unknown reads as any, the default every parent starts at.
500        _ => "any",
501    }
502}
503
504/// The rules for a facet panel.
505///
506/// Depth comes from the description: a value at rest sits as
507/// [`Depth::Flat`] and a taken one is held in, which is
508/// [`makeover_layout::Selector::chosen`]'s shape for a segment and is the same
509/// sentence, this one is picked, so it is pressed. Nothing here states a
510/// colour or a size; the indent is a count multiplied by a geometry step, and
511/// the step is the one variable this crate is allowed to read.
512pub(crate) fn facet_rules(opts: &Emit) -> String {
513    let mut css = String::new();
514    let panel = class("facet", opts);
515    let name = class("facet-name", opts);
516    let values = class("facet-values", opts);
517    let value = class("facet-value", opts);
518    let take = class("facet-take", opts);
519    let count = class("facet-count", opts);
520    let prune = class("facet-prune", opts);
521
522    // The name of the dimension. A caption, and captions are legitimately
523    // muted: it was never going to answer a press.
524    let _ = writeln!(css, ".{name} {{\n    color: var(--content-muted);\n}}");
525
526    // The list gives back what a `<ul>` brought, the same ask `row_rules`
527    // makes: a described set of tags is not a bulleted list and rendered as one
528    // because nothing said otherwise.
529    css.push_str(&Reset::BULLETS.rule(&format!(".{values}")));
530
531    // A value is one line: its control, then its exclude control. The indent
532    // is the level times one geometry step. `--facet-depth` is written per value
533    // and `--facet-reach` per panel; the panel one reserves the gutter so
534    // nothing moves as deeper values arrive. Both read `--gap-group`, which
535    // makeover-geometry defines: they read `--space-tight`, which nothing
536    // defines, and so always took the literal fallback.
537    let _ = writeln!(
538        css,
539        ".{value} {{\n    display: flex;\n    align-items: center;\n    gap: var(--gap-bound);\n    padding-inline-start: calc(var(--facet-depth, 0) * var(--gap-group));\n}}"
540    );
541
542    let _ = writeln!(
543        css,
544        ".{panel} {{\n    min-inline-size: calc(var(--facet-reach, 0) * var(--gap-group));\n}}"
545    );
546
547    // The value's own control. Flat at rest, held in when it is in force, and
548    // that is the segmented control's sentence rather than a new one.
549    //
550    // Flat states nothing, no fill and no bevel, so `depth_rule` emitted an
551    // empty string and saying it was the whole of what this arm did. Where an
552    // app hands makeover the cascade with `revert-layer`, an empty layer rolls
553    // the handoff past makeover to the app's own bare `button` rule and the
554    // value renders raised, with `[aria-pressed="true"]` its only true state.
555    // Flat here has to be said out loud, which is what the reset is for.
556    css.push_str(&Reset::FLAT_BUTTON.rule(&format!(".{take}")));
557    // The control fills the line, label at its start and count at its end, so
558    // the counts of a column of values line up. It reads as content whichever
559    // element it is: a host giving a value a real address draws an anchor,
560    // which would otherwise wear link colour and an underline.
561    let _ = writeln!(
562        css,
563        ".{take} {{\n    display: flex;\n    flex: 1 1 auto;\n    align-items: center;\n    justify-content: space-between;\n    gap: var(--gap-peer);\n    min-block-size: var(--tap-target, 2rem);\n    padding: 0 var(--gap-bound);\n    color: var(--content);\n    text-decoration: none;\n    text-align: start;\n    font: inherit;\n}}"
564    );
565    css.push_str(&crate::interactive_rules(&take, Depth::Flat, opts));
566    css.push_str(&held_rules(&take));
567
568    // A pruned branch reads one step back and stays live: pressing it takes the
569    // prune off, so it may not wear `content-muted`. `Standing::intent` is
570    // where that is decided. A value out because a branch above it was pruned
571    // reads the same, since to the set the two mean the same thing; the
572    // attribute keeps the difference for whoever wants it, as with inherited.
573    for standing in [Standing::Pruned, Standing::PrunedAbove] {
574        let _ = writeln!(
575            css,
576            ".{value}[data-standing=\"{}\"] .{take} {{\n    color: var(--{});\n}}",
577            standing_name(standing),
578            standing.intent()
579        );
580    }
581
582    // Inherited is in force and was not chosen. It reads as the thing itself,
583    // like a taken value, and the difference is carried by the attribute for
584    // whoever wants it rather than by a colour claiming something.
585    // Figures of one width, so a column of counts reads down.
586    let _ = writeln!(
587        css,
588        ".{count} {{\n    color: var(--content-muted);\n    font-variant-numeric: tabular-nums;\n}}"
589    );
590
591    // Same withdrawal as the take, for the same reason, and a square target at
592    // the end of the line. It reads one step back: it is an offer about the
593    // value, not the value.
594    css.push_str(&Reset::FLAT_BUTTON.rule(&format!(".{prune}")));
595    let _ = writeln!(
596        css,
597        ".{prune} {{\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    min-block-size: var(--tap-target, 2rem);\n    min-inline-size: var(--tap-target, 2rem);\n    color: var(--content-secondary);\n    text-decoration: none;\n    font: inherit;\n}}"
598    );
599    css.push_str(&crate::interactive_rules(&prune, Depth::Flat, opts));
600    css.push_str(&held_rules(&prune));
601    // An empty value offers no exclude, so where the facet prunes it keeps the
602    // exclude's place and its count stays in the column.
603    let _ = writeln!(
604        css,
605        ".{panel}[data-selecting=\"subtree\"] .{take}[aria-disabled=\"true\"] {{\n    margin-inline-end: calc(var(--tap-target, 2rem) + var(--gap-bound));\n}}"
606    );
607
608    // A group's heading reads as a heading: the label carries the weight a
609    // section caption does, and nothing about it says pressed, because
610    // opening a group picks nothing.
611    let rank = class("facet-rank", opts);
612    let start = class("facet-start", opts);
613    let cut = class("facet-cut", opts);
614    let join = class("facet-join", opts);
615    let word = class("facet-join-word", opts);
616    let _ = writeln!(
617        css,
618        ".{value}[data-kind=\"heading\"] .{take} {{\n    font-weight: bold;\n}}"
619    );
620    // A link row is an offer about the list, not a member of it: one step
621    // back, and live.
622    let _ = writeln!(
623        css,
624        ".{value}[data-kind=\"link\"] .{take} {{\n    color: var(--content-secondary);\n}}"
625    );
626
627    // The rank sits where a count would, at the line's end: the start mark,
628    // then the bar. The bar's track is the ramp's own neutral step and its
629    // fill the content tone, so no hue claims anything about a group.
630    let _ = writeln!(
631        css,
632        ".{rank} {{\n    display: inline-flex;\n    align-items: center;\n    gap: var(--gap-peer);\n    font-weight: normal;\n}}"
633    );
634    let _ = writeln!(css, ".{start} {{\n    color: var(--content-secondary);\n}}");
635    let _ = writeln!(
636        css,
637        ".{cut} {{\n    inline-size: calc(var(--gap-pane) * 2);\n    block-size: var(--gap-bound);\n    background: linear-gradient(to right, var(--content-secondary) var(--facet-cut, 0%), var(--surface-raised) 0);\n}}"
638    );
639
640    // The join toggle: two words, the one in force held in, the segmented
641    // control's sentence again.
642    let _ = writeln!(
643        css,
644        ".{join} {{\n    display: inline-flex;\n    flex: none;\n}}"
645    );
646    css.push_str(&Reset::FLAT_BUTTON.rule(&format!(".{word}")));
647    let _ = writeln!(
648        css,
649        ".{word} {{\n    min-block-size: var(--tap-target, 2rem);\n    padding: 0 var(--gap-bound);\n    color: var(--content-secondary);\n    font: inherit;\n}}"
650    );
651    css.push_str(&crate::interactive_rules(&word, Depth::Flat, opts));
652    css.push_str(&held_rules(&word));
653
654    css
655}
656
657/// A control held in while it is in force, whichever element it turned out to
658/// be.
659///
660/// This emitter writes buttons, which say it with `aria-pressed`. A host that
661/// gives a value a real address writes an anchor for a read, and an anchor says
662/// it with `aria-current`, since `aria-pressed` means nothing on one. Keyed on
663/// the first alone, a taken value drawn as a link looked exactly like an
664/// untaken one.
665fn held_rules(class: &str) -> String {
666    let mut css = String::new();
667    for state in ["aria-pressed", "aria-current"] {
668        css.push_str(&crate::depth_rule(
669            &format!("{class}[{state}=\"true\"]"),
670            Depth::Well,
671        ));
672    }
673    css
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679    use makeover_layout::Nesting;
680
681    fn tag_values() -> [FacetValue<'static>; 3] {
682        [
683            FacetValue::new("music", "Music")
684                .standing(Standing::Taken)
685                .counted(128)
686                .at(Nesting::at(0), true),
687            FacetValue::new("music/synths", "Synths")
688                .standing(Standing::Inherited)
689                .at(Nesting::at(1), false),
690            FacetValue::new("music/drums", "Drums")
691                .standing(Standing::Pruned)
692                .at(Nesting::at(1), false),
693        ]
694    }
695
696    #[test]
697    fn a_streamed_facet_is_the_facet_the_other_form_returns() {
698        let opts = Emit {
699            class_prefix: "mk-",
700            ..Emit::default()
701        };
702        let values = tag_values();
703        for facet in [
704            Facet::new("Tag", Selecting::Subtree, &values),
705            Facet::new("Type", Selecting::AnyOf, &values),
706            Facet::new("Search", Selecting::Text, &[]),
707        ] {
708            let mut streamed = String::new();
709            facet_html_into(&facet, &opts, &mut streamed);
710            assert_eq!(streamed, facet_html(&facet, &opts));
711        }
712    }
713
714    /// Links for every take, the prune on the first value left out, and each
715    /// control marked with what it is.
716    struct Links;
717
718    impl FacetControls for Links {
719        fn draws(&mut self, index: usize, control: FacetControl) -> bool {
720            !(index == 0 && control == FacetControl::Prune)
721        }
722
723        fn open(&mut self, _index: usize, control: FacetControl, out: &mut String) -> &'static str {
724            if control == FacetControl::Take {
725                out.push_str("<a");
726                "</a>"
727            } else {
728                out.push_str("<button type=\"button\"");
729                "</button>"
730            }
731        }
732
733        fn state(&mut self, _index: usize, control: FacetControl, on: bool, out: &mut String) {
734            if control != FacetControl::Take {
735                out.push_str(if on {
736                    " aria-pressed=\"true\""
737                } else {
738                    " aria-pressed=\"false\""
739                });
740            } else if on {
741                out.push_str(" aria-current=\"true\"");
742            }
743        }
744
745        fn attrs(&mut self, index: usize, control: FacetControl, out: &mut String) {
746            let _ = write!(out, " data-at=\"{index}:{control:?}\"");
747        }
748    }
749
750    #[test]
751    fn the_controls_a_caller_finishes_keep_the_anatomy_and_take_its_choices() {
752        let opts = Emit::default();
753        let values = tag_values();
754        let facet = Facet::new("Tag", Selecting::Subtree, &values);
755        let mut html = String::new();
756        facet_html_with(&facet, &opts, &mut Links, &mut html);
757
758        assert!(html.contains(
759            r#"<a class="facet-take" data-facet-value="music" aria-current="true" aria-expanded="true" data-at="0:Take">Music"#
760        ), "{html}");
761        assert!(
762            html.contains(r#"<span class="facet-count">128</span></a>"#),
763            "{html}"
764        );
765        // The first value's prune was refused; the others draw theirs.
766        assert!(!html.contains(r#"data-at="0:Prune""#), "{html}");
767        assert!(html.contains(
768            r#"<button type="button" class="facet-prune" data-facet-value="music/drums" aria-pressed="true" aria-label="Exclude Drums" data-at="2:Prune">"#
769        ), "{html}");
770
771        let groups = group_values();
772        let facet = Facet::new("Tags", Selecting::Subtree, &groups);
773        let mut html = String::new();
774        facet_html_with(&facet, &opts, &mut Links, &mut html);
775        assert!(html.contains(
776            r#"class="facet-join-word" data-facet-value="genre" data-facet-join="all" aria-pressed="true" data-at="0:Join(All)">"#
777        ), "{html}");
778    }
779
780    #[test]
781    fn a_caller_that_changes_nothing_writes_the_plain_facet() {
782        let opts = Emit {
783            class_prefix: "mk-",
784            ..Emit::default()
785        };
786        struct Plain;
787        impl FacetControls for Plain {}
788        let values = tag_values();
789        let groups = group_values();
790        for facet in [
791            Facet::new("Tag", Selecting::Subtree, &values),
792            Facet::new("Tags", Selecting::Subtree, &groups),
793        ] {
794            let mut with = String::new();
795            facet_html_with(&facet, &opts, &mut Plain, &mut with);
796            assert_eq!(with, facet_html(&facet, &opts));
797        }
798    }
799
800    #[test]
801    fn only_a_subtree_draws_an_exclude_affordance() {
802        // The one control a flat facet has no use for: excluding a value there
803        // is the same fact as not picking it.
804        let values = tag_values();
805        let subtree = facet_html(
806            &Facet::new("Tag", Selecting::Subtree, &values),
807            &Emit::default(),
808        );
809        assert!(subtree.contains("facet-prune"));
810        assert!(subtree.contains(r#"aria-label="Exclude Drums""#));
811        // The mark is one the house faces draw: U+2715 rendered as a box.
812        assert!(subtree.contains("\u{2718}</button>"), "{subtree}");
813        assert!(!subtree.contains('\u{2715}'), "{subtree}");
814
815        let flat = facet_html(
816            &Facet::new("Type", Selecting::AnyOf, &values),
817            &Emit::default(),
818        );
819        assert!(!flat.contains("facet-prune"));
820    }
821
822    #[test]
823    fn an_inherited_value_reads_as_pressed_without_having_been_pressed() {
824        // The distinction `Standing` has four members for. A renderer given a
825        // bool marks every descendant of a taken branch or marks none, and both
826        // are wrong on screen.
827        let values = tag_values();
828        let html = facet_html(
829            &Facet::new("Tag", Selecting::Subtree, &values),
830            &Emit::default(),
831        );
832        let synths = html
833            .split("<li")
834            .find(|chunk| chunk.contains("music/synths"))
835            .expect("the inherited value");
836        assert!(synths.contains(r#"data-standing="inherited""#));
837        assert!(synths.contains(r#"aria-pressed="true""#));
838
839        let drums = html
840            .split("<li")
841            .find(|chunk| chunk.contains("music/drums"))
842            .expect("the pruned value");
843        // Pruned is a decision and it is not in force, so the take control is
844        // not pressed and the prune control is.
845        assert!(drums.contains(r#"data-standing="pruned""#));
846        assert!(drums.contains(r#"aria-pressed="false""#));
847        assert!(drums.contains(r#"aria-label="Exclude Drums""#));
848    }
849
850    #[test]
851    fn a_value_is_one_line_laid_out_with_geometry_that_exists() {
852        let css = facet_rules(&Emit::default());
853        // `--space-tight` is defined nowhere, so a rule reading it always took
854        // its literal fallback.
855        assert!(!css.contains("--space-tight"), "{css}");
856        assert!(css.contains("var(--gap-group)"), "{css}");
857        assert!(css.contains("justify-content: space-between"), "{css}");
858        assert!(css.contains("font-variant-numeric: tabular-nums"), "{css}");
859        assert!(css.contains("text-decoration: none"), "{css}");
860    }
861
862    #[test]
863    fn a_value_drawn_as_a_link_is_held_in_while_it_is_in_force() {
864        let css = facet_rules(&Emit::default());
865        for control in ["facet-take", "facet-prune"] {
866            assert!(
867                css.contains(&format!(r#".{control}[aria-current="true"]"#)),
868                "{control} drawn as an anchor must read pressed in force: {css}"
869            );
870            assert!(css.contains(&format!(r#".{control}[aria-pressed="true"]"#)));
871        }
872    }
873
874    #[test]
875    fn a_value_under_a_prune_is_named_and_reads_back_like_one() {
876        let values = [FacetValue::new("music/drums/808", "808")
877            .standing(Standing::PrunedAbove)
878            .at(Nesting::at(2), false)];
879        let html = facet_html(
880            &Facet::new("Tag", Selecting::Subtree, &values),
881            &Emit::default(),
882        );
883        assert!(html.contains(r#"data-standing="pruned-above""#), "{html}");
884        // Not a decision: its own prune control is not pressed.
885        assert!(
886            !html
887                .contains(r#"facet-prune" data-facet-value="music/drums/808" aria-pressed="true""#)
888        );
889
890        let css = facet_rules(&Emit::default());
891        assert!(
892            css.contains(r#"[data-standing="pruned-above"]"#),
893            "the sheet reads a value under a prune back a step: {css}"
894        );
895    }
896
897    #[test]
898    fn a_mode_that_lists_nothing_still_renders_its_panel() {
899        // The app puts its own box in; the panel is what gives it the group
900        // label and the shared geometry.
901        let html = facet_html(
902            &Facet::new("Search", Selecting::Text, &[]),
903            &Emit::default(),
904        );
905        assert!(html.contains("facet-name"));
906        assert!(html.contains(r#"data-selecting="text""#));
907        assert!(!html.contains("facet-take"));
908    }
909
910    #[test]
911    fn a_value_counted_at_zero_answers_no_press_and_takes_the_disabled_ink() {
912        let values = [
913            FacetValue::of("Live").counted(0),
914            FacetValue::of("Audio").counted(12),
915            FacetValue::of("Video"),
916            FacetValue::of("Text").counted(0).standing(Standing::Taken),
917        ];
918        let html = facet_html(
919            &Facet::new("Medium", Selecting::Subtree, &values),
920            &Emit::default(),
921        );
922        let line = |label: &str| {
923            let at = html.find(&format!(">{label}<")).expect(label);
924            let start = html[..at].rfind("<li").expect("li");
925            let end = at + html[at..].find("</li>").expect("/li");
926            html[start..end].to_owned()
927        };
928        let live = line("Live");
929        assert!(
930            live.contains(r#"<span class="facet-take" aria-disabled="true""#),
931            "{live}"
932        );
933        assert!(!live.contains("<button"), "{live}");
934        assert!(!live.contains("facet-prune"), "{live}");
935        assert!(
936            live.contains(r#"<span class="facet-count">0</span>"#),
937            "{live}"
938        );
939        for label in ["Audio", "Video", "Text"] {
940            let other = line(label);
941            assert!(other.contains("<button"), "{other}");
942            assert!(!other.contains("aria-disabled"), "{other}");
943        }
944
945        let css = facet_rules(&Emit::default());
946        assert!(css.contains("color: var(--content-disabled)"), "{css}");
947        assert!(
948            css.contains(r#".facet[data-selecting="subtree"] .facet-take[aria-disabled="true"]"#),
949            "{css}"
950        );
951    }
952
953    #[test]
954    fn an_unmeasured_count_emits_no_number_at_all() {
955        // A written zero reads as "none of them", which is a different claim
956        // from "not counted".
957        let values = [FacetValue::of("Ambient")];
958        let html = facet_html(
959            &Facet::new("Tag", Selecting::AnyOf, &values),
960            &Emit::default(),
961        );
962        assert!(!html.contains("facet-count"));
963
964        let counted = [FacetValue::of("Ambient").counted(0)];
965        let html = facet_html(
966            &Facet::new("Tag", Selecting::AnyOf, &counted),
967            &Emit::default(),
968        );
969        assert!(html.contains(">0</span>"));
970    }
971
972    #[test]
973    fn the_gutter_is_reserved_from_the_deepest_value_before_anything_is_drawn() {
974        // "First paint is final paint" applied to a tree: a gutter widened as
975        // deeper values arrive is the reflow that rule forbids.
976        let values = tag_values();
977        let html = facet_html(
978            &Facet::new("Tag", Selecting::Subtree, &values),
979            &Emit::default(),
980        );
981        assert!(html.contains("--facet-reach: 1"));
982        assert!(html.contains("--facet-depth: 0"));
983        assert!(html.contains("--facet-depth: 1"));
984    }
985
986    #[test]
987    fn labels_and_identifiers_are_escaped_like_every_other_string() {
988        // Both arrive from the app, and a tag path is user-supplied on a system
989        // where a user names their own tags.
990        let values = [FacetValue::new("a&b", "A & B")];
991        let html = facet_html(
992            &Facet::new("T<ag>", Selecting::AnyOf, &values),
993            &Emit::default(),
994        );
995        assert!(html.contains("A &amp; B"));
996        assert!(html.contains(r#"data-facet-value="a&amp;b""#));
997        assert!(html.contains("T&lt;ag&gt;"));
998        assert!(!html.contains("<ag>"));
999    }
1000
1001    #[test]
1002    fn a_value_reads_flat_before_it_is_touched() {
1003        // The reason the arm exists: `Depth::Flat` declares nothing, so an app
1004        // handing makeover the cascade with `revert-layer` rolled the handoff
1005        // past an empty layer onto its own bare `button` rule and the value
1006        // came out raised. Both controls say flat out loud now, and the states
1007        // below it are what a press is allowed to change.
1008        let css = facet_rules(&Emit::default());
1009        for name in ["facet-take", "facet-prune"] {
1010            assert!(
1011                css.contains(&format!(
1012                    ".{name} {{\n    background: none;\n    border: none;\n    box-shadow: none;\n}}"
1013                )),
1014                "{name} is not withdrawn: {css}"
1015            );
1016        }
1017    }
1018
1019    #[test]
1020    fn every_class_this_module_emits_is_one_the_stylesheet_rules() {
1021        // `ROW_PART_CLASSES`' obligation: a class this crate writes and the
1022        // sheet does not rule is invisible to the dead-vocabulary seal.
1023        let names = crate::vocabulary::names(&Emit::default());
1024        for name in FACET_CLASSES {
1025            assert!(
1026                names.contains(&crate::class(name, &Emit::default())),
1027                "{name} is not in the vocabulary"
1028            );
1029        }
1030    }
1031
1032    #[test]
1033    fn the_prefix_reaches_every_class_in_the_markup() {
1034        // A prefixed build claims its own names, and the emitted CSS selects
1035        // descendants: miss one and the rule stops matching.
1036        let opts = Emit {
1037            class_prefix: "mo-",
1038            ..Emit::default()
1039        };
1040        let values = tag_values();
1041        let mut html = facet_html(&Facet::new("Tag", Selecting::Subtree, &values), &opts);
1042        let groups = group_values();
1043        html.push_str(&facet_html(
1044            &Facet::new("Tags", Selecting::Subtree, &groups),
1045            &opts,
1046        ));
1047        for name in FACET_CLASSES {
1048            assert!(html.contains(&format!("mo-{name}")), "{name} is unprefixed");
1049        }
1050    }
1051
1052    /// A ranked tree: an open group with a pick under it, a closed group
1053    /// marked as where to start, a dead one, and a link row.
1054    fn group_values() -> [FacetValue<'static>; 5] {
1055        [
1056            FacetValue::new("genre", "Genre")
1057                .heading()
1058                .at(Nesting::at(0), true)
1059                .opened(true)
1060                .joined(Join::All)
1061                .ranked(GroupRank::in_use()),
1062            FacetValue::new("genre.ambient", "Ambient")
1063                .standing(Standing::Taken)
1064                .counted(12)
1065                .at(Nesting::at(1), false),
1066            FacetValue::new("genre.drone", "Drone")
1067                .counted(3)
1068                .gained()
1069                .at(Nesting::at(1), false),
1070            FacetValue::new("mood", "Mood")
1071                .heading()
1072                .at(Nesting::at(0), true)
1073                .opened(false)
1074                .joined(Join::Any)
1075                .ranked(GroupRank::cutting(70).starting()),
1076            FacetValue::new("more", "More groups (2)").heading(),
1077        ]
1078    }
1079
1080    #[test]
1081    fn a_group_opens_rather_than_picks_and_says_how_its_picks_combine() {
1082        let groups = group_values();
1083        let html = facet_html(
1084            &Facet::new("Tags", Selecting::Subtree, &groups),
1085            &Emit::default(),
1086        );
1087        // The heading is no toggle: it opens, and offers no exclude.
1088        let genre = html.split("<li").nth(1).unwrap();
1089        assert!(genre.contains(r#"data-kind="heading""#), "{genre}");
1090        assert!(genre.contains(r#"aria-expanded="true""#), "{genre}");
1091        assert!(!genre.contains("aria-pressed=\"false\">Genre"), "{genre}");
1092        assert!(!genre.contains("facet-prune"), "{genre}");
1093        assert!(genre.contains("in use"), "{genre}");
1094        // Open, so its join toggle shows with all pressed.
1095        assert!(
1096            genre.contains(r#"data-facet-join="all" aria-pressed="true""#),
1097            "{genre}"
1098        );
1099        // A gain carries its sign.
1100        assert!(html.contains(">+3</span>"), "{html}");
1101        // A closed group keeps its join out of sight, and shows its bar.
1102        let mood = html.split("<li").nth(4).unwrap();
1103        assert!(!mood.contains("facet-join"), "{mood}");
1104        assert!(mood.contains("start here"), "{mood}");
1105        assert!(mood.contains("--facet-cut: 70%"), "{mood}");
1106        // A link row neither toggles nor branches.
1107        let more = html.split("<li").nth(5).unwrap();
1108        assert!(more.contains(r#"data-kind="link""#), "{more}");
1109        assert!(
1110            !more.contains("aria-pressed") && !more.contains("aria-expanded"),
1111            "{more}"
1112        );
1113    }
1114}