makeover_webview/lib.rs
1//! The webview renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-webview -->
4//!
5//! # The renderer that needs no palette
6//!
7//! `makeover-immediate` and `makeover-tui` both take a `Palette`, because egui
8//! and a terminal need an actual colour before they can put anything on
9//! screen. A webview does not: `var(--surface-raised)` *is* the late binding,
10//! and the browser resolves it against whatever `themes.js` last wrote onto
11//! `:root`.
12//!
13//! So this crate emits text naming intents, and never learns a colour. It is
14//! the deferral rule with no adapter in the way, and it is why the webview was
15//! always the wrong renderer to derive a vocabulary from: it can express
16//! anything, so it never pushes back.
17//!
18//! # Phase A: the stylesheet
19//!
20//! The stylesheet half needs no markup of the app's to change: an app that
21//! writes its own markup keeps every line of it and gains the classes, which is
22//! why adopting the generated stylesheet is not a migration.
23//!
24//! Adoption is not a deletion either. A rule loses its depth declarations and
25//! gains a variant selector next to it, so an app's file stays about the same
26//! size. What moves is where depth is defined, not how much CSS exists.
27//!
28//! The bevel properties are byte-identical to what both apps already
29//! hand-write, which is asserted below.
30//!
31//! Some of what phase A emits is not a look but the withdrawal of one. A
32//! renderer that picks its element from the description inherits that element's
33//! user-agent chrome, and [`reset`] is where a primitive says which parts of it
34//! were never asked for.
35//!
36//! # Phase B: the markup's names, and the hosts' markup
37//!
38//! The vocabulary's members (fields, choices, columns, figures, meters, charts,
39//! acts and the rest) are drawn by the quasi hosts: `quasi-webview` for this
40//! renderer. What phase B keeps here is everything those hosts and the
41//! hand-written apps have to agree with this crate about:
42//!
43//! - [`form`]: the one escaper, [`form::Markup`] and [`form::Filling`], the
44//! field classes and the rules behind them. One function covers element text
45//! and attribute values, where the apps needed four and had to choose
46//! correctly at every call site.
47//! - [`list`]: column names as classes, the kind, part and flow classes, the
48//! cell wrapper and sizer, and the `short-N` and `stacks-N` ladders a table
49//! narrows and stacks by.
50//! - [`chart`], [`figure`], [`meter`]: class lists and rules only.
51//! - [`facet`] renders `makeover_layout::Facet` itself: a dimension a set is
52//! narrowed by, and the one phase-B emitter whose markup an app is not
53//! keeping, because the markup it replaces was two mechanisms rather than
54//! one. A tag's selection and a tag's browse position were separate state on
55//! MNW's discover page, which is why every filter row there carries a tick
56//! box *and* a chevron; one gesture doing both is what lets the second one go.
57//! - [`placeholder`] draws the stand-in a region shows while it has nothing.
58//!
59//! Every class a host's markup can carry is in one of the modules' class lists,
60//! and [`vocabulary::names`] is their union with the generated sheet.
61//!
62//! # What phase A settled, and what it costs
63//!
64//! Measured against goingson's `styles.css` rather than against a component
65//! list: `.btn`, `.card` and `.tag, .badge` each hand-write the same
66//! composition, so three quarters of phase A is one rule with several names.
67//!
68//! Two of the four decisions change how goingson looks, and adoption should
69//! not be described as a pure deletion:
70//!
71//! - **Pressed carries its fill.** [`interactive_rules`] emits
72//! [`Depth::pressed`] whole. goingson presses to `--surface-sunken` today and
73//! will press to `--surface-well`, and hovers to `--surface-overlay` today
74//! and will hover to `--hover-surface`. Since `surface-well` inverts by theme
75//! where `surface-sunken` does not, a dark theme presses *lighter* than it
76//! hovers. That falls out of `makeover`'s own derivation, which says outright
77//! that `surface-sunken` cannot serve as a well, so if it reads wrong the
78//! answer is there and not here.
79//! - **Badges go flat.** See `token_rules`.
80//!
81//! The other two: the progress trough is renderer-local and the scrollbar
82//! track was dropped ([`component_rules`]), and no class prefix ships by
83//! default, so adoption means deleting the app's hand-written rule in the same
84//! commit that adds the generated one. `.card`, `.badge` and the tab classes
85//! all already exist in goingson, and while both rules exist the cascade order
86//! decides which wins. That is the one real risk in adopting this, and it is
87//! why the migration lands per component rather than in one commit.
88//!
89//! # Interaction states
90//!
91//! [`interactive_rules`] emits four states, in emission order, and the order is
92//! load-bearing: they are all specificity (0,2,0), so disabled beats hover by
93//! coming last and by nothing else. Nothing here reaches for `:not(:disabled)`,
94//! which would raise a selector this crate wraps in its own layer.
95//!
96//! Emitting the states here is what keeps an app from completing the primitive
97//! from outside, by out-specifying a rule it does not own. Those overrides are
98//! also what breaks under cascade layers: an app that declares `@layer` puts
99//! its own rules in a named layer, and unlayered declarations outrank every
100//! named layer regardless of specificity.
101//!
102//! Hover sits inside a capability query. `makeover-layout`'s `Affordance`
103//! answers whether a fingertip has hover and `makeover-geometry` spells the condition; this crate
104//! asks and does not decide, so no app has to take the hover state back on
105//! touch.
106//!
107//! # The layer contract
108//!
109//! [`stylesheet`] emits into the `makeover` cascade layer ([`CSS_LAYER`], which
110//! lives in `makeover-geometry` because that is the one crate every CSS emitter
111//! in the family already depends on). `makeover-geometry` does the same for
112//! `geometry.css`.
113//!
114//! The cascade resolves origin and importance, then layer, then specificity,
115//! then source order, and **unlayered normal declarations outrank every named
116//! layer**. An unlayered generated file therefore beats every rule an app owns,
117//! regardless of specificity and regardless of loading last. Nothing errors when
118//! that happens: the CSS is valid, the minifier is happy, and buttons and badges
119//! look subtly wrong. The layer belongs here rather than in each app, because an
120//! app cannot fix it from its own stylesheet: the fix is to layer the file it
121//! does not own.
122//!
123//! An app should declare the order once, or the layer's position is decided by
124//! whichever generated file the browser happens to see first:
125//!
126//! ```css
127//! @layer makeover, base, components, responsive;
128//! ```
129//!
130//! [`in_css_layer`] is re-exported for an app that assembles its own stylesheet
131//! from this crate's pieces: rules an app generates from them are as generated
132//! as the ones here, so they belong in the same layer and this crate cannot put
133//! them there on the app's behalf.
134//!
135//! # Form rules
136//!
137//! The field markup is the hosts', and the look is this crate's, because a
138//! renderer inventing how a label or an error reads is the drift the
139//! vocabulary check exists to catch. A few rules spend a mark the markup
140//! carries rather than a class:
141//!
142//! - A markdown field is marked `data-format="markdown"`, and
143//! `form::editor_rules` spends that mark. The Write/Preview pair is a
144//! segmented control, so it takes the depth, the focus ring and the chosen
145//! state from rules that already exist; the preview pane is a well, because
146//! it stands where the control stood. Both are gated on the attribute rather
147//! than on a class, which is what the attribute is for. **This crate renders
148//! no markdown**: the pane is filled by whatever binds the editor, which is
149//! where the host's sanitiser already is.
150//! - A suggestion's second line, `.form-suggestion-detail`, is drawn in
151//! `--content-muted` rather than in the disabled token. A detail orients
152//! rather than refuses, and every other secondary line in this crate reads
153//! the same way, `.form-option-detail` and `.form-unit` included.
154//! - An unavailable option's reason is `.form-option-reason`, and a group with
155//! an error carries `has-error` while its message carries `visible`
156//! ([`form::FIELD_STATE_CLASSES`]).
157//!
158//! # A cell says what it holds
159//!
160//! [`CellPart`] names the four things a cell holds,
161//! and `table_rules` turns them into `.cell-value`, `.cell-tokens`,
162//! `.cell-actions` and `.cell-link`. The value and the link take a colour: a
163//! token carries its own tone and an action is a control rather than text.
164//!
165//! The colour goes on `.cell-value` rather than on `.cell`. On the container it
166//! cascades into the parts that are not text, and a control in a cell is painted
167//! as text, which is the drift
168//! [`RowPart::intent`](makeover_layout::RowPart) prevents for list rows.
169//!
170//! A cell's part is a [`CellPart`] and never a [`RowPart`]: the two answer
171//! different questions, and only one of them is about a cell.
172//!
173//! # A table narrows itself
174//!
175//! A table a description produced knows its columns at render time, so no rule
176//! can be written per table: it would have to travel with the markup, as a
177//! `<style>` element that needs `style-src 'unsafe-inline'` or in a head an htmx
178//! fragment swap does not carry. `table_rules` lays every table out as flex
179//! rows instead, each column starting at its declared floor and giving up room
180//! by its [`Priority`](makeover_layout::Priority), so the browser narrows a
181//! table at the width its floors add up to. A host puts the column's classes
182//! on every cell (its name through [`list::push_column_name`], its width and
183//! drop tiers from [`list::CELL_WIDTH_CLASSES`] and [`list::CELL_DROP_CLASSES`],
184//! its kind from [`list::kind_class`]), and every cell's contents go in
185//! [`list::CELL_IN`]. **A header row emitted by a renderer's own code has to do
186//! both too**, or the header and the body disagree about which column just
187//! closed and how wide the rest are.
188//!
189//! `.button` takes the four tones as colour, off `data-tone`, the way the badge
190//! does, so a destructive button has somewhere for its tone to land. A list is
191//! reset rather than left as a bulleted list.
192//!
193//! `RowPart::revealed_on_hover` is not honoured. Hiding a row's actions until
194//! hover hides them from pointer users alone, who are the ones scanning a list
195//! to learn what can be done to a row, and every escape the rule grows
196//! (`focus-within` for the keyboard, a capability gate for a fingertip) is a
197//! report that hiding was wrong for somebody.
198//!
199//! # The depth classes are not controls
200//!
201//! `.raised` is a statement about shape and carries no interactive set, so the
202//! vocabulary has a raised surface that is merely an object. An app that wants
203//! one does not have to take a control class and cancel the control half.
204//!
205//! `.button` is the same depth *and* a control, and takes its states from
206//! `surface_rules`, which is where a state belongs: on the thing that claims
207//! to answer a pointer. `.card` is a raised object, and it answers a pointer
208//! only when the element it is written on is a control, `a`, `button`,
209//! `label`, or anything carrying `data-act`, so one name serves the card
210//! that is read and the card that is pressed.
211//!
212//! # Substitution, three ways
213//!
214//! A theme with no `surface-well` is answered differently by each renderer,
215//! which is why substitution belongs to a renderer and not to the description:
216//!
217//! - `makeover-immediate` substitutes the page in Rust.
218//! - `makeover-tui` refuses to substitute and draws an edge instead, because a
219//! terminal would quantise the two together.
220//! - here, CSS already has the mechanism: `var(--surface-well,
221//! var(--surface-page))` falls back in the browser, and nothing in Rust
222//! decides anything.
223
224#![forbid(unsafe_code)]
225
226#[cfg(feature = "build")]
227pub mod build;
228pub mod chart;
229mod css_lex;
230pub mod facet;
231pub mod figure;
232pub mod form;
233pub mod list;
234pub mod meter;
235pub mod placeholder;
236pub mod reset;
237pub mod vocabulary;
238
239mod table;
240use table::table_rules;
241
242use crate::list::{cell_part_class, part_class};
243use crate::reset::{Chrome, Reset};
244use makeover_geometry::{Density, SizeClass};
245// Re-exported rather than redefined. An app assembling its own stylesheet out
246// of this crate's pieces needs the same layer name, and most such apps depend
247// on this crate and not on `makeover-geometry` directly.
248pub use makeover_geometry::{CSS_LAYER, in_css_layer};
249
250/// This crate's version, as the generated stylesheet reports it.
251///
252/// A consumer whose lockfile still pins an old `makeover-webview` gets a
253/// well-formed sheet with components missing and no error anywhere, so the
254/// emitter has to name itself in what it writes. Read by
255/// `build::layout_css` through [`stylesheet`].
256pub const VERSION: &str = env!("CARGO_PKG_VERSION");
257use makeover_layout::{
258 Affordance, Bevel, CellPart, Depth, Fallback, Fill, Flow, Intent, RowPart, Selector, Sort,
259 State, Token, Tone,
260};
261use std::fmt::Write as _;
262
263/// How the emitted CSS and markup are shaped, and the copy they carry.
264///
265/// Built with [`Emit::new`] and its setters. `#[non_exhaustive]`, so a new
266/// knob is not a breaking change for anyone who configures one.
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268#[non_exhaustive]
269pub struct Emit {
270 /// Bevel thickness, as a CSS length.
271 ///
272 /// A value, so it arrives from the caller: this crate names no sizes of its
273 /// own. The default is `makeover_geometry::Stroke::Hairline`, and
274 /// [`focus_width`](Self::focus_width)'s is `Stroke::Mark`; a test holds
275 /// both equal to the scale.
276 pub border_width: &'static str,
277 /// Focus ring thickness, as a CSS length.
278 ///
279 /// Separate from [`border_width`](Self::border_width), and never derived
280 /// from it: a bevel and a focus indicator answer different questions, and
281 /// only one of them has to be noticed from across a desk.
282 ///
283 /// The default, 2px, is what every consumer had chosen for its own ring.
284 pub focus_width: &'static str,
285 /// The smallest a pointer target may be drawn, as a CSS length.
286 ///
287 /// A value for [`border_width`](Self::border_width)'s reason: a floor is a
288 /// size, and this crate names no sizes of its own.
289 ///
290 /// The default is WCAG 2.2's target minimum. It is an absolute rather than
291 /// a step off the geometry base, and that is deliberate on two counts: a
292 /// floor that scales with the reader's root size is not a floor, and the
293 /// touch density opens the gaps *between* targets rather than licensing a
294 /// smaller one for a pointer.
295 pub target_min: &'static str,
296 /// Prefix for emitted class names, without the leading dot.
297 pub class_prefix: &'static str,
298 /// What marks a compulsory field, appended to its label.
299 ///
300 /// `makeover-tui`'s `PieceStyle::required_marker` and
301 /// `makeover-immediate`'s `FieldStyle::required_marker`, said here for the
302 /// third renderer, with their default. A knob for their reason: it is the
303 /// one piece of *copy* this crate emits, and copy is not a renderer's
304 /// call.
305
306 ///
307 /// # Why it is hidden from the accessibility tree here and nowhere else
308 ///
309 /// The control already carries `required`, which a screen reader
310 /// announces. A marker read out beside it is the same fact twice, so the
311 /// span is `aria-hidden`. The other two renderers have no such attribute
312 /// to lean on, which is why the marker is part of the label string there
313 /// and an element here.
314 pub required_marker: &'static str,
315 /// The accessible name's lead on a facet value's exclude button, before
316 /// the value's own label: "Exclude Drums". Copy, for
317 /// [`required_marker`](Self::required_marker)'s reason.
318 pub exclude_label: &'static str,
319 /// The markdown editor's two modes, as the segments say them.
320 pub write_label: &'static str,
321 /// See [`write_label`](Self::write_label).
322 pub preview_label: &'static str,
323 /// The accessible names of an interval's two boxes.
324 pub lower_label: &'static str,
325 /// See [`lower_label`](Self::lower_label).
326 pub upper_label: &'static str,
327 /// The words a facet group's join toggle offers: picks under it combine
328 /// when any of them holds, or only when all do.
329 pub any_label: &'static str,
330 /// See [`any_label`](Self::any_label).
331 pub all_label: &'static str,
332 /// The accessible name's lead on a join toggle, before the group's label:
333 /// "Combine picks under Genre".
334 pub join_label: &'static str,
335 /// What marks the group a newcomer should start with.
336 pub start_label: &'static str,
337 /// What a ranked group says when a pick inside it is already in force.
338 pub in_use_label: &'static str,
339 /// What a ranked group says when no pick inside it would leave anything.
340 pub dead_label: &'static str,
341}
342
343impl Emit {
344 /// The defaults: the measured widths above, no prefix, and English copy.
345 #[must_use]
346 pub const fn new() -> Self {
347 Self {
348 border_width: "1px",
349 focus_width: "2px",
350 target_min: "24px",
351 class_prefix: "",
352 required_marker: "*",
353 exclude_label: "Exclude",
354 write_label: "Write",
355 preview_label: "Preview",
356 lower_label: "lower",
357 upper_label: "upper",
358 any_label: "any",
359 all_label: "all",
360 join_label: "Combine picks under",
361 start_label: "start here",
362 in_use_label: "in use",
363 dead_label: "no effect",
364 }
365 }
366}
367
368/// One setter per field, named after it, for building an [`Emit`] outside this
369/// crate: `Emit::new().class_prefix("mk-")`.
370macro_rules! setters {
371 ($($field:ident),* $(,)?) => {
372 impl Emit {
373 $(
374 #[doc = concat!("Set [`", stringify!($field), "`](Self::", stringify!($field), ").")]
375 #[must_use]
376 pub const fn $field(mut self, value: &'static str) -> Self {
377 self.$field = value;
378 self
379 }
380 )*
381 }
382 };
383}
384
385setters!(
386 border_width,
387 focus_width,
388 target_min,
389 class_prefix,
390 required_marker,
391 exclude_label,
392 write_label,
393 preview_label,
394 lower_label,
395 upper_label,
396 any_label,
397 all_label,
398 join_label,
399 start_label,
400 in_use_label,
401 dead_label,
402);
403
404impl Default for Emit {
405 fn default() -> Self {
406 Self::new()
407 }
408}
409
410/// A string as CSS escapes, for a `content` value.
411///
412/// `\u{25B2}` becomes `\25B2`. Emitted escaped rather than literally so the
413/// stylesheet is ASCII whatever the description spells: a `content` string is
414/// read by whatever encoding the consumer serves the file as, and a caret that
415/// depends on that is a caret that works on one machine.
416///
417/// Terminated by the closing quote at every site here. A CSS hex escape takes
418/// up to six digits and ends at the first character that cannot be one, so an
419/// escape followed by more text would need a space that these do not.
420fn css_escape(text: &str) -> String {
421 text.chars().fold(String::new(), |mut out, c| {
422 let _ = write!(out, "\\{:X}", c as u32);
423 out
424 })
425}
426
427/// The CSS custom property holding a bevel's composition.
428#[must_use]
429pub fn bevel_var(bevel: Bevel) -> &'static str {
430 match bevel {
431 Bevel::Raised => "--bevel-raised",
432 Bevel::Inset => "--bevel-inset",
433 Bevel::RaisedOpen => "--bevel-raised-open",
434 // An edge added to the description since this renderer was last
435 // built. The raised edge rather than no edge: a control with no
436 // box-shadow reads as flat, which is a different claim, where a
437 // closed edge is at worst the same shape drawn one run too many.
438 _ => "--bevel-raised",
439 }
440}
441
442/// A `var()` reference to a fill intent, with the browser's own fallback where
443/// the intent may be absent.
444///
445/// The fallback is CSS syntax, not a decision made here. That is the whole
446/// difference between this renderer and the other two.
447#[must_use]
448pub fn fill_var(fill: Fill) -> String {
449 match fill {
450 Fill::Well => format!("var(--{}, var(--{}))", fill.token(), Fill::Page.token()),
451 other => format!("var(--{})", other.token()),
452 }
453}
454
455/// The two-tone edge as a `box-shadow` value.
456///
457/// Two inset shadows, one per corner pair: the light one offset down and
458/// right so it lands on the top and left edges, the dark one the other way.
459/// The same assignment `makeover-immediate` draws with polylines and
460/// `makeover-tui` draws with box-drawing characters.
461#[must_use]
462pub fn bevel_shadow(bevel: Bevel, opts: &Emit) -> String {
463 let (top_left, bottom_right) = bevel.edges();
464 let w = opts.border_width;
465 // The shaded run's vertical offset is what puts it on the bottom edge. At
466 // zero it lands on the right edge alone, which is the open bevel: three
467 // sides drawn and the fourth left for the surface below to continue
468 // through. Same two shadows either way, so nothing downstream has to know
469 // which it got.
470 // The sign belongs to the value rather than to the template: writing
471 // `-{down}` against a zero emits `-0`, which is a length no stylesheet
472 // should carry even where a parser accepts it.
473 let down = if bevel.draws_bottom() {
474 format!("-{w}")
475 } else {
476 "0".to_string()
477 };
478 format!(
479 "inset {w} {w} 0 var(--{}), inset -{w} {down} 0 var(--{})",
480 top_left.token(),
481 bottom_right.token()
482 )
483}
484
485/// The custom properties both bevels resolve through.
486///
487/// Emitted as properties rather than inlined into every rule because that is
488/// what the apps already do, and because a consumer that wants the edge
489/// without the fill reads the property directly.
490#[must_use]
491pub fn bevel_properties(opts: &Emit) -> String {
492 let mut css = String::new();
493 for bevel in [Bevel::Raised, Bevel::Inset, Bevel::RaisedOpen] {
494 let _ = writeln!(
495 css,
496 " {}: {};",
497 bevel_var(bevel),
498 bevel_shadow(bevel, opts)
499 );
500 }
501 let _ = writeln!(css, " {OPEN_SIDE_VAR}: {};", open_side_shadow(opts));
502 css.push_str(ELEVATION_PROPERTY);
503 // The edge a surface draws when its depth alone does not separate it: a
504 // field, a button, a card, a toast. One shorthand, so no rule spells out
505 // its own `1px solid`.
506 let _ = writeln!(
507 css,
508 " --edge-control: {} solid var(--border);",
509 opts.border_width
510 );
511 css
512}
513
514/// The property holding [`Bevel::RaisedOpen`] turned a quarter.
515///
516/// Which run of an open bevel is left off is the arrangement's, not the edge's:
517/// the run facing the surface the tab opens into. A strip across its pane
518/// opens downward, which is the composition under [`bevel_var`]; a strip
519/// running down beside its pane opens toward the inline end, and this is that.
520/// Not a member of [`Bevel`], for the reason [`Selector`] carries no direction:
521/// the description says what joins, and the renderer drawing the arrangement
522/// says which side.
523const OPEN_SIDE_VAR: &str = "--bevel-raised-open-side";
524
525/// [`bevel_shadow`] for a tab that joins its pane on the inline-end side.
526///
527/// The lit run stays on top and left, and the shaded run drops its horizontal
528/// offset instead of its vertical one, so it lands on the bottom alone and the
529/// right run is not drawn. Physical rather than logical sides, as every bevel
530/// here is: `box-shadow` has no logical form.
531fn open_side_shadow(opts: &Emit) -> String {
532 let (top_left, bottom_right) = Bevel::RaisedOpen.edges();
533 let w = opts.border_width;
534 format!(
535 "inset {w} {w} 0 var(--{}), inset 0 -{w} 0 var(--{})",
536 top_left.token(),
537 bottom_right.token()
538 )
539}
540
541/// The cast shadow of a surface that floats over the page.
542///
543/// Composed here for the reason the bevel pair is: `makeover` derives the tone,
544/// this crate owns the geometry, and neither has to know the other's numbers.
545///
546/// **Only for a surface that overlays the page.** A menu, a toast, a popover, a
547/// dropdown. A surface *in* the page takes `.raised` and its bevel, and a rule
548/// that reaches for this on a card or a plate has renamed a literal rather than
549/// replaced it.
550///
551/// Two lengths rather than one, because a single blur reads as a smudge at
552/// plate size and as a halo at menu size. The offset is small and downward: a
553/// Platinum-era menu sits just off the page rather than hovering above it.
554const ELEVATION_PROPERTY: &str =
555 " --elevation-overlay: 0 2px 4px var(--elevation), 0 8px 24px var(--elevation);\n";
556
557/// The class name for a depth.
558#[must_use]
559pub fn depth_class(depth: Depth, opts: &Emit) -> Option<String> {
560 let name = match depth {
561 Depth::Flat => return None,
562 Depth::Raised => "raised",
563 Depth::Well => "well",
564 Depth::Sunken => "sunken",
565 // A depth added to the description since this renderer was last
566 // built. No class, on the same footing as Flat: emitting a name
567 // whose rule body we cannot write would put a class in the markup
568 // that the stylesheet never defines.
569 _ => return None,
570 };
571 Some(format!("{}{name}", opts.class_prefix))
572}
573
574/// A prefixed class name.
575///
576/// Public, for the renderers that emit markup this crate does not. A screen
577/// renderer writing `class="row"` has to prefix it the way the stylesheet half
578/// does, or a prefixed app gets rules matching everything except the elements
579/// that renderer wrote, and the failure is invisible: the CSS stays valid and
580/// one element is unstyled. Call this rather than copying it.
581#[must_use]
582pub fn class(name: &str, opts: &Emit) -> String {
583 let mut out = String::with_capacity(opts.class_prefix.len() + name.len());
584 push_class(&mut out, name, opts);
585 out
586}
587
588/// A prefixed class name, written into a buffer the caller already has.
589///
590/// The form the emitters use, and the reason it exists is [`escape_into`]'s:
591/// putting every class on every element through a `format!` allocates even in
592/// the default case, where the prefix is empty and the answer is the argument.
593/// A described table row carries roughly eighty transient allocations that way,
594/// and this and the escaper are most of them.
595///
596/// [`class`] stays for callers holding a name rather than a buffer.
597///
598/// [`escape_into`]: crate::form::escape_into
599pub fn push_class(out: &mut String, name: &str, opts: &Emit) {
600 out.push_str(opts.class_prefix);
601 out.push_str(name);
602}
603
604/// The attribute an element's custom properties ride in, instead of `style`.
605///
606/// A number this crate hands the stylesheet, a bar's value and its axis, a
607/// facet's depth, a meter's fill, is a custom property the rules divide or
608/// multiply. A `style-src` without `'unsafe-inline'` refuses every style
609/// attribute, so a page under that policy would draw every chart flat from
610/// `style="--value: 4210"`. The same text in this
611/// attribute is data a policy does not police, and the host's script sets each
612/// property through the CSSOM, which the policy allows: [`VARS_JS`].
613///
614/// The value is `--name: value` pairs separated by `;`, the declaration syntax
615/// the `style` attribute already had, so the numbers still reach the markup as
616/// themselves. That is the property the residual seam needs: see the
617/// [`chart`] module header.
618///
619/// Only custom properties. A script that applied any declaration from markup
620/// would hand the policy's refusal straight back.
621pub const VARS_ATTR: &str = "data-vars";
622
623/// The script that applies [`VARS_ATTR`], for a host to serve beside its other
624/// assets.
625///
626/// Without it every number the rules read from that attribute is missing: bars
627/// and charts flat, tree rows unindented, a split screen at even halves.
628///
629/// It also restores this device's density choice onto the root element
630/// ([`DENSITY_STORE_KEY`] into
631/// [`DENSITY_ATTRIBUTE`](makeover_geometry::DENSITY_ATTRIBUTE)) and answers a
632/// [`DENSITY_CHOICE_ATTR`] picker, for the same reason it is not deferred: a
633/// choice applied after first paint is a page that jumps. Serve
634/// it as a classic script in the head, not deferred, so its observer is
635/// running before the parser reaches the body and the first paint already has
636/// every property.
637///
638/// ```no_run
639/// # fn main() -> std::io::Result<()> {
640/// std::fs::write("static/vars.js", makeover_webview::VARS_JS)?;
641/// # Ok(())
642/// # }
643/// ```
644pub const VARS_JS: &str = include_str!("vars.js");
645
646/// The attribute a [`FieldKind::Density`](makeover_layout::FieldKind::Density)
647/// picker carries, which is how [`VARS_JS`] finds it.
648///
649/// The picker is a `<select>` with this attribute and **no `name`**, so no
650/// form or htmx request ever submits it: the device holds the answer, and the
651/// script reads and writes it there.
652pub const DENSITY_CHOICE_ATTR: &str = "data-density-choice";
653
654/// The browser storage key a device's density choice is kept under.
655///
656/// The value is [`Density::attribute_value`](makeover_geometry::Density::attribute_value),
657/// and an absent key is "follow detection". Per origin, which is per device
658/// for a hosted app and per app for a desktop one: both are what the choice
659/// is about.
660pub const DENSITY_STORE_KEY: &str = "makeover-density";
661
662/// Write the options of a density picker, in
663/// [`DENSITY_CHOICES`](makeover_layout::DENSITY_CHOICES) order.
664///
665/// None is marked selected. The server cannot know what this device chose,
666/// so [`VARS_JS`] sets the picker's value from storage as it arrives, which
667/// is before first paint on a page load and on insertion after a swap.
668///
669/// ```
670/// let mut out = String::new();
671/// makeover_webview::density_options_into(&mut out);
672/// assert!(out.starts_with("<option value=\"\">Automatic</option>"));
673/// assert!(out.contains("<option value=\"touch\">Touch</option>"));
674/// ```
675pub fn density_options_into(out: &mut String) {
676 for (density, label) in makeover_layout::DENSITY_CHOICES {
677 out.push_str("<option value=\"");
678 out.push_str(density.map_or("", makeover_geometry::Density::attribute_value));
679 out.push_str("\">");
680 form::escape_into(label, out);
681 out.push_str("</option>");
682 }
683}
684
685/// The class an option of a selector carries, which is what the rules key off.
686///
687/// Named for the option and not for the group: `selector_rules` styles the
688/// thing that gets picked, so `Selector::Tabs` is `tab` and not `tabs`. The
689/// distinction is not pedantry. quasi-webview spelled these `tabs`, `segmented`
690/// and `option`, put `toggle` on the wrapping element rather than on the
691/// buttons inside it, and every described selector in that renderer came out
692/// with no depth, no focus ring and no chosen state, while the toggle group got
693/// a bevel meant for its buttons.
694///
695/// The chosen option additionally carries `chosen`, the same way a latched chip
696/// carries `latched`. That name is this crate's too; there is no reason for a
697/// caller to spell it, and `selector_rules` is where it is written down.
698#[must_use]
699pub fn option_class(selector: Selector) -> &'static str {
700 match selector {
701 Selector::Tabs => "tab",
702 Selector::Segmented => "segment",
703 Selector::Toggle => "toggle",
704 // A selector this crate has not learned draws as tabs, the plainest
705 // of the three, rather than as nothing.
706 _ => "tab",
707 }
708}
709
710/// The fill and edge declarations for a depth, as a rule body.
711///
712/// Empty for [`Depth::Flat`], which has neither and inherits what it sits on.
713/// Callers lean on the emptiness to skip the rule rather than emit a class that
714/// sets nothing: a class that sets no properties is a class that means "I
715/// thought about this", which is what comments are for.
716///
717/// The two halves are emitted independently because [`Depth::Sunken`] has a
718/// fill and no bevel. Requiring both would silently drop the fill for exactly
719/// that case. Independent does not
720/// mean unpaired: both halves still come off one `Depth`, so they cannot
721/// disagree about what the region is.
722#[must_use]
723pub fn depth_declarations(depth: Depth) -> String {
724 let mut css = String::new();
725 if let Some(fill) = depth.fill() {
726 let _ = writeln!(css, " background: {};", fill_var(fill));
727 }
728 if let Some(bevel) = depth.bevel() {
729 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
730 }
731 css
732}
733
734/// One rule giving a selector a depth, or nothing when the depth declares
735/// nothing.
736#[must_use]
737pub fn depth_rule(selector: &str, depth: Depth) -> String {
738 let body = depth_declarations(depth);
739 if body.is_empty() {
740 return String::new();
741 }
742 format!(".{selector} {{\n{body}}}\n")
743}
744
745/// The media condition a hover rule has to sit inside, or `None` if hover is
746/// unconditional.
747///
748/// Two crates answer this and neither answer is made here. `makeover-layout`'s
749/// [`Affordance`] owns *whether* hover exists at a density, and `makeover-geometry` owns how
750/// that capability is spelled as a media condition. Asking both is what stops
751/// this renderer minting a third opinion, which is what all three apps did:
752/// goingson sniffed the user agent, Balanced Breakfast used `(hover: none)`
753/// alone, and the MNW server had no gate at all.
754///
755/// [`SizeClass`] is required by [`Affordance::available`] and ignored by this
756/// member, which reports as much through `reads_size`. Passing Compact is not
757/// a claim about width; the test below pins that every class agrees.
758pub(crate) fn hover_condition() -> Option<&'static str> {
759 if Affordance::Hover.available(Density::Touch, SizeClass::Compact) {
760 // A fingertip grew a hover state. Nothing to gate, and this renderer
761 // should not invent a reason to gate anyway.
762 None
763 } else {
764 Some(Density::Pointer.media_condition())
765 }
766}
767
768/// The tones that carry a status, each of which a toned member draws.
769pub(crate) const STATUS_TONES: [Tone; 4] = [Tone::Info, Tone::Success, Tone::Warning, Tone::Danger];
770
771/// The disabled state, native or announced, as one selector suffix.
772pub(crate) const DISABLED: &str = ":is(:disabled, [aria-disabled=\"true\"])";
773
774/// One `{selector}[data-tone="…"]` rule per status tone, `body` writing the
775/// declarations for a tone token.
776pub(crate) fn tone_rules(css: &mut String, selector: &str, body: impl Fn(&str) -> String) {
777 for tone in STATUS_TONES {
778 let tone = tone.token();
779 let _ = writeln!(css, "{selector}[data-tone=\"{tone}\"] {{\n{}}}", body(tone));
780 }
781}
782
783/// A status drawn as an edge on the start side, the words keeping their ink.
784pub(crate) fn status_edge(width: &str, tone: &str) -> String {
785 format!(
786 " border-inline-start: {width} solid var(--{tone});\n \
787 padding-inline-start: var(--step-snug);\n"
788 )
789}
790
791/// A status drawn as a tinted ground edged in the tone.
792fn toned_surface(tone: &str) -> String {
793 format!(" background: var(--{tone}-surface);\n border-color: var(--{tone});\n")
794}
795
796/// Put a rule inside a media query, or leave it alone.
797pub(crate) fn gated(condition: Option<&str>, rule: &str) -> String {
798 let Some(condition) = condition else {
799 return rule.to_string();
800 };
801 let mut css = format!("@media {condition} {{\n");
802 for line in rule.lines() {
803 // Blank lines stay blank. Indenting one leaves trailing whitespace,
804 // which is the sort of thing a formatter later reverts and calls a diff.
805 if line.is_empty() {
806 css.push('\n');
807 } else {
808 let _ = writeln!(css, " {line}");
809 }
810 }
811 css.push_str("}\n");
812 css
813}
814
815/// The keyboard focus ring, placed by the depth it lands on.
816///
817/// This is the webview's **focus ring** and nothing more. **Reach** and
818/// **focus** are both the browser's, the document decides what is reachable
819/// and `:focus-visible` decides which reached thing wears the ring, and no
820/// description states either. The three terms are defined once in
821/// `makeover_layout`'s crate header, "Reach, focus and the focus ring".
822///
823/// One ring for the whole system, because a focus ring's job is to be
824/// recognised and three apps having three of them is the failure. What varies
825/// is where it sits, and that comes off [`Depth`] rather than off a per-
826/// component choice: a well takes the ring inside its own edge, and anything
827/// standing proud of the page takes it outside.
828///
829/// `outline` rather than the composed `box-shadow` the invalid-field ring at
830/// `field_rules` uses, and deliberately the one place the two rings are built
831/// differently. A `box-shadow` ring has to restate the bevel beside it, because
832/// `box-shadow` is not additive and a lone ring silently drops the well out
833/// from under the element. That restatement is a second copy of the depth,
834/// living in a different function from the first, and it is exactly the
835/// duplication `Depth` exists to prevent. `outline` occupies its own property,
836/// so the bevel survives untouched and there is nothing to keep in agreement.
837/// They render the same: both are a flush ring one border-width wide.
838#[must_use]
839pub fn focus_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
840 let w = opts.focus_width;
841 // Same magnitude either way, and only the sign comes off the depth. Both
842 // values are what the consumers had already converged on independently:
843 // 2px out is what all three wrote, and 2px in is the MNW server's own
844 // answer for the one inset ring it had.
845 let offset = match depth.bevel() {
846 // Inside the well, clear of its edge rather than painted over it.
847 Some(Bevel::Inset) => format!("calc(-1 * {w})"),
848 // Raised, or no edge at all. Outside, standing off by its own width.
849 _ => w.to_string(),
850 };
851 // The token by name. It is `makeover`'s, derived from the action colour,
852 // and reaching it through a description member was a second path to the
853 // same variable for as long as one existed.
854 format!(
855 ".{selector}:focus-visible {{\n outline: {w} solid var(--focus-ring);\n outline-offset: {offset};\n}}\n"
856 )
857}
858
859/// A rest depth said out loud on both axes, for a rule that has to beat the
860/// states above it.
861///
862/// [`depth_declarations`] states an axis only when the depth has something to
863/// say about it, which is right for a rest rule: a [`Depth::Flat`] region
864/// inherits what it sits on, and asserting `background: none` there would be
865/// the difference between level-with and painted-transparent. It is wrong for
866/// a rule whose whole job is to take a state back. An axis left unstated is an
867/// axis the state above keeps, so `Flat` re-asserted nothing at all and a
868/// disabled control kept whatever hover had given it.
869///
870/// So the axes the depth is silent on are withdrawn rather than skipped, and
871/// the withdrawal is spelled by [`reset`] rather than here, so a disabled
872/// control and a flat one say the same words. Reaches further than the fill:
873/// [`Depth::Sunken`] and [`Depth::Overlay`] have no bevel either, and the
874/// pressed rule above hands out an inset one.
875fn rest_declarations(depth: Depth) -> String {
876 let mut css = String::new();
877 match depth.fill() {
878 Some(fill) => {
879 let _ = writeln!(css, " background: {};", fill_var(fill));
880 }
881 None => css.push_str(&Reset::NOTHING.and(Chrome::Fill).declarations()),
882 }
883 match depth.bevel() {
884 Some(bevel) => {
885 let _ = writeln!(css, " box-shadow: var({});", bevel_var(bevel));
886 }
887 None => css.push_str(&Reset::NOTHING.and(Chrome::Shadow).declarations()),
888 }
889 css
890}
891
892/// Present, visible, and not answering.
893///
894/// Matches the ARIA attribute as well as the pseudo-class, because `:disabled`
895/// only matches form elements and half the things this crate emits are not
896/// one: a `div` carrying `.chip` or `.tab` can never be `:disabled`. Keying on
897/// the accessible state is the pattern `field_rules` already establishes for
898/// `aria-invalid`, on the reasoning that one fact read by both the styling and
899/// the accessibility tree cannot drift from itself.
900///
901/// The rest depth is re-asserted rather than assumed, because this rule has to
902/// beat the hover and pressed rules above it. It does that on source order at
903/// equal specificity, not by out-specifying them: every rule this function's
904/// caller emits is (0,2,0), and adding a `:not(:disabled)` anywhere would raise
905/// one of them and have to be unpicked when this output moves inside its own
906/// cascade layer.
907///
908/// Re-asserted on **both** axes, through `rest_declarations`.
909/// `depth_declarations` alone is empty for [`Depth::Flat`], so a flat control
910/// would win the contest with nothing to say and keep the hover surface
911/// underneath a control that had stopped answering.
912#[must_use]
913pub fn disabled_rule(selector: &str, depth: Depth) -> String {
914 format!(
915 ".{selector}{DISABLED} {{\n{} color: var(--{});\n cursor: not-allowed;\n}}\n",
916 rest_declarations(depth),
917 State::Disabled.token()
918 )
919}
920
921/// Every state a selector that answers a click implies: hover, pressed, focus
922/// and disabled, in that order.
923///
924/// Order is the whole cascade mechanism here. All four selectors are
925/// specificity (0,2,0), so disabled wins over hover and pressed by coming last
926/// and by nothing else.
927///
928/// Pressed emits [`Depth::pressed`] in full, fill and edge together. Emitting
929/// only the edge is what left goingson hand-writing `background:
930/// var(--surface-sunken)` on three separate rules, and a fill that does not
931/// travel with its edge is precisely the disagreement `Depth` exists to make
932/// unrepresentable. So the pressed fill comes from the description
933/// (`--surface-well`) rather than from whatever each app reached for.
934///
935/// Hover has no member in the description and is renderer policy: a terminal
936/// and an immediate-mode painter have no hover to express. It resolves against
937/// `--hover-surface`, which `makeover` already derives and which nothing
938/// consumed until now. What it *is* gated on is capability, via
939/// `hover_condition`. Before that gate existed the apps each wrote their own:
940/// goingson's section 60 exists solely to take back the hover state this
941/// function had just handed it, by out-specifying a rule it does not own.
942///
943/// `depth` is the selector's **rest** depth, used to place the focus ring and
944/// to restore the surface under a disabled control. The pressed rule keeps
945/// inverting from [`Depth::Raised`] regardless: a tab's unchosen depth is
946/// [`Depth::Sunken`], and `Sunken.pressed()` is `Sunken`, so deriving the press
947/// from the rest depth would leave a tab with no press at all.
948#[must_use]
949pub fn interactive_rules(selector: &str, depth: Depth, opts: &Emit) -> String {
950 let mut css = gated(
951 hover_condition(),
952 &format!(".{selector}:hover {{\n background: var(--hover-surface);\n}}\n"),
953 );
954 css.push_str(&depth_rule(
955 &format!("{selector}:active"),
956 Depth::Raised.pressed(),
957 ));
958 css.push_str(&focus_rule(selector, depth, opts));
959 css.push_str(&disabled_rule(selector, depth));
960 css
961}
962
963/// The compound a card's interactive states are written against: the class
964/// on an element that is itself a control.
965///
966/// `label` for a card wrapping a choice, `[data-act]` for an act a renderer
967/// drew on some other element. Without the class prefix, the way every
968/// selector handed to [`interactive_rules`] is.
969#[must_use]
970pub fn pressable_card(card: &str) -> String {
971 format!("{card}:is(a, button, label, [data-act])")
972}
973
974/// One rule per depth: its fill and its edge, together.
975///
976/// A depth and nothing else. `.raised` says a surface sits on what is behind
977/// it, which is a statement about the shape and not about what happens when a
978/// pointer arrives, so it emits no hover, press, focus or disabled rule. The
979/// named surfaces are where interaction lives: `.button`, and `.card` written
980/// on a control, get their states from `surface_rules`.
981///
982/// Giving this class the interactive set leaves the vocabulary with no raised
983/// surface that is merely an object, so a consumer that needs one has to take a
984/// control class and cancel half of it.
985#[must_use]
986pub fn depth_rules(opts: &Emit) -> String {
987 let mut css = String::new();
988 for depth in [Depth::Raised, Depth::Well] {
989 let Some(class) = depth_class(depth, opts) else {
990 continue;
991 };
992 css.push_str(&depth_rule(&class, depth));
993 }
994 css
995}
996
997/// The three surfaces that are a depth with a name.
998///
999/// `button` and `card` are both [`Depth::Raised`], and `field` is a
1000/// [`Depth::Well`] because that is the reading `Depth`'s own documentation
1001/// gives a text field. Their bodies come out identical by construction rather
1002/// than by hand: three hand-written copies in goingson's stylesheet is what
1003/// phase A deletes, and generating them from one call is what stops them
1004/// drifting apart again.
1005///
1006/// A card's states hang off [`pressable_card`] rather than the bare class. A
1007/// card is a raised object that answers a pointer only when it is written on a
1008/// control, which is what lets one name cover both: a store tile that is one
1009/// link, a tier picker that is a label round a radio, and a use-case card that
1010/// does nothing and so has no hover to cancel.
1011fn surface_rules(opts: &Emit) -> String {
1012 let mut css = String::new();
1013 let button = class("button", opts);
1014 css.push_str(&depth_rule(&button, Depth::Raised));
1015 css.push_str(&interactive_rules(&button, Depth::Raised, opts));
1016
1017 let card = class("card", opts);
1018 css.push_str(&depth_rule(&card, Depth::Raised));
1019 css.push_str(&interactive_rules(
1020 &pressable_card(&card),
1021 Depth::Raised,
1022 opts,
1023 ));
1024
1025 let field = class("field", opts);
1026 css.push_str(&depth_rule(&field, Depth::Well));
1027
1028 // A field takes focus and refuses input like everything else here, and got
1029 // neither until now, which is why all three apps hand-write a focus ring
1030 // for it and no two of them match. No hover or pressed: a text field does
1031 // not light up under the pointer and does not invert when clicked, so the
1032 // two states `interactive_rules` would add are the two it does not have.
1033 css.push_str(&focus_rule(&field, Depth::Well, opts));
1034 css.push_str(&disabled_rule(&field, Depth::Well));
1035
1036 // A multiline field shows its value, not a window onto it: a whole message
1037 // is content, not a scroll. `field-sizing: content` grows the `<textarea>`
1038 // with its value up to its container's ceiling; the floor is three lines,
1039 // the resting height and the answer for an engine without the property.
1040 // Scoped to `textarea`: a single-line input or select is already its own
1041 // size and must not grow. The floor rides a custom property the way the
1042 // table's `ch` floors do, so an app that wants a taller resting field says
1043 // so once instead of restyling the rule.
1044 let _ = writeln!(
1045 css,
1046 "textarea.{field} {{\n field-sizing: content;\n min-block-size: var(--field-min-lines, 3lh);\n}}\n"
1047 );
1048
1049 // A file field's own button is a button. `::file-selector-button` is the
1050 // one part of an `<input type="file">` a stylesheet reaches, and without a
1051 // rule the platform's grey control sits inside a well drawn in the theme's.
1052 // Raised, with the hover and the press a button has; no focus ring, because
1053 // the focus belongs to the input the pseudo-element is part of, and the
1054 // field's own ring already draws it.
1055 let chooser = format!("{field}::file-selector-button");
1056 css.push_str(&depth_rule(&chooser, Depth::Raised));
1057 let _ = writeln!(
1058 css,
1059 ".{chooser} {{\n border: none;\n color: inherit;\n font: inherit;\n padding: var(--gap-bound) var(--gap-peer);\n margin-inline-end: var(--gap-peer);\n cursor: pointer;\n}}"
1060 );
1061 css.push_str(&gated(
1062 hover_condition(),
1063 &format!(".{chooser}:hover {{\n background: var(--hover-surface);\n}}\n"),
1064 ));
1065 css.push_str(&depth_rule(
1066 &format!("{chooser}:active"),
1067 Depth::Raised.pressed(),
1068 ));
1069
1070 // Keyed on the ARIA attribute rather than on a class, so the visual state
1071 // and the accessible state cannot drift apart: there is one fact and both
1072 // read it. goingson already drove its invalid styling this way and was
1073 // right to; the `.invalid` class this emitted before 0.5.0 was a second
1074 // place to forget.
1075 //
1076 // The ring composes *after* the bevel rather than replacing it. box-shadow
1077 // is not additive, so a lone ring silently dropped the well out from under
1078 // an invalid field. Flat and unlit: this edge is saying "wrong", and
1079 // lighting one side would have it say "raised" at the same time.
1080 let _ = writeln!(
1081 css,
1082 ".{field}[aria-invalid=\"true\"] {{\n box-shadow: var({}), 0 0 0 {} var(--danger);\n}}",
1083 bevel_var(Bevel::Inset),
1084 opts.border_width
1085 );
1086
1087 // The default-button ring, on the one control that commits
1088 // (the act that commits, wiki `explicit-commit-affordance`).
1089 // A flush frame twice the border width, composed after the bevel for the
1090 // invalid ring's reason, and outside the element, so the focus outline,
1091 // which stands off by its own width, lands beside it rather than over it.
1092 // Pressed keeps the ring and inverts only the bevel. Disabled drops the
1093 // ring and the weight together: the ring says "this is what Return does",
1094 // and a control Return cannot reach is not the default. goingson's bulk
1095 // bars are the site: Complete and Delete stand disabled until a row is
1096 // ticked, and ringed they read as the strongest controls on a page with
1097 // nothing selected.
1098 //
1099 // An attribute rather than a class, for `data-tone`'s reason: it is a fact
1100 // about the act, and a renderer writes it beside the tone.
1101 let ring = format!("0 0 0 calc(2 * {})", opts.border_width);
1102 let _ = writeln!(
1103 css,
1104 ".{button}[data-commits] {{\n box-shadow: var({}), {ring} var(--border-strong);\n font-weight: bold;\n}}",
1105 bevel_var(Bevel::Raised)
1106 );
1107 let _ = writeln!(
1108 css,
1109 ".{button}[data-commits]:active {{\n box-shadow: var({}), {ring} var(--border-strong);\n}}",
1110 bevel_var(Bevel::Inset)
1111 );
1112 let _ = writeln!(
1113 css,
1114 ".{button}[data-commits]{DISABLED} {{\n box-shadow: var({});\n font-weight: inherit;\n}}",
1115 bevel_var(Bevel::Raised)
1116 );
1117
1118 // The act the screen is for (the leading act).
1119 //
1120 // **Leading fills and committing outlines**, which is what lets a control
1121 // wear both. The ring above is a frame outside the bevel and this is the
1122 // ground inside it, so the two compose rather than compete: a form that is
1123 // the screen's own work draws a filled button with the default ring round
1124 // it, and a sub-form's Add keeps the ring alone.
1125 //
1126 // `--content-on-action` rather than a hand-picked ink. The theme derives it
1127 // with `readable_on(action)`, so a theme whose action hue is pale gets dark
1128 // text without this file knowing which themes those are.
1129 //
1130 // The bevel stays. A leading control is still a button, and dropping its
1131 // raise to signal importance would make the one control a reader most needs
1132 // to press the one that least looks pressable.
1133 // `:not([data-tone])` is load-bearing, and a render caught it missing.
1134 // A toned control already says what pressing it means, and that outranks
1135 // how badly the screen wants it pressed, the rule `makeover-tui` states
1136 // and this file did not. Without the guard, goingson's compose drew Queue
1137 // with the Success tone's pale ground under `--content-on-action`'s near
1138 // white ink, which is a label nobody can read.
1139 //
1140 // The tone keeps the control; `leading` adds nothing to it. That is a
1141 // deliberate loss: a screen whose primary act is destructive or toned has
1142 // to lead by order and by what the tone already says.
1143 let _ = writeln!(
1144 css,
1145 ".{button}[data-leading]:not([data-tone]) {{\n background: var(--action);\n color: var(--content-on-action);\n}}"
1146 );
1147 // Hover keeps the derived pair, so the fill does not fall back to the
1148 // ordinary button's ground mid-hover and leave `--content-on-action`
1149 // stranded on a surface it was never measured against.
1150 //
1151 // Gated through `hover_condition` like every other hover rule here: whether
1152 // a hover state exists at a density is `Affordance`'s to answer, and a
1153 // rule written outside the gate is this renderer inventing a second answer.
1154 // The vocabulary test catches exactly that, and caught this.
1155 css.push_str(&gated(
1156 hover_condition(),
1157 &format!(
1158 ".{button}[data-leading]:not([data-tone]):hover {{\n background: var(--action-hover);\n color: var(--content-on-action);\n}}\n"
1159 ),
1160 ));
1161 // Disabled drops to the disabled ink on the ordinary button ground: a filled
1162 // control that cannot be pressed still reads as the thing to press, which
1163 // is the one thing the fill must not say when it cannot be pressed.
1164 //
1165 // Through `fill_var` rather than naming the token, so this follows the
1166 // ordinary button if the raised fill is ever re-pointed.
1167 let _ = writeln!(
1168 css,
1169 ".{button}[data-leading]:not([data-tone]){DISABLED} {{\n background: {};\n color: var(--{});\n}}",
1170 fill_var(Fill::Raised),
1171 State::Disabled.token()
1172 );
1173 css
1174}
1175
1176/// Badges and chips.
1177///
1178/// The one place phase A changes how goingson looks rather than only where its
1179/// rules live. [`Token::Badge`] is [`Depth::Flat`], so a badge emits no fill
1180/// and no edge at all, where goingson ships `.tag, .badge` as a single rule
1181/// carrying the raised bevel. Splitting that means reading every call site to
1182/// decide which of the two it always was.
1183///
1184/// What a badge does carry is a [`Tone`], the intent family it shares with
1185/// notices and nothing else. Neutral is the bare class rather than a variant,
1186/// because it is the absence of a status and not a status called "none".
1187/// Text that goes somewhere.
1188///
1189/// The one inline control. A table cell carries `cell-link` instead, which
1190/// reads as its row's title rather than as a link; this is the same thing
1191/// outside a table, which is what a described run holds when a sentence
1192/// contains a link.
1193///
1194/// Colour and underline only. Whether a link is inline in a sentence or sitting
1195/// on its own line is the app's layout, and how much room it takes is
1196/// `makeover-geometry`'s. What is here is the pair of signals that say "this
1197/// goes somewhere" and nothing that says where it sits.
1198///
1199/// The visited arm is deliberately absent. A link inside an app points at the
1200/// app's own screens, which the user is expected to have been to, so painting
1201/// them differently marks almost everything and distinguishes nothing.
1202fn link_rules(opts: &Emit) -> String {
1203 let mut css = String::new();
1204 let link = class("link", opts);
1205
1206 let _ = writeln!(
1207 css,
1208 ".{link} {{\n color: var(--action);\n \
1209 text-decoration: underline;\n}}"
1210 );
1211 // The pointer-target floor, and the scope is the whole of the design in it.
1212 //
1213 // A bare `.link` is its own line box, 21px at the body size, under the 24
1214 // that `makeover_geometry::TARGET_LEAST` names. Applied to every `.link`
1215 // that floor would reach an anchor set in running prose, where growing the
1216 // box sets the leading of the paragraph around it: the fix would cost more
1217 // than the defect. So it is scoped to a link laid out as a piece rather
1218 // than set in text, which in the emitted markup is one inside a run or a
1219 // cell, a footer strip, a row of places, a table cell.
1220 //
1221 // `min-block-size` rather than padding: padding adds to the line box and
1222 // grows whatever holds the link, where a minimum lets the anchor take room
1223 // its container usually already has. `inline-flex` is what makes the
1224 // minimum apply to an inline element at all, and `align-items: center`
1225 // keeps the text on the box's centre line rather than its top.
1226 let run = class("run", opts);
1227 let cell = class("cell", opts);
1228 let least = makeover_geometry::TARGET_LEAST.token();
1229 let _ = writeln!(
1230 css,
1231 ".{run} .{link},\n.{cell} .{link} {{\n display: inline-flex;\n \
1232 align-items: center;\n min-block-size: var(--{least});\n}}"
1233 );
1234 // The hover step is the same one every other control takes, and it is a
1235 // colour rather than a surface: a link has no box to raise.
1236 css.push_str(&gated(
1237 hover_condition(),
1238 &format!(".{link}:hover {{\n color: var(--action-hover);\n}}\n"),
1239 ));
1240 // The one ring, placed as on anything standing level with the page.
1241 css.push_str(&focus_rule(&link, Depth::Flat, opts));
1242 // A link is often a `<button>` rather than an `<a>`: a renderer picks the
1243 // element from the method, so a link that writes is a button that has to
1244 // stop looking like one. What that costs is named in [`reset`].
1245 css.push_str(&Reset::TEXT_BUTTON.rule(&format!("button.{link}")));
1246 css
1247}
1248
1249fn token_rules(opts: &Emit) -> String {
1250 let mut css = String::new();
1251
1252 // No `depth_rule` call here, deliberately: `Token::Badge.depth(_)` is Flat,
1253 // and a label with an edge says it can be pressed.
1254 let badge = class("badge", opts);
1255 // `content-muted` literally, not `Tone::Neutral.token()`. What makes a
1256 // badge quiet is `Token::Badge` answering no click, which this crate holds
1257 // and `Tone` genuinely does not know. Routing it through Neutral put the
1258 // claim where the evidence was not, and the bill arrived on the figure
1259 // value: it took the same muting from the same call and read as its own
1260 // caption. Neutral answers `content`.
1261 //
1262 // A badge is a chip, wiki `table-model`: an opaque fill inside an edge, in
1263 // the theme's own ink at normal weight. Coloured text was never ratified
1264 // and measured 1.34:1 on goingson's warning; muted text 2.78:1 on
1265 // solarized-dark. So the ink is `content` and what says which kind of
1266 // token it is moves to the fill and the edge: the table's raised ground for
1267 // a neutral chip, makeover's `*-surface` for a status, edged in its tone.
1268 // Still no bevel: a label with a raised edge says it can be pressed.
1269 //
1270 // `inline-block`, not a flex row: a badge whose label outruns its column
1271 // ends in an ellipsis, and `text-overflow` reads the text as inline content
1272 // rather than as a flex item. `min-width: 0` overrides the flex-item
1273 // `min-width: auto`, which would otherwise hold the badge at its label's
1274 // full width and refuse to shrink to the ellipsis.
1275 let bw = opts.border_width;
1276 let _ = writeln!(
1277 css,
1278 ".{badge} {{\n display: inline-block;\n min-width: 0;\n max-inline-size: 100%;\n \
1279 overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n \
1280 padding: 0 var(--step-snug);\n border: {bw} solid var(--border);\n \
1281 border-radius: var(--radius-fine);\n background: var(--surface-raised);\n \
1282 color: var(--content);\n font-weight: normal;\n}}"
1283 );
1284 tone_rules(&mut css, &format!(".{badge}"), toned_surface);
1285
1286 // A button carries the four tones a badge does. It had none, on the reading
1287 // that a control's colour is its surface rather than its text, and that
1288 // reading has one hole big enough to matter: the button that destroys
1289 // something. Every consumer had written that rule itself, and a description
1290 // that says `Tone::Danger` on an act had nowhere for it to land.
1291 //
1292 // A fill and not the text, matching the badge exactly. Coloured text is
1293 // the shape wiki `table-model` ruled out for status text, and
1294 // `{tone}-surface`'s own derivation comment says why: the tone colours are
1295 // fills, and a fill used as
1296 // ink measures 3.36:1 for danger and 1.84:1 for success on goingson's
1297 // theme. Both are under the 4.5:1 floor, and success is under it by more
1298 // than the floor itself.
1299 //
1300 // It read as ratified for longer than it was because goingson set
1301 // `color` on `.button` in a later layer, so no described tone ever reached
1302 // a button and nobody saw the colour it would have drawn.
1303 //
1304 // The earlier note here said a red surface belongs to an app's own layer.
1305 // That argument was against a *saturated* fill, and it still holds: this is
1306 // the ground with 12 percent of the tone in it, which is the same tint a
1307 // status chip carries and is not something an app would draw over.
1308 //
1309 // The fill and NOT the edge, which is where this differs from the badge.
1310 // A badge's border is makeover's, so the badge tones it. A button's is the
1311 // app's: goingson writes `border: ... solid var(--border)` on `.button` in
1312 // a later layer, and a shorthand cancels a generated `border-color` the
1313 // same way its `color` cancelled the tone for months. goingson's own drift
1314 // check caught it on the first build. An edge an app silently overrides is
1315 // worse than no edge, so the tint carries the tone alone.
1316 let button = class("button", opts);
1317 for tone in STATUS_TONES {
1318 let _ = writeln!(
1319 css,
1320 ".{button}[data-tone=\"{0}\"] {{\n background: var(--{0}-surface);\n}}",
1321 tone.token()
1322 );
1323 // The pointer answer, at the specificity the tone rule just took. The
1324 // plain `.button:hover` is (0,2,0) and sits earlier in this sheet, so
1325 // without this a toned button is the one control on the screen that
1326 // does not move under a pointer.
1327 //
1328 // The fallback is for the version skew, and it is not decoration: the
1329 // hover tint is a `makeover` 3.8 token and this sheet is emitted from a
1330 // crate an app can upgrade on its own. An unresolved custom property
1331 // makes the whole declaration invalid at computed-value time rather
1332 // than dropping to the cascade, so without it a toned button on an
1333 // older theme would hover to `transparent`.
1334 css.push_str(&gated(
1335 hover_condition(),
1336 &format!(
1337 ".{button}[data-tone=\"{0}\"]:hover {{\n background: \
1338 var(--{0}-surface-hover, var(--hover-surface));\n}}\n",
1339 tone.token()
1340 ),
1341 ));
1342 }
1343
1344 // A chip holds itself down, which is `Depth::pressed` arrived at
1345 // independently by two apps. `removable` is a remove affordance, so it is
1346 // markup and waits for phase B.
1347 let chip = class("chip", opts);
1348 let unlatched = Token::Chip { removable: false };
1349
1350 // The pointer floor, and the one number in this file that does not scale.
1351 // A chip drawn from its padding alone came out 23px at every width and
1352 // every density in goingson: 36 of one ui-fuzz run's 51 target findings
1353 // were this single rule. The length arrives from the caller, the way every
1354 // other length in this crate does, see `Emit::target_min` for why the
1355 // floor is an absolute rather than a `--step-*`.
1356 //
1357 // A floor and not a height: a chip with two lines of text or a larger root
1358 // size still grows. `.chip` is already `inline-flex` with its items
1359 // centred, from quasi-webview's box rules, so the extra block size opens
1360 // around the label rather than under it. `.chip.latched` takes it through
1361 // the same class; `.badge` is a separate class and deliberately does not,
1362 // because a badge is a label and never a target.
1363 let _ = writeln!(
1364 css,
1365 ".{chip} {{\n min-block-size: {};\n}}",
1366 opts.target_min
1367 );
1368
1369 css.push_str(&depth_rule(&chip, unlatched.depth(false)));
1370 css.push_str(&interactive_rules(&chip, unlatched.depth(false), opts));
1371 css.push_str(&depth_rule(
1372 &format!("{chip}.latched"),
1373 unlatched.depth(true),
1374 ));
1375 css
1376}
1377
1378/// The three selectors, each named by what it picks.
1379///
1380/// A tab comes *forward* to join the pane it opens, which is why
1381/// [`Selector::Tabs`] chooses [`Depth::Raised`] where a segment and a toggle
1382/// are held in. That is the folder semantic, and it is the whole reason the
1383/// three are not one member with a flag.
1384///
1385/// [`Selector::abutting`] is not emitted: whether the options touch is
1386/// spacing, and spacing is `makeover-geometry`'s question to answer.
1387///
1388/// Both states emit. Naming only the chosen option leaves an unchosen one
1389/// falling through to [`Depth::Flat`] with nothing drawn for it, so an app has
1390/// to hand-write the recess that makes its chosen tab read as forward.
1391fn selector_rules(opts: &Emit) -> String {
1392 let mut css = String::new();
1393 for selector in [Selector::Tabs, Selector::Segmented, Selector::Toggle] {
1394 let c = class(option_class(selector), opts);
1395 css.push_str(&depth_rule(&c, selector.unchosen()));
1396 css.push_str(&interactive_rules(&c, selector.unchosen(), opts));
1397 if selector.joins_its_pane() {
1398 // Every tab in a folder strip rounds at the top and stays square
1399 // at the bottom, chosen or not: the corners belong to the strip's
1400 // shape rather than to which option is up. On the base class and
1401 // not only on the chosen arm, so that an app has no reason left to
1402 // carry a radius of its own. goingson's unlayered `.tab` rule beat
1403 // a chosen-only version of this outright, an unlayered rule being
1404 // ahead of every layer whatever its specificity.
1405 let _ = writeln!(
1406 css,
1407 ".{c} {{\n border-radius: var(--radius-control) var(--radius-control) 0 0;\n}}"
1408 );
1409 css.push_str(&joined_rule(&c, selector.chosen(), opts));
1410 } else {
1411 css.push_str(&depth_rule(&format!("{c}.chosen"), selector.chosen()));
1412 }
1413 }
1414 css
1415}
1416
1417/// The chosen option of a selector that joins what it opens.
1418///
1419/// [`depth_rule`] draws a closed box, which is right for anything standing on
1420/// its own and wrong for a folder tab: a closed bottom run reads as a chip
1421/// resting near its pane rather than as the front of it. Three things make the
1422/// join, and all three are needed, which is why this is one rule rather than a
1423/// property added to the depth:
1424///
1425/// - The depth's own fill, so the tab and the pane are the same surface. Taken
1426/// from [`Depth::fill`] rather than named here, so the pairing rule holds.
1427/// - [`Bevel::RaisedOpen`], so the run between the two is not drawn.
1428/// - A pull down by one border width, so the tab covers the pane's own top
1429/// run where it passes underneath. Without it the pane's lit edge draws
1430/// straight across the join and the tab reads as sitting on a line.
1431///
1432/// The corners round at the top and stay square at the bottom for the same
1433/// reason: a rounded bottom corner puts a notch of page colour either side of
1434/// the join. `makeover-geometry` has no per-corner member and does not need
1435/// one, since which corners round is a consequence of the join rather than a
1436/// scale a consumer picks.
1437fn joined_rule(selector: &str, depth: Depth, opts: &Emit) -> String {
1438 let mut body = String::new();
1439 if let Some(fill) = depth.fill() {
1440 let _ = writeln!(body, " background: {};", fill_var(fill));
1441 }
1442 let _ = writeln!(
1443 body,
1444 " box-shadow: var({});",
1445 bevel_var(Bevel::RaisedOpen)
1446 );
1447 // No radius here. Every tab in a joining strip already rounds at the top
1448 // from the base rule, chosen or not, and repeating it on this arm would be
1449 // a second copy of one decision.
1450 let _ = writeln!(
1451 body,
1452 " margin-block-end: calc(-1 * {});",
1453 opts.border_width
1454 );
1455 // And it has to paint above what it overlaps. Both the tab and the pane are
1456 // in flow, the pane is the later sibling, so without this the pane draws
1457 // over the run the pull-down just covered and the join is undone by the
1458 // pane's own lit edge. Positioned, not raised by `z-index`: being
1459 // positioned is enough to paint above an unpositioned sibling, and a stack
1460 // index here would be a number this crate has no way to keep true against
1461 // whatever an app stacks around it.
1462 let _ = writeln!(body, " position: relative;");
1463 let mut css = format!(".{selector}.chosen {{\n{body}}}\n");
1464
1465 // A strip that runs down its pane joins it on the side, and the join above
1466 // is written for a strip that runs across. Which way a strip runs is not
1467 // on [`Selector`], and it should not be: it is the arrangement, and the
1468 // renderer drawing the arrangement is the one that knows.
1469 //
1470 // `aria-orientation` is how that renderer has to say it anyway. It is
1471 // ARIA's word rather than a private attribute, required on any vertical
1472 // tablist for a screen reader, so keying on it couples this to the
1473 // standard and not to one caller's markup.
1474 //
1475 // The join turned a quarter: the open run faces the pane at the inline end,
1476 // the pull is one border width toward it rather than down, and the corners
1477 // round on the side away from the pane. Every tab in the column takes those
1478 // corners, chosen or not, for the across strip's reason: the corners are
1479 // the strip's shape, not the chosen option's. The pane has to sit against
1480 // the strip for this to read, which is the arrangement sheet's to say.
1481 let _ = writeln!(
1482 css,
1483 "[aria-orientation=\"vertical\"] .{selector} {{\n \
1484 border-radius: var(--radius-control) 0 0 var(--radius-control);\n}}"
1485 );
1486 let _ = writeln!(
1487 css,
1488 "[aria-orientation=\"vertical\"] .{selector}.chosen {{\n \
1489 box-shadow: var({OPEN_SIDE_VAR});\n \
1490 margin-block-end: 0;\n \
1491 margin-inline-end: calc(-1 * {});\n}}",
1492 opts.border_width
1493 );
1494
1495 // A column of tabs that has folded over its pane runs across it, so inside
1496 // a folded strip the join turns back: corners round at the top and the
1497 // chosen tab pulls down. The arrangement sheet decides when a column folds
1498 // and says so by naming the container; `aria-orientation` cannot, since it
1499 // describes the keys and not the drawing.
1500 let _ = writeln!(
1501 css,
1502 "@container {STRIP_CONTAINER} (inline-size < {STRIP_FOLD}) {{\n\
1503 [aria-orientation=\"vertical\"] .{selector} {{\n \
1504 border-radius: var(--radius-control) var(--radius-control) 0 0;\n}}\n\
1505 [aria-orientation=\"vertical\"] .{selector}.chosen {{\n \
1506 box-shadow: var({});\n \
1507 margin-inline-end: 0;\n \
1508 margin-block-end: calc(-1 * {});\n}}\n}}",
1509 bevel_var(Bevel::RaisedOpen),
1510 opts.border_width
1511 );
1512 css
1513}
1514
1515/// The container a vertical tab strip's arrangement names when it can fold the
1516/// strip over its pane.
1517pub const STRIP_CONTAINER: &str = "tab-strip";
1518
1519/// The inline size of [`STRIP_CONTAINER`] under which a vertical strip runs
1520/// across its pane. An arrangement that folds the strip folds at this width,
1521/// or the tabs draw one way while laid out the other.
1522pub const STRIP_FOLD: &str = "36rem";
1523
1524/// The parts of a list row.
1525///
1526/// The list is written out rather than derived because `RowPart` is
1527/// `#[non_exhaustive]`, so there is nothing to iterate. A member added upstream emits no rule until it is named here, which
1528/// is the trade `non_exhaustive` makes: a silent gap instead of a build break.
1529/// [`part_class`] carries the same list and the same obligation.
1530fn row_rules(opts: &Emit) -> String {
1531 let mut css = String::new();
1532
1533 // The container the rows sit in, giving back what a `<ul>` brought. Not a
1534 // size: there is no magnitude in it, which is the line this crate holds.
1535 css.push_str(&Reset::BULLETS.rule(&format!(".{}", class("list", opts))));
1536
1537 for part in [
1538 RowPart::Primary,
1539 RowPart::Secondary,
1540 RowPart::Meta,
1541 RowPart::Actions,
1542 RowPart::Tokens,
1543 RowPart::Proportion,
1544 ] {
1545 let c = class(part_class(part), opts);
1546
1547 // Actions carry controls rather than text, and `RowPart::intent` says
1548 // so by returning the same intent inheriting already gives. Pinning it
1549 // would be louder than saying nothing. Tokens answer alike, for their
1550 // own reason: each token carries its own tone, and a colour on the
1551 // strip would fight the things sitting in it. A proportion is the same
1552 // case again: the meter inside carries the tone.
1553 if !matches!(
1554 part,
1555 RowPart::Actions | RowPart::Tokens | RowPart::Proportion
1556 ) {
1557 let _ = writeln!(css, ".{c} {{\n color: var(--{});\n}}", part.intent());
1558 }
1559
1560 // A row's actions are shown at rest. `RowPart::revealed_on_hover` said
1561 // otherwise and was not honoured here from 0.23.0; makeover-layout
1562 // 0.13.0 retired the method, so there is no longer a description saying
1563 // one thing and a renderer doing another.
1564 //
1565 // The rule was `opacity: 0` gated to pointer devices, revealed on
1566 // `:hover` and on `:focus-within`. Each escape it needed was a report
1567 // that hiding was wrong for somebody: `focus-within` because tabbing
1568 // could never reach an action; the gate because a fingertip had no way
1569 // to unhide, which both webview apps had already hand-written
1570 // `opacity: 1` to undo. What was left was a control hidden from
1571 // exactly one group: people using a pointer, who are also the group
1572 // scanning a list to find out what can be done to a row.
1573 //
1574 // A settings screen is where that reads worst: the whole reason to be
1575 // on it is to remove a key, and the button doing so was invisible
1576 // until pointed at. A table cell's actions were never hidden, so the
1577 // two arrangements now agree.
1578 }
1579
1580 // A part that may take two lines. `Flow::Tight` gets no rule: one line is
1581 // what a run already does, and restating it here would put a declaration on
1582 // every part in every row to say nothing.
1583 //
1584 // This is the shape both webview apps had already written by hand and
1585 // commented, Balanced Breakfast on a feed row's title, goingson on a
1586 // problem's body, which is the whole argument for the description
1587 // carrying it. `-webkit-` prefixed and unprefixed together: the prefixed
1588 // trio is what every engine actually implements, and `line-clamp` is the
1589 // standard property landing behind it.
1590 let _ = writeln!(
1591 css,
1592 ".{} {{\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: {lines};\n line-clamp: {lines};\n overflow: hidden;\n}}",
1593 class("row-relaxed", opts),
1594 lines = Flow::Relaxed.lines()
1595 );
1596
1597 // A row inside a hierarchy: a tree, an outline, a threaded list.
1598 // makeover-layout names the concept `Nesting`, deliberately not `Depth`,
1599 // which is surface bevel in that crate, and this is the rule. Without it a
1600 // described outline in a browser is a flat list with chevrons in it: the
1601 // folding works and the indent does not exist.
1602 //
1603 // The magnitude is a custom property with a fallback, which is this crate's
1604 // own shape: `--awaiting-gap` above is the precedent, and an app overriding
1605 // `--row-indent` is how a level becomes worth more or less. What a level IS
1606 // stays the description's; what it is WORTH is a renderer's, and a terminal
1607 // spending columns for the same fact is not disagreeing.
1608 //
1609 // Here rather than in each app, and that was a live option rather than an
1610 // oversight. `row-select`, `row-current` and `row-chosen` are app-styled by
1611 // design; the indent is not decoration, it is what the description MEANS,
1612 // and three apps agreeing about it by accident is not agreement.
1613 //
1614 // `padding` and not `margin`: a row is a box that can be selected and
1615 // hovered, and indenting with margin would take the indent out of the
1616 // highlight, so the shading under a nested row would start where its text
1617 // does rather than where its row does.
1618 let _ = writeln!(
1619 css,
1620 ".{} {{\n padding-inline-start: calc(var(--row-depth, 0) * var(--row-indent, 1.5ch));\n}}",
1621 class("row-nested", opts)
1622 );
1623
1624 // The two halves of a branch, emitted by quasi-webview and unstyled until
1625 // now for the same reason.
1626 //
1627 // A branch row is the one a reader can fold, and the chevron is its hit
1628 // target. The chevron is drawn by the app or the description, this says
1629 // where it sits and how big the target is, which is the accessibility fact
1630 // rather than the decorative one: a control smaller than this is one a
1631 // finger misses.
1632 let _ = writeln!(
1633 css,
1634 ".{} {{\n display: flex;\n align-items: baseline;\n gap: var(--row-disclose-gap, 0.5ch);\n}}",
1635 class("row-branch", opts)
1636 );
1637 let _ = writeln!(
1638 css,
1639 ".{} {{\n flex: none;\n min-inline-size: var(--tap-target, 2rem);\n min-block-size: var(--tap-target, 2rem);\n background: none;\n border: 0;\n color: inherit;\n cursor: pointer;\n}}",
1640 class("row-disclose", opts)
1641 );
1642
1643 // How a part holds what is in it, for a row and for a table cell. Here
1644 // rather than in quasi-webview's arrangement sheet because these are names
1645 // this crate emits, so a row an app writes by hand gets them too. The row
1646 // itself stays quasi-webview's: where a part sits in the line is the screen
1647 // renderer's arrangement, and nothing here says it.
1648 //
1649 // A token or a control never breaks across two lines. What gives when the
1650 // line runs short is the row's text.
1651 let tokens = class(part_class(RowPart::Tokens), opts);
1652 let actions = class(part_class(RowPart::Actions), opts);
1653 let proportion = class(part_class(RowPart::Proportion), opts);
1654 let fallback = class("row-part", opts);
1655 let cell_tokens = class(cell_part_class(CellPart::Tokens), opts);
1656 let cell_actions = class(cell_part_class(CellPart::Actions), opts);
1657 let cell_fallback = class("cell-part", opts);
1658 let _ = writeln!(
1659 css,
1660 ".{fallback},\n.{cell_fallback} {{\n min-width: 0;\n}}"
1661 );
1662 let _ = writeln!(
1663 css,
1664 ".{tokens} {{\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1665 );
1666 let _ = writeln!(
1667 css,
1668 ".{actions} {{\n display: flex;\n flex: none;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1669 );
1670 // A cell's parts sit inside the cell's own box, so they are inline: the
1671 // cell's alignment, which the column kind sets, still places them.
1672 let _ = writeln!(
1673 css,
1674 ".{cell_tokens},\n.{cell_actions} {{\n display: inline-flex;\n align-items: center;\n gap: var(--gap-bound);\n}}"
1675 );
1676 // Wrapping, and no wider than the cell: a badge already ends in an
1677 // ellipsis at its container's width, and an inline run sized by its
1678 // contents gave it a container as wide as the badge, so a long token was
1679 // clipped at the cell edge instead.
1680 let _ = writeln!(
1681 css,
1682 ".{cell_tokens} {{\n flex-wrap: wrap;\n max-inline-size: 100%;\n}}"
1683 );
1684 // A part that follows another keeps the same gap from it that its own
1685 // members keep from each other: a title ran into its New version badge, a
1686 // split into its Invited one, and a value into the value after it. Every
1687 // part after the first, not just tokens and actions. Not after the sizer,
1688 // which is a block of its own above the run.
1689 let sizer = class(list::CELL_SIZER, opts);
1690 let cell_in = class(list::CELL_IN, opts);
1691 let _ = writeln!(
1692 css,
1693 ".{cell_in} > :not(.{sizer}) + * {{\n \
1694 margin-inline-start: var(--gap-bound);\n}}"
1695 );
1696 let _ = writeln!(
1697 css,
1698 ".{tokens} > *,\n.{actions} > *,\n.{cell_tokens} > *,\n.{cell_actions} > * {{\n white-space: nowrap;\n}}"
1699 );
1700 // A proportion is a meter, and a meter is as wide as the row lets it be.
1701 let _ = writeln!(css, ".{proportion} {{\n flex: 1 1 auto;\n}}");
1702
1703 css
1704}
1705
1706/// A row of things that share their space, and what each fallback gets here.
1707///
1708/// Ruling: wiki `layout-room-and-fallback`, Max. Rule 1 is that every described
1709/// member is in flow, and these rules are how that is kept rather than asked
1710/// for. A member taken out of flow with `position: absolute` contributes zero
1711/// width to the row it shares, so nothing can collide with it and nothing
1712/// prevents the collision.
1713///
1714/// # The floor, which is most of the fix
1715///
1716/// `.run > *` gets `min-width: min-content`. That is the derived minimum the
1717/// ruling asks for, in this renderer's own unit and stated by the browser
1718/// rather than by anybody: a member cannot be squeezed narrower than what is
1719/// in it, so members in one flow push each other instead of overlapping. It
1720/// costs no query and no number, and it is what fixes all four measured widths
1721/// whichever fallback the group declared.
1722///
1723/// # A member that asks to fill
1724///
1725/// `.run > [data-width="fill"]` gets `flex: 1 1 0`, which is the second half of
1726/// what a column has always been able to say, reaching a row of regions.
1727/// `flex-basis: 0` and not `auto` is what makes several fills divide the room
1728/// equally rather than dividing the leftovers in proportion to their contents;
1729/// equal division is [`makeover_layout::Width::Fill`]'s own stated rule. The
1730/// floor above still applies, so a fill cannot shrink under what is in it.
1731///
1732/// A member that says nothing gets nothing, because a flex item with the floor
1733/// and no grow is already content-sized. That is why the omitted value here is
1734/// `Content` while a control omits `Fill`: each position leaves out what it
1735/// already did.
1736///
1737/// # What each fallback gets, exactly
1738///
1739/// [`Fallback::Wrap`] is `flex-wrap: wrap`, and a member that asks to fill gets
1740/// a stated room to start from.
1741///
1742/// Wrapping on its own is not exact. A flex line
1743/// breaks on each member's hypothetical size, a fill member's basis is `0`, and
1744/// the floor above is `min-content`, so the line breaks only once the members'
1745/// intrinsic widths no longer fit. A member holding a table reports almost
1746/// nothing for that: a table's headings and cells are `container-type:
1747/// inline-size`, so the size container refuses to be measured through and a few
1748/// headings are all that is left. Two fill members each holding a table drew as
1749/// two slivers side by side at 420 while both tables overflowed, and the page
1750/// scrolled sideways.
1751///
1752/// So under `Wrap` a fill member's `flex-basis` is
1753/// `min(100%, var(--run-room, 20rem))` rather than `0`: room the description
1754/// states, rather than room measured through a container that will not report
1755/// it. `min(100%, ...)` is what keeps a lone member from overflowing a run
1756/// narrower than the room, and it is the shape quasi's own `main.list-detail`
1757/// regions already fold on. The custom property is how an app says what the
1758/// room is, because the number is a size and sizes are the app's; the fallback
1759/// is a default rather than this crate settling a width.
1760///
1761/// Only under `Wrap`. A fill member in a run that does not wrap keeps
1762/// `flex: 1 1 0`, where equal division is the whole of what it asked for and
1763/// there is no line to break.
1764///
1765/// [`Fallback::Stack`] is wrap plus `flex: 1 1 max-content` on the members, so
1766/// a member that cannot sit beside its sibling takes a line of its own and
1767/// fills it. For the two-member run this was ruled on, a tab strip and a
1768/// band, that is precisely "a row becomes a column".
1769///
1770/// [`Fallback::Shed`] and [`Fallback::Menu`] get wrap, and this renderer is
1771/// honouring less than the description says. **CSS cannot express either one
1772/// without breaking the ruling's own first constraint.** Both need to know that
1773/// the run is out of room in order to take a member out of it, a container
1774/// query is the only construct that can ask, and `@container` compares against
1775/// a `<length>`, there is no `@container (inline-size < min-content)`. So
1776/// every honest spelling of Shed here needs an authored breakpoint, which is
1777/// the thing the ruling exists to forbid, and the dishonest ones are worse: a
1778/// clamped height clips by document order rather than by [`Priority`], and
1779/// `display: none` under a viewport `@media` is the `nth-child(n+5)` bug the
1780/// vocabulary replaced.
1781///
1782/// Wrapping is the right thing to do instead. It keeps every member reachable,
1783/// which is the property that was actually broken, goingson's new-contact
1784/// button left the viewport entirely at 560, and it keeps rule 1. A renderer
1785/// answering with less than was described is precedented and deliberate here:
1786/// [`makeover_layout::Region::Columns`] says a terminal stacking a board's
1787/// columns is honouring the description rather than degrading it.
1788///
1789/// The real mechanism needs the shed members to have somewhere to go, which is
1790/// markup and belongs to quasi-webview: an overflow control is a member of the
1791/// run, and the description does not yet say that a member *is* one.
1792///
1793/// # Menu, once a script is measuring
1794///
1795/// That is now built, in `quasi-webview`'s `menu.js`, and this crate's half of
1796/// it is two classes and one override. A script that has taken a menu run over
1797/// marks it `data-menu`, and a marked run goes back to `nowrap`: wrapping is
1798/// what hides the overflow condition the script is trying to measure. The
1799/// unmarked rule above is untouched, so a page that ships no script still
1800/// wraps, which is rule 1, every member reachable, rather than a strip with
1801/// tabs squeezed off the end.
1802///
1803/// `.run-overflow` is the control the shed members move into and
1804/// `.run-overflow-items` is where they land. The geometry is this crate's the
1805/// way every other surface's is; what is *in* it is the script's, because which
1806/// members no longer fit is a measurement and not a description.
1807fn run_rules(opts: &Emit) -> String {
1808 let run = class("run", opts);
1809 let mut css = String::new();
1810
1811 // `flex-wrap: nowrap` is stated rather than left to the default, because
1812 // the fallbacks below are read as overrides of this line and a reader
1813 // should not have to know which way flexbox leans to see that.
1814 //
1815 // No gap. Spacing between members is the app's, the same way this crate
1816 // states no margins anywhere else; a gap here would be a size, and the one
1817 // hardcoded size in the mechanism is makeover-geometry's contact patch.
1818 let _ = writeln!(
1819 css,
1820 ".{run} {{\n display: flex;\n flex-wrap: nowrap;\n align-items: center;\n}}"
1821 );
1822
1823 // The derived minimum, and the whole reason a member can no longer be
1824 // overlapped. `min-width: auto` is flexbox's default for a flex item and is
1825 // *not* the same thing: auto lets an item be compressed below its content
1826 // in a nowrap run, which is how a toolbar ends up drawn over a tab strip
1827 // even without anything leaving the flow.
1828 let _ = writeln!(css, ".{run} > * {{\n min-width: min-content;\n}}");
1829
1830 // A member that absorbs what is left. `flex-basis: 0` rather than `auto` is
1831 // what makes several fills divide the room equally instead of dividing the
1832 // leftovers in proportion to what is already in them, which is
1833 // `Width::Fill`'s own rule and the one thing that type states about more
1834 // than one of them.
1835 //
1836 // The `min-width: min-content` floor above is deliberately not overridden.
1837 // A fill that could shrink below its contents would overlap its neighbour,
1838 // which is rule 1, and equal division under a floor is still equal division
1839 // everywhere the floor is not reached.
1840 //
1841 // Attribute rather than class, because the width is a fact the description
1842 // carried rather than a hook this crate invented: the same division
1843 // `data-tone` and `data-selector` are on the right side of. It beats the
1844 // `Stack` rule below on specificity whichever order they are written in,
1845 // which is what a member asking to fill should do to a blanket.
1846 let _ = writeln!(
1847 css,
1848 ".{run} > [data-width=\"fill\"] {{\n flex: 1 1 0;\n}}"
1849 );
1850
1851 for fallback in [
1852 Fallback::Wrap,
1853 Fallback::Stack,
1854 Fallback::Shed,
1855 Fallback::Menu,
1856 ] {
1857 let name = fallback_class(fallback);
1858 let c = class(name, opts);
1859 let _ = writeln!(css, ".{c} {{\n flex-wrap: wrap;\n}}");
1860 if matches!(fallback, Fallback::Stack) {
1861 let _ = writeln!(css, ".{c} > * {{\n flex: 1 1 max-content;\n}}");
1862 }
1863 // The stated room, and only here. Written after the blanket fill rule
1864 // above so it overrides the basis it set; the grow and shrink that rule
1865 // states are deliberately left alone, so several fills still divide one
1866 // line equally and the min-content floor still stops any of them
1867 // shrinking under its contents.
1868 if matches!(fallback, Fallback::Wrap) {
1869 let _ = writeln!(
1870 css,
1871 ".{c} > [data-width=\"fill\"] {{\n \
1872 flex-basis: min(100%, var(--run-room, 20rem));\n}}"
1873 );
1874 }
1875 }
1876
1877 // A menu run a script has taken over. The mark is the script's and this is
1878 // the only rule that reads it: wrapping is what a run does when nothing is
1879 // measuring, and it is also what makes the overflow unmeasurable, since a
1880 // wrapped run always fits. The two cannot both be on.
1881 let menu = class(fallback_class(Fallback::Menu), opts);
1882 let _ = writeln!(css, ".{menu}[data-menu] {{\n flex-wrap: nowrap;\n}}");
1883
1884 // The tab strip inside such a run, which is the member whose tabs fold.
1885 // The run going back to `nowrap` is not enough on its own: the strip is a
1886 // wrapping row in its own right, and the floor above holds it at its
1887 // min-content, so it either wrapped to more lines or pushed the run wider
1888 // than its pane. Neither overflows, and a strip that never overflows never
1889 // folds: eight tabs drew as three rows. So the strip takes the room the
1890 // run has and no more, holds one line, keeps each tab at its own width,
1891 // and clips across, which is the overflow the script measures. `clip` and
1892 // not `hidden`: `hidden` would make the block axis scroll too, and a
1893 // chosen tab's pull over its pane is drawn below the strip's box.
1894 //
1895 // The floor comes off this one member deliberately. It exists so members
1896 // push rather than overlap; a clipped strip overlaps nothing, and what it
1897 // clips is moved into the menu before anyone sees it.
1898 let strip =
1899 format!("{menu}[data-menu] > [role=\"tablist\"]:not([aria-orientation=\"vertical\"])");
1900 let _ = writeln!(
1901 css,
1902 ".{strip} {{\n flex: 1 1 auto;\n flex-wrap: nowrap;\n min-width: 0;\n overflow-x: clip;\n}}"
1903 );
1904 let _ = writeln!(css, ".{strip} > * {{\n flex-shrink: 0;\n}}");
1905
1906 // The overflow control, and it is a member of the run like any other: in
1907 // flow, at the end, taking the width of what is in it. `relative` is what
1908 // the items hang off.
1909 let overflow = class("run-overflow", opts);
1910 let items = class("run-overflow-items", opts);
1911 let _ = writeln!(css, ".{overflow} {{\n position: relative;\n}}");
1912
1913 // Overlaid rather than in flow, for the reason every menu is: a control
1914 // that pushed the page down when it opened would change the layout it was
1915 // opened to escape. `inset-inline-end: 0` rather than a left, so the panel
1916 // stays on the page in both writing directions.
1917 //
1918 // No width, no padding and no border. All three are sizes and sizes are
1919 // makeover-geometry's; what is stated here is placement, the surface and
1920 // the shadow that separates it from the page, which is the same division
1921 // `figure_rules` and the timeline entry make. The elevation shadow is what
1922 // an overlaid surface takes instead of an edge, see `ELEVATION_PROPERTY`.
1923 let _ = writeln!(
1924 css,
1925 ".{items} {{\n \
1926 position: absolute;\n \
1927 inset-block-start: 100%;\n \
1928 inset-inline-end: 0;\n \
1929 z-index: 1;\n \
1930 display: flex;\n \
1931 flex-direction: column;\n \
1932 align-items: stretch;\n \
1933 background: var(--surface-raised);\n \
1934 box-shadow: var(--elevation-overlay);\n\
1935 }}"
1936 );
1937
1938 // `hidden` is how the script closes it, and a flex display would otherwise
1939 // beat the attribute's own `display: none`.
1940 let _ = writeln!(css, ".{items}[hidden] {{\n display: none;\n}}");
1941
1942 css
1943}
1944
1945/// Every class [`fallback_class`] can return, plus the run itself.
1946///
1947/// [`ROW_PART_CLASSES`](crate::list::ROW_PART_CLASSES)'s reasoning and the same
1948/// obligation: a `match` over a `#[non_exhaustive]` enum cannot be enumerated
1949/// from outside, so the list sits beside it and a test holds the two together.
1950/// `run` is in it because it is emitted in its own right rather than only as a
1951/// fallback's fallback.
1952pub const RUN_CLASSES: &[&str] = &[
1953 "run",
1954 "run-wrap",
1955 "run-stack",
1956 "run-shed",
1957 "run-menu",
1958 // Not returned by `fallback_class`: these two are the overflow control a
1959 // measuring renderer builds, and they are in the list because the list is
1960 // what a host seals its vocabulary against. A class emitted by a script and
1961 // missing from here is a control with no surface and no edge.
1962 "run-overflow",
1963 "run-overflow-items",
1964];
1965
1966/// The class a run carries for what it does when it is tight.
1967///
1968/// A run always carries `.run` as well, so an unrecognised fallback, the enum
1969/// is `#[non_exhaustive]`, lands as a plain nowrap row with the min-content
1970/// floor still under it. That is the safe failure: every member in flow and
1971/// none overlapped, which is the property, with only the rearrangement missing.
1972#[must_use]
1973pub fn fallback_class(fallback: Fallback) -> &'static str {
1974 match fallback {
1975 Fallback::Wrap => "run-wrap",
1976 Fallback::Stack => "run-stack",
1977 Fallback::Shed => "run-shed",
1978 Fallback::Menu => "run-menu",
1979 _ => "run",
1980 }
1981}
1982
1983/// What a wait looks like, for the attribute that has been describing one to
1984/// nobody.
1985///
1986/// Wiki `loading-and-progress-standard`, phase 2. `data-awaiting` is emitted
1987/// as `data-awaiting="determinate"` with a `data-awaiting-amount` beside it, or
1988/// `data-awaiting="indeterminate"` alone. This is the half that styles them,
1989/// without which the two render identically.
1990///
1991/// # Why it is keyed on `aria-busy` and not on the attribute alone
1992///
1993/// `data-awaiting` is a fact about the control: pressing this waits. It is true
1994/// when the page is painted and it stays true. Whether a wait is *running* is
1995/// true only between two events, so it is the binder's to set, and `aria-busy`
1996/// is the standard spelling of it, announced as well as drawn, which a class
1997/// of our own would not be.
1998///
1999/// That also keeps this crate out of any one client library's vocabulary.
2000/// `quasi-webview` sets `aria-busy` from htmx's request events; a host driving
2001/// the same markup another way sets it the same way and gets the same drawing.
2002///
2003/// # The two drawings
2004///
2005/// One pseudo-element either way, so no renderer has to emit an extra node.
2006///
2007/// Indeterminate is the activity mark of rule 2: a small square that blinks.
2008/// Determinate is a trough with a fill, drawn as a single gradient whose stop is
2009/// `--awaiting-share`, a plain number from 0 to 1 that the binder sets from
2010/// bytes it has actually watched land, marking the control
2011/// `data-awaiting-watched` while it does.
2012///
2013/// A determinate control nobody is watching draws the mark with the total
2014/// beside it in the reading's ink, `content: attr(data-awaiting-amount)`: the
2015/// size is known and the delivery is not, which is what the tui and egui
2016/// renderers draw for the same wait. The attribute is the binder's because no
2017/// rule can tell an unset share from a zero one. A watched control whose share
2018/// is still unset draws an empty trough, never a full one.
2019///
2020/// **What the bar may not do**, from rule 1 and from `Awaiting`'s own docs:
2021/// what is done over what there is, and never a remaining time, an arrival time
2022/// or a rate extrapolated forward. Nothing here can express one, which is
2023/// deliberate, the only input is a share of a measured payload.
2024///
2025/// # Sizes, and the deferral rule
2026///
2027/// `progress_rules` emits the tones and never the width, because the width is
2028/// not this crate's to know. A pseudo-element has no intrinsic size at all, so
2029/// the same treatment would render nothing anywhere. Both sizes are therefore
2030/// custom properties with defaults: an app that wants a different mark sets
2031/// `--awaiting-mark` and `--awaiting-bar` once, and one that says nothing gets a
2032/// mark that is visible.
2033///
2034/// # The cadence, and what happens without it
2035///
2036/// `--cadence-activity` comes from `makeover-timing` through [`build`](mod@crate::build),
2037/// and is a half-period, so a full cycle is twice it. It is used bare rather
2038/// than with a fallback: a number written here would be a second heartbeat for
2039/// a mark three renderers draw.
2040///
2041/// A sheet assembled without the time axis leaves `animation-duration` invalid,
2042/// which resolves to `0s`, which runs no animation and leaves the base style ,
2043/// a lit, still mark. That is also exactly what the reduced-motion block does,
2044/// since it sets the cadence to `0ms`. Both fall out of one rule because the
2045/// base style is lit and the keyframes do the dimming, which is the ordering
2046/// `makeover_timing::reduced_motion_css` asks its consumers for by name.
2047fn awaiting_rules(opts: &Emit) -> String {
2048 let mut css = String::new();
2049
2050 // Dimming rather than lighting, so a zero-length animation leaves a lit
2051 // mark rather than a blank one. See `makeover_timing::reduced_motion_css`.
2052 css.push_str(
2053 "@keyframes makeover-activity {\n \
2054 0%, 49.99% {\n background: var(--action);\n }\n \
2055 50%, 100% {\n background: var(--surface-sunken);\n }\n\
2056 }\n",
2057 );
2058 // The same blink for a mark drawn as an image beside text, where the
2059 // background colour is the text's ground and must not change.
2060 css.push_str(
2061 "@keyframes makeover-activity-beside {\n \
2062 0%, 49.99% {\n background-image: linear-gradient(var(--action), var(--action));\n }\n \
2063 50%, 100% {\n background-image: linear-gradient(var(--surface-sunken), var(--surface-sunken));\n }\n\
2064 }\n",
2065 );
2066
2067 // Nothing is drawn until something is waiting. `content` on the base rule
2068 // rather than on the busy one keeps the box the same box across the
2069 // transition, so a mark appearing does not reflow the line it is in.
2070 let _ = writeln!(
2071 css,
2072 "[data-awaiting]::after {{\n \
2073 content: \"\";\n \
2074 display: none;\n \
2075 margin-inline-start: var(--awaiting-gap, 0.5ch);\n \
2076 vertical-align: baseline;\n\
2077 }}"
2078 );
2079
2080 let _ = writeln!(
2081 css,
2082 "[data-awaiting][aria-busy=\"true\"]::after {{\n \
2083 display: inline-block;\n \
2084 inline-size: var(--awaiting-mark, 0.5em);\n \
2085 block-size: var(--awaiting-mark, 0.5em);\n \
2086 background: var(--action);\n \
2087 opacity: 1;\n \
2088 animation: makeover-activity calc(var(--cadence-activity) * 2) \
2089 step-end infinite;\n\
2090 }}"
2091 );
2092
2093 // The measured half. A wider box, no blink, and a gradient whose stop is
2094 // the share: the fill and the trough in one paint, so the markup stays one
2095 // pseudo-element on both branches.
2096 //
2097 // `--awaiting-share` unset is an empty trough, not a full one. A bar that
2098 // read full because nobody was counting would be the confidently-wrong
2099 // drawing rule 1 exists to forbid.
2100 //
2101 // `to right` and a right-to-left override rather than `to inline-end`:
2102 // no browser takes a logical direction in a gradient, and the declaration
2103 // that names one is dropped whole, leaving no fill at all.
2104 //
2105 // The trough takes an edge for the reason a well does: a bar at zero share
2106 // is otherwise a rectangle of the surface it sits on, which is nothing at
2107 // all. `border_width` rather than a literal, the way `depth_rule` and
2108 // `track_rules` write theirs.
2109 let _ = writeln!(
2110 css,
2111 "[data-awaiting=\"determinate\"][aria-busy=\"true\"]::after {{\n \
2112 inline-size: var(--awaiting-bar, 6em);\n \
2113 animation: none;\n \
2114 outline: {} solid var(--border);\n \
2115 outline-offset: -{};\n \
2116 background: linear-gradient(\n \
2117 to right,\n \
2118 var(--action) 0 calc(var(--awaiting-share, 0) * 100%),\n \
2119 var(--surface-sunken) 0\n \
2120 );\n\
2121 }}",
2122 opts.border_width, opts.border_width
2123 );
2124
2125 // Measured and unwatched: the mark, then the total. One pseudo-element
2126 // still, so the mark is an image painted at the inline start and the
2127 // total is the content beside it. More specific than the bar by the
2128 // `:not`, so it wins whatever the order.
2129 let _ = writeln!(
2130 css,
2131 "[data-awaiting=\"determinate\"][aria-busy=\"true\"]:not([data-awaiting-watched])::after {{\n \
2132 content: attr(data-awaiting-amount);\n \
2133 inline-size: auto;\n \
2134 block-size: auto;\n \
2135 outline: none;\n \
2136 color: var(--content-muted);\n \
2137 padding-inline-start: calc(var(--awaiting-mark, 0.5em) + var(--awaiting-gap, 0.5ch));\n \
2138 background: linear-gradient(var(--action), var(--action)) no-repeat \
2139 left center / var(--awaiting-mark, 0.5em) var(--awaiting-mark, 0.5em);\n \
2140 animation: makeover-activity-beside calc(var(--cadence-activity) * 2) \
2141 step-end infinite;\n\
2142 }}"
2143 );
2144
2145 // Right to left, the fill grows from the right and the mark sits there.
2146 let _ = writeln!(
2147 css,
2148 "[data-awaiting=\"determinate\"][aria-busy=\"true\"][data-awaiting-watched]:dir(rtl)::after {{\n \
2149 background: linear-gradient(\n \
2150 to left,\n \
2151 var(--action) 0 calc(var(--awaiting-share, 0) * 100%),\n \
2152 var(--surface-sunken) 0\n \
2153 );\n\
2154 }}\n\
2155 [data-awaiting=\"determinate\"][aria-busy=\"true\"]:not([data-awaiting-watched]):dir(rtl)::after {{\n \
2156 background-position: right center;\n\
2157 }}"
2158 );
2159
2160 css
2161}
2162
2163/// A strip of figures, and the two spans inside each one.
2164///
2165/// Colour only, which is the deferral rule applied to a component that badly
2166/// wants to break it. A figure reads as a figure because the value is set large
2167/// over a small caption, and that is a size: `makeover-geometry` answers how
2168/// much space and this crate answers what the thing is. Emitting `font-size`
2169/// here would be this crate naming a value, which is the one thing it is defined
2170/// by not doing, and `progress_rules` is the precedent, it emits the tones and
2171/// never the width, because the width is not its to know.
2172///
2173/// So the type scale is the app's, and what is generated is the part an app
2174/// cannot get right by itself: which of the two spans carries the tone, and,
2175/// from 0.82.0, the strip the figures sit in.
2176/// A definition list, and the two tracks that make its values line up.
2177///
2178/// **The alignment is the whole member.** Five goingson panes were saying
2179/// labelled facts as a row each, and rendered that way every value started
2180/// after its own label, so no column formed and the eye had nothing to run
2181/// down. A grid with one label track sized to the longest label is the fix, and
2182/// it is something only the set can do, which is why `Node::Facts` carries
2183/// the set rather than each pair.
2184///
2185/// `max-content` on the first track and not a fixed width: the label column is
2186/// as wide as the longest label and no wider, which is what keeps a pane of
2187/// short labels from leaving a canyon before the values.
2188///
2189/// The value takes `content` and the label reads back. goingson had that the
2190/// other way round, muted values against unmuted labels, so the part a
2191/// person came for was the quieter of the two. Same rule `figure_rules` states
2192/// for a value against its caption, and `row` for primary against meta.
2193fn facts_rules(opts: &Emit) -> String {
2194 let facts = class("facts", opts);
2195 let label = class("facts-label", opts);
2196 let value = class("facts-value", opts);
2197 let mut css = String::new();
2198
2199 let _ = writeln!(
2200 css,
2201 ".{facts} {{\n display: grid;\n grid-template-columns: max-content 1fr;\n \
2202 column-gap: var(--gap-section);\n row-gap: var(--gap-peer);\n margin: 0;\n}}"
2203 );
2204 // `dt` and `dd` both carry a browser margin that would break the tracks.
2205 let _ = writeln!(
2206 css,
2207 ".{facts} > .{label} {{\n margin: 0;\n color: var(--content-secondary);\n}}"
2208 );
2209 let _ = writeln!(
2210 css,
2211 ".{facts} > .{value} {{\n margin: 0;\n color: var(--content);\n}}"
2212 );
2213 css
2214}
2215
2216/// A picture, its frame and its caption.
2217///
2218/// # The frame is a border, and this is the one place a bevel is wrong
2219///
2220/// Emitting [`Depth::Raised`] here through [`depth_rule`], the same call
2221/// `button` and `card` make, is wrong, and MNW's landing page is where it
2222/// showed: **the frames had no visible edge at all.**
2223///
2224/// `Depth::Raised`'s edge is `--bevel-raised`, which is an *inset* shadow, a
2225/// 1px light run at the top-left and a dark one at the bottom-right, drawn
2226/// **inside** the element's box. On a button or a card that box is a surface
2227/// this crate owns, so an inset edge reads as the surface catching the light.
2228/// On a picture it is drawn on top of the picture, over whatever pixels the
2229/// image happens to have at its border. MNW's screenshots are light-on-light
2230/// parchment, so the light half landed on a light image and the frame
2231/// disappeared.
2232///
2233/// **You cannot bevel a surface you do not own.** A picture's content is the
2234/// app's, arrives at request time, and can be any colour, so its edge has to
2235/// sit *outside* the content rather than on it. That is a border.
2236///
2237/// The fill stays, and it is not decoration: it is what shows through a
2238/// transparent PNG and what stands in the frame's place while the image is
2239/// still loading.
2240///
2241/// This is a real limit on [`Depth`] rather than a special case. Every other
2242/// consumer of a depth draws its own surface; a picture is the first member
2243/// whose surface belongs to someone else.
2244///
2245/// # No size
2246///
2247/// `width: 100%` and nothing else. How large a picture is depends on the box it
2248/// was put in, which is the app's arrangement and `makeover-geometry`'s scales,
2249/// and a renderer that picked one would be answering for every consumer at
2250/// once. This is where `figure_rules` landed for the same reason.
2251fn picture_rules(opts: &Emit) -> String {
2252 let picture = class("picture", opts);
2253 let img = class("picture-img", opts);
2254 let caption = class("picture-caption", opts);
2255 let mut css = String::new();
2256
2257 // Block, or an inline image sits on the text baseline and carries a
2258 // descender's worth of space under it that no app ever wants and every app
2259 // deletes by hand. The border is the frame; see the type docs for why it is
2260 // not the bevel every other surface here gets.
2261 let _ = writeln!(
2262 css,
2263 ".{img} {{\n display: block;\n width: 100%;\n height: auto;\n \
2264 background: var(--{});\n border: {} solid var(--border);\n}}",
2265 Fill::Raised.token(),
2266 opts.border_width
2267 );
2268
2269 // The two fits that need a rule. `Fit::Natural` emits no attribute at all,
2270 // so it is the bare rule above and needs nothing here.
2271 let _ = writeln!(
2272 css,
2273 ".{img}[data-fit=\"cover\"] {{\n height: 100%;\n object-fit: cover;\n}}"
2274 );
2275 let _ = writeln!(
2276 css,
2277 ".{img}[data-fit=\"contain\"] {{\n height: 100%;\n object-fit: contain;\n}}"
2278 );
2279
2280 // A caption reads back one step, which is `figure-caption`'s answer and the
2281 // same claim: it says what the thing above it is, and it is not the thing.
2282 let _ = writeln!(
2283 css,
2284 ".{picture} > .{caption} {{\n color: var(--content-muted);\n}}"
2285 );
2286
2287 css
2288}
2289
2290/// A region showing one child at a time, and the chrome that moves between them.
2291///
2292/// [`makeover_layout::Showing`] lets a description say that a region holds
2293/// several children and shows some of them. A renderer derives its own chrome
2294/// from that, which is what stops every renderer growing a `match` on a widget
2295/// name; these are the rules the derived chrome needs.
2296///
2297/// # Why the default is every child, and the enhancement takes them away
2298///
2299/// The controls are a lie until something binds them. A prev button rendered
2300/// into a document with no script is a control that looks live and answers
2301/// nothing, and the reader it lies to is exactly the one who cannot see the
2302/// other children either, the collapsing and the moving are the same half.
2303///
2304/// So the rules run in the direction the enhancement does. Nothing here hides a
2305/// child and nothing here shows a control. Whatever binds the region sets
2306/// `data-ready` on it, and that is what collapses the stack to one and reveals
2307/// the row that moves it. A reader with no script gets every child in order and
2308/// no controls, which is more content rather than less, and a reader with
2309/// script gets a settled page rather than a stack that jumps to one frame after
2310/// load.
2311///
2312/// MNW proved this shape by hand, a `<noscript>` stylesheet opening its
2313/// carousel back out, and it is here rather than there because the property is
2314/// the description's, not one app's.
2315///
2316/// # Not spacing
2317///
2318/// The row's gaps are `makeover-geometry`'s question and are absent for
2319/// [`row_rules`]'s reason. What is here is `display`, which carries no
2320/// magnitude, and the muted readout, which is the same claim `picture-caption`
2321/// makes: it says where you are among the children and it is not one of them.
2322fn showing_rules(opts: &Emit) -> String {
2323 let controls = class("showing", opts);
2324 let position = class("showing-position", opts);
2325 let frame = class("showing-frame", opts);
2326 let mut css = String::new();
2327
2328 // Hidden until something binds it, which is the whole argument above.
2329 let _ = writeln!(css, ".{controls} {{\n display: none;\n}}");
2330 // Block, and nothing about how the three sit in it. A button and a span are
2331 // inline already, so they make a row without this crate saying so, and
2332 // saying so is where `align-items` and a gap would follow, both spacing,
2333 // both `makeover-geometry`'s, and `row_rules` refuses them for the same
2334 // reason.
2335 let _ = writeln!(
2336 css,
2337 "[data-ready] > .{controls} {{\n display: block;\n}}"
2338 );
2339
2340 // A child is in flow until the region is bound, and then only the current
2341 // one is. `.current` is a modifier for the reason `.chosen` and `.latched`
2342 // are: one name for the state, set by whoever knows it.
2343 let _ = writeln!(
2344 css,
2345 "[data-ready] > .{frame}:not(.current) {{\n display: none;\n}}"
2346 );
2347
2348 // Reads back one step. `picture-caption`'s rule and its reason.
2349 let _ = writeln!(css, ".{position} {{\n color: var(--content-muted);\n}}");
2350
2351 css
2352}
2353
2354/// A time axis: the container, its gridlines and ruler, and the placed things.
2355///
2356/// [`Track`](makeover_layout::Track), the one member here whose whole point is
2357/// *position*. That makes the magnitude line this crate keeps worth restating
2358/// rather than assuming.
2359///
2360/// # Where the numbers come from
2361///
2362/// Every value that varies per item is a custom property the caller sets
2363/// inline, and every rule here reads one. `--track-at` and `--track-for` are
2364/// percentages of the span, which
2365/// [`Track::fraction`](makeover_layout::Track::fraction) computes once so three
2366/// renderers cannot disagree about it. Nothing here knows a pixel.
2367///
2368/// That is what lets the stylesheet stay static while the items move: an entry
2369/// carries `--track-at: 37.5%; --track-for: 4.166%` in [`VARS_ATTR`] and the rule below
2370/// turns it into a box. The alternative was emitting a rule per item, which is
2371/// a stylesheet that grows with the data.
2372///
2373/// **The height of the track is the app's**, not this crate's. 96 quarter-hour
2374/// slots at some slot height is a size, and a size is `makeover-geometry`'s
2375/// question, the same refusal `figure_rules` and `placeholder_rules` make.
2376/// Percentages need a resolved height above them, so `.track` gets
2377/// `position: relative` and nothing else; the app says how tall a day is.
2378///
2379/// # Overlap
2380///
2381/// Two things at the same time is intrinsic to an axis and has no analogue in a
2382/// list. The description does not declare it, `Placement::overlaps` derives it
2383/// from the times, so what arrives here is a lane index and a lane count, and
2384/// the rule divides the width. A renderer that would rather stack them ignores
2385/// both properties and the defaults give it one full-width lane.
2386fn track_rules(opts: &Emit) -> String {
2387 let track = class("track", opts);
2388 let slot = class("track-slot", opts);
2389 let tick = class("track-tick", opts);
2390 let entry = class("track-entry", opts);
2391 let mut css = String::new();
2392
2393 // The positioning context every entry resolves against, and the whole of
2394 // what this crate says about the container. No height: see the doc above.
2395 let _ = writeln!(css, ".{track} {{\n position: relative;\n}}");
2396
2397 // Gridlines and the ruler are the axis reading itself back, which is
2398 // `picture-caption` and `showing-position`'s claim: about the thing rather
2399 // than one of the things.
2400 //
2401 // `border_width` rather than a literal, the way `depth_rule` writes its
2402 // edge. A gridline is the one place a timeline would most naturally reach
2403 // for a hardcoded 1px, and a hardcoded 1px is this crate naming a size.
2404 let _ = writeln!(
2405 css,
2406 ".{slot} {{\n border-top: {} solid var(--border);\n}}",
2407 opts.border_width
2408 );
2409 let _ = writeln!(css, ".{tick} {{\n color: var(--content-muted);\n}}");
2410
2411 // The one rule that does real work. Top and height are the placement;
2412 // left and width are the lane. Both lane properties default so an entry
2413 // that names neither is full width, which is the common case and the one a
2414 // renderer gets for free.
2415 let _ = writeln!(
2416 css,
2417 ".{entry} {{\n \
2418 position: absolute;\n \
2419 top: var(--track-at, 0%);\n \
2420 height: var(--track-for, 100%);\n \
2421 left: calc(var(--track-lane, 0) / var(--track-lanes, 1) * 100%);\n \
2422 width: calc(100% / var(--track-lanes, 1));\n\
2423 }}"
2424 );
2425
2426 css
2427}
2428
2429/// A region's stand-in, and the header of a table that can be reordered.
2430///
2431/// Both are colour and affordance only, the same place `figure_rules` lands:
2432/// emitting a type scale is not this crate's. How much room
2433/// a stand-in gets is a size, goingson has the same one at three, as
2434/// `--compact`, `--dashboard` and `--padded`, and a size is
2435/// `makeover-geometry`'s question.
2436///
2437/// The caret is the one thing here that is neither colour nor affordance, and it
2438/// is a renderer's own expression rather than a value the description named:
2439/// `aria-sort` is what the table actually says, and this turns it into something
2440/// visible for everyone not using a screen reader. A terminal draws its own; an
2441/// immediate-mode painter draws its own.
2442fn state_rules(opts: &Emit) -> String {
2443 let placeholder = class("placeholder", opts);
2444 let text = class("placeholder-text", opts);
2445 let heading = class("table-heading", opts);
2446 let mut css = String::new();
2447
2448 // An empty stand-in is a slot with nothing in it yet, and it draws as one:
2449 // a box on the page's own ground with a dashed edge from the neutral ramp.
2450 // A muted sentence loose on the page read as a stray line, and the way
2451 // out beneath it as an unrelated control; inside the box they read as one
2452 // thing that says what will be here and how to put it there. A waiting
2453 // stand-in keeps its sunken ground (below), so the two states stay apart.
2454 let _ = writeln!(
2455 css,
2456 ".{placeholder}:not([data-state=\"pending\"]) {{\n \
2457 border: 1px dashed var(--border);\n border-radius: var(--radius-fine);\n \
2458 padding: var(--gap-section);\n}}"
2459 );
2460 // A stand-in's sentence wraps at the reading measure rather than running
2461 // the pane's width: goingson's Problems empty state was 172 characters on
2462 // one line at 1440. The token is quasi-webview's, the one a screen's
2463 // `Measure::Reading` already answers to, and the fallback is the value it
2464 // falls back to, so a page that sets neither still gets a line that reads.
2465 let _ = writeln!(
2466 css,
2467 ".{placeholder} > .{text} {{\n max-inline-size: var(--measure-reading, 42rem);\n \
2468 color: var(--content-muted);\n}}"
2469 );
2470 // Only the failure is toned. An empty list is the normal state of a new
2471 // install, and `Readiness::tone` is what says so. The tone is an edge and
2472 // the sentence takes content ink, a step up from the muted one an empty
2473 // stand-in reads in: a failure is read, and a status colour is never the
2474 // colour of words (wiki `quasi-vocabulary-findings`).
2475 let _ = writeln!(
2476 css,
2477 ".{placeholder}[data-tone=\"{0}\"] > .{text} {{\n color: var(--content);\n{1}}}",
2478 Tone::Danger.token(),
2479 status_edge(opts.focus_width, Tone::Danger.token())
2480 );
2481 // A stand-in that is waiting draws on a sunken ground, so it does not
2482 // read as one that is empty: both say a sentence where content will be,
2483 // and only the ground says whether anything is coming. A step of the
2484 // neutral ramp rather than a tone, since waiting is not a status. The
2485 // sentence carries the same news to a screen reader through the region's
2486 // own `aria-busy`. The inset is a gap step, so the ground reads as a
2487 // ground rather than a highlight under the words.
2488 let _ = writeln!(
2489 css,
2490 ".{placeholder}[data-state=\"pending\"] {{\n background: var(--surface-sunken);\n \
2491 padding: var(--gap-bound) var(--gap-peer);\n \
2492 border-radius: var(--radius-fine);\n}}"
2493 );
2494 // A sentence that carries a status draws an edge in that status, the way
2495 // a figure does, and keeps its ink. A bare sentence was the one member
2496 // that accepted a tone and drew none of it; drawing the words in the tone
2497 // is what a figure's numbers measured at 1.24:1 to 2.27:1, and a
2498 // sentence is read the same way. Same edge and inset as the figure's.
2499 let sentence = class("text", opts);
2500 tone_rules(&mut css, &format!(".{sentence}"), |tone| {
2501 status_edge(opts.focus_width, tone)
2502 });
2503 // A sentence at a measure band sits on that band's step of the neutral
2504 // ramp, sized to its words so the band reads as the value's and not the
2505 // line's. Band 0 is the ground and draws nothing.
2506 for band in 1..makeover_layout::HEAT_BANDS {
2507 let heat = makeover_layout::Heat(band).token();
2508 let _ = writeln!(
2509 css,
2510 ".{sentence}[data-heat=\"{heat}\"] {{\n background: var(--{heat});\n \
2511 inline-size: fit-content;\n \
2512 padding-inline: var(--step-snug);\n \
2513 border-radius: var(--radius-fine);\n}}"
2514 );
2515 }
2516 // The way out stands a group apart from the sentence it answers. A gap
2517 // step rather than a size: how much room the stand-in gets is still the
2518 // app's.
2519 let _ = writeln!(
2520 css,
2521 ".{placeholder} > .{} {{\n margin-block-start: var(--gap-group);\n}}",
2522 class("placeholder-action", opts)
2523 );
2524
2525 // A header that reorders the table is a control, and the pointer is the
2526 // only part of saying so that is not the app's own type and spacing.
2527 let _ = writeln!(
2528 css,
2529 ".{heading}[data-sortable] {{\n cursor: pointer;\n}}"
2530 );
2531 // The caret carries its own leading space, the way `makeover-tui` and
2532 // `makeover-immediate` both write `" \u{25B2}"`. An app adding the gap
2533 // itself would do it the obvious way, as `content`, and app CSS outranks
2534 // this crate's cascade layer, so it would win over the glyph and leave the
2535 // heading with no caret at all. With the space emitted here there is
2536 // nothing left for one to add.
2537 //
2538 // Three states, three tones, on the convention in wiki
2539 // `three-tone-convention`. A column in force is `content`; a column offering
2540 // to reorder and not doing it now is `content-secondary`, because it still
2541 // answers a press; a column that is not sortable emits no caret at all and
2542 // takes nothing. The idle arm draws its glyph rather than hiding it and
2543 // reserving the box, so there is no reservation to get right.
2544 //
2545 // The glyph is `Sort::glyph`, escaped rather than written: a CSS `content`
2546 // string cannot carry the character literally through this file's own
2547 // escaping, and spelling it here as well would put the third copy back that
2548 // `makeover-layout` 0.27.5 exists to remove.
2549 //
2550 // On the heading's `.cell-in`, so the caret sits beside the label inside
2551 // its padding rather than at the far edge of a column that grew.
2552 let cell_in = class("cell-in", opts);
2553 let _ = writeln!(
2554 css,
2555 ".{heading}[data-sortable] > .{cell_in}::after \
2556 {{\n content: \" {}\";\n color: var(--content-secondary);\n}}",
2557 css_escape(Sort::Ascending.glyph())
2558 );
2559 for direction in [Sort::Ascending, Sort::Descending] {
2560 let _ = writeln!(
2561 css,
2562 ".{heading}[aria-sort=\"{}\"] > .{cell_in}::after \
2563 {{\n content: \" {}\";\n color: var(--content);\n}}",
2564 direction.as_str(),
2565 css_escape(direction.glyph())
2566 );
2567 }
2568 css
2569}
2570
2571/// The component layer: every named thing phase A emits.
2572///
2573/// No scrollbar track. It was on the phase A list and came off: eight lines of
2574/// `::-webkit-scrollbar` with no shape a terminal or an immediate-mode painter
2575/// would want handed to it, so it stays with the apps.
2576#[must_use]
2577pub fn component_rules(opts: &Emit) -> String {
2578 let mut css = String::new();
2579 css.push_str(&surface_rules(opts));
2580 css.push_str(&link_rules(opts));
2581 css.push_str(&token_rules(opts));
2582 css.push_str(&selector_rules(opts));
2583 css.push_str(&row_rules(opts));
2584 css.push_str(&run_rules(opts));
2585 css.push_str(&meter::progress_rules(opts));
2586 css.push_str(&chart::rules(opts));
2587 css.push_str(&awaiting_rules(opts));
2588 css.push_str(&figure::figure_rules(opts));
2589 css.push_str(&facts_rules(opts));
2590 css.push_str(&picture_rules(opts));
2591 css.push_str(&showing_rules(opts));
2592 css.push_str(&track_rules(opts));
2593 css.push_str(&state_rules(opts));
2594 css.push_str(&table_rules(opts));
2595 css.push_str(&facet::facet_rules(opts));
2596 css.push_str(&form::group_rules(opts));
2597 css.push_str(&form::editor_rules(opts));
2598 css.push_str(&form::suggestion_rules(opts));
2599 css.push_str(&form::unit_rules(opts));
2600 css.push_str(&form::option_detail_rules(opts));
2601 css.push_str(&form::note_rules(opts));
2602 css.push_str(&banner_rules(opts));
2603 css.push_str(&toast_rules(opts));
2604 css.push_str(&leaving_rules());
2605 css
2606}
2607
2608/// A notice that leaves on its own, floating over the page.
2609///
2610/// Its look is this crate's and where it floats is the host's: a toast takes
2611/// [`Notice::Toast`]'s fill, the control edge, the overlay cast and the notice
2612/// layer, and no position, because a window and a phone put it in different
2613/// places. A toned toast is the banner's answer: the tone's surface under the
2614/// theme's own ink, edged in the tone.
2615fn toast_rules(opts: &Emit) -> String {
2616 let toast = class("toast", opts);
2617 let mut css = String::new();
2618 let _ = writeln!(
2619 css,
2620 ".{toast} {{\n background: var(--{});\n color: var(--content);\n \
2621 border: var(--edge-control);\n box-shadow: var(--elevation-overlay);\n \
2622 padding: var(--gap-peer) var(--gap-group);\n z-index: var(--layer-notice);\n}}",
2623 makeover_layout::Notice::Toast.fill().token()
2624 );
2625 tone_rules(&mut css, &format!(".{toast}"), toned_surface);
2626 css
2627}
2628
2629/// A notice that stays until dealt with, across whatever it is about.
2630///
2631/// A banner holds a sentence someone has to read, so it is left-aligned and its
2632/// words stop at the reading measure while its ground keeps the width of the
2633/// box it was put in. The words are a bare text node beside an optional act, so
2634/// the measure is the far padding rather than a cap on a child: what is left of
2635/// the box past the measure, or the ordinary inset once the box is narrower
2636/// than that.
2637///
2638/// A status is the chip's answer: `*-surface` under the theme's own ink, edged
2639/// in the tone. A status colour is never the colour of words.
2640fn banner_rules(opts: &Emit) -> String {
2641 let banner = class("banner", opts);
2642 let mut css = String::new();
2643 let _ = writeln!(
2644 css,
2645 ".{banner} {{\n padding-block: var(--gap-peer);\n \
2646 padding-inline-start: var(--gap-section);\n \
2647 padding-inline-end: max(var(--gap-section), 100% - var(--measure-reading, 42rem));\n \
2648 border-inline-start: {} solid var(--border);\n \
2649 color: var(--content);\n text-align: start;\n}}",
2650 opts.focus_width
2651 );
2652 tone_rules(&mut css, &format!(".{banner}"), |tone| {
2653 format!(
2654 " background: var(--{tone}-surface);\n border-inline-start-color: var(--{tone});\n"
2655 )
2656 });
2657 css
2658}
2659
2660/// How a transient notice goes away.
2661///
2662/// `makeover-timing` says that `Intent::Dismiss` is how long a notice lives
2663/// *before it starts to leave*, and that the leaving itself is `Motion::Fade`.
2664/// The `build` module writes `--motion-fade` into every consumer's `timing.css`,
2665/// and this is the rule that reads it. Removing the node the moment the dismiss
2666/// is up skips the leaving entirely.
2667///
2668/// # Why an attribute and not a class
2669///
2670/// [`Emit`]'s prefix moves every class this crate writes, so a class here would
2671/// have to be resolved through `class()` by whoever sets it, and the party
2672/// setting it is a script, which has no prefix to hand. `data-leaving` is
2673/// outside that namespace, so a renderer can set it from JavaScript with no
2674/// coordination.
2675///
2676/// The transition sits on the notice and the opacity on the leaving state, so
2677/// the element is transitionable before the attribute arrives; a transition
2678/// declared in the same rule as the value it changes has nothing to animate
2679/// from.
2680///
2681/// # Reduced motion is handled by the token, not by a second rule here
2682///
2683/// `timing.css` already zeroes `--motion-fade` under `prefers-reduced-motion`.
2684/// The reader who asked for less motion gets an instant change rather than a
2685/// fade, and the renderer that sets the attribute must still remove the node on
2686/// a timer rather than on `transitionend`, a zero-length transition may fire
2687/// no event at all, and a node waiting on one that never comes stays forever.
2688///
2689/// The fallback is `0ms` and not a guessed duration: a page with no timing
2690/// sheet has not opted into this vocabulary, and the honest answer there is the
2691/// behaviour it had before, which is the notice going away at once.
2692fn leaving_rules() -> String {
2693 let mut css = String::new();
2694 let _ = writeln!(
2695 css,
2696 "[data-notice] {{\n transition: opacity var(--motion-fade, 0ms) \
2697 ease-out;\n}}"
2698 );
2699 let _ = writeln!(css, "[data-notice][data-leaving] {{\n opacity: 0;\n}}");
2700 css
2701}
2702
2703/// The ink a native control draws its tick, dot and fill in.
2704///
2705/// A checkbox, a radio, a range and a `<progress>` are drawn by the browser,
2706/// and without this they draw in its own blue against a themed page: every
2707/// tick in goingson (Notifications, row selection, the All day box) was
2708/// user-agent blue in both themes. `accent-color` is inherited, so one
2709/// declaration on `:root` reaches every native control in the document,
2710/// including the ones no emitter here wrote, such as an app's own row-select
2711/// box. `--content`, not `--action`: a tick is a state mark, and the accent is
2712/// reserved for the primary action (accent-as-state ruling).
2713///
2714/// The browser picks the tick's own colour against that ink for contrast, so
2715/// `--content-on-action` has nothing to do here.
2716const NATIVE_ACCENT: &str = " accent-color: var(--content);\n";
2717
2718/// The whole phase-A stylesheet: properties, depth rules and components, in
2719/// [`CSS_LAYER`], under a generated-file banner.
2720///
2721/// The banner sits outside the layer, because a comment participates in no
2722/// cascade and a reader opening the file should see what it is before seeing
2723/// an at-rule.
2724#[must_use]
2725pub fn stylesheet(opts: &Emit) -> String {
2726 let body = in_css_layer(&format!(
2727 ":root {{\n{}{NATIVE_ACCENT}}}\n\n{}\n{}",
2728 bevel_properties(opts),
2729 depth_rules(opts),
2730 component_rules(opts)
2731 ));
2732 // Counted from the body rather than through `vocabulary::names`, which
2733 // calls back into here.
2734 let classes = vocabulary::classes_in_css(&body).len();
2735 let version = VERSION;
2736 format!(
2737 "/* Generated by makeover-webview {version} from makeover-layout, \
2738 {classes} classes.\n \
2739 Do not edit. The version and the count are here because a stale\n \
2740 lockfile fails silently: an older emitter writes a well-formed sheet\n \
2741 with components missing, and nothing else in the file says so. If\n \
2742 this version trails what the manifest asks for, re-resolve.\n\n \
2743 Depth is a fill and an edge together; naming them apart is what let\n \
2744 them disagree. See the crate's README and wiki note makeover-layout.\n\n \
2745 Everything below is in the `{CSS_LAYER}` cascade layer. Declare the\n \
2746 order once in your own stylesheet, or this layer's position is decided\n \
2747 by whichever generated file the browser happens to see first:\n\n \
2748 @layer {CSS_LAYER}, base, components, responsive; */\n{body}"
2749 )
2750}
2751
2752#[cfg(test)]
2753mod test_support;
2754#[cfg(test)]
2755mod tests;