use axum::{
Router,
body::Bytes,
extract::State,
http::{HeaderMap, HeaderValue, header},
response::IntoResponse,
routing::get,
};
use super::SessionToken;
const INDEX: &str = include_str!("../../web/index.html");
const SCRIPT: &str = include_str!("../../web/app.js");
const ACTIONS: &str = include_str!("../../web/actions.js");
const STYLE: &str = include_str!("../../web/style.css");
const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; \
img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
pub(super) fn routes<S: Clone + Send + Sync + 'static>(
port: u16,
token: &SessionToken,
) -> Router<S> {
Router::new()
.route("/", get(index))
.route("/app.js", get(script))
.route("/actions.js", get(actions))
.route("/style.css", get(style))
.with_state(Bytes::from(render_index(token.as_str(), port)))
}
fn render_index(token: &str, port: u16) -> String {
let mut escaped = String::with_capacity(token.len());
for character in token.chars() {
match character {
'&' => escaped.push_str("&"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
_ => escaped.push(character),
}
}
INDEX
.replace("{{TROLL_PORT}}", &port.to_string())
.replace("{{TROLL_VERSION}}", env!("CARGO_PKG_VERSION"))
.replace("{{TROLL_TOKEN}}", &escaped)
}
async fn index(State(page): State<Bytes>) -> impl IntoResponse {
(
[
(header::CONTENT_TYPE, "text/html; charset=utf-8"),
(header::CACHE_CONTROL, "no-store"),
],
page,
)
}
async fn script() -> impl IntoResponse {
javascript(SCRIPT)
}
async fn actions() -> impl IntoResponse {
javascript(ACTIONS)
}
fn javascript(source: &'static str) -> impl IntoResponse {
(
[(header::CONTENT_TYPE, "text/javascript; charset=utf-8")],
source,
)
}
async fn style() -> impl IntoResponse {
([(header::CONTENT_TYPE, "text/css; charset=utf-8")], STYLE)
}
pub(super) fn apply_browser_headers(headers: &mut HeaderMap) {
for (name, value) in [
(header::CONTENT_SECURITY_POLICY, CSP),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
(header::X_FRAME_OPTIONS, "DENY"),
] {
headers.insert(name, HeaderValue::from_static(value));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn field_hints_and_drift_ink_match_their_markup() {
assert!(STYLE.contains(".field :is(.small, small), .component-list legend + p { font-weight: 400; color: var(--muted); }"));
assert!(ACTIONS.contains("element(\"small\", options.hint)"));
assert!(!INDEX.contains("expire-ink"));
assert!(!INDEX.contains("conflict-ink"));
assert!(SCRIPT.contains("if (ink) count.classList.toggle(ink, Boolean(snapshot && snapshot.drift.counts[key] > 0));"));
}
#[test]
fn console_controls_are_wired_to_scripts() {
for id in ["listener-filter", "refresh-now", "theme-picker", "density"] {
assert!(
INDEX.contains(&format!("id=\"{id}\"")),
"missing {id} markup"
);
let reference = format!("\"{id}\"");
assert!(
SCRIPT.contains(&reference) || ACTIONS.contains(&reference),
"missing {id} script reference"
);
}
}
#[test]
fn registry_derived_ids_cannot_repeat_a_static_id() {
let prefixes = [
("permanent-port-", "`${tier}-port-${"),
("lease-port-", "`${tier}-port-${"),
("unregistered-socket-", "`unregistered-socket-${"),
("zone-row-", "`zone-row-${"),
("app-group-", "`app-group-${"),
("stack-group-", "`stack-group-${"),
("apps-project-", "`apps-project-${"),
("apps-claims-", "`apps-claims-${"),
("apps-leases-", "`apps-leases-${"),
("history-row-", "`history-row-${"),
("field-", "`field-${"),
];
for (_, source) in prefixes {
assert!(
SCRIPT.contains(source) || ACTIONS.contains(source),
"missing ID builder {source}"
);
}
let ids: Vec<_> = INDEX
.split(" id=\"")
.skip(1)
.map(|rest| rest.split_once('"').expect("unterminated id").0)
.collect();
assert!(ids.contains(&"project-rows"), "static IDs not found");
for id in ids {
for (prefix, _) in prefixes {
assert!(
!id.starts_with(prefix),
"static ID {id} starts with the dynamic prefix {prefix}"
);
}
}
}
#[test]
fn browser_storage_holds_only_display_preferences() {
let mut calls = 0;
for (asset, source) in [("app.js", SCRIPT), ("actions.js", ACTIONS)] {
let script: String = source.chars().filter(|ch| !ch.is_whitespace()).collect();
assert!(
!script.contains("sessionStorage"),
"{asset} uses sessionStorage"
);
for call in script.split("localStorage").skip(1) {
calls += 1;
assert!(
[
".getItem(THEME_KEY)",
".setItem(THEME_KEY,theme)",
".removeItem(THEME_KEY)",
".getItem(DENSITY_KEY)",
".setItem(DENSITY_KEY,density)",
]
.iter()
.any(|allowed| call.starts_with(allowed)),
"{asset} uses localStorage outside the display preferences: {}",
&call[..call.len().min(40)],
);
}
}
assert_eq!(calls, 5, "expected the theme and density storage calls");
assert!(SCRIPT.contains(r#"const THEME_KEY = "troll.console.theme";"#));
assert!(SCRIPT.contains(r#"const DENSITY_KEY = "troll.console.density";"#));
assert!(SCRIPT.contains(r#"const DENSITIES = new Set(["cards", "list"]);"#));
}
#[test]
fn page_inserts_and_escapes_the_meta_token() {
let html = render_index("ab0123", 8123);
assert!(html.contains(r#"<meta name="troll-token" content="ab0123">"#));
assert!(html.contains("127.0.0.1:8123"));
assert!(html.contains(concat!("v", env!("CARGO_PKG_VERSION"))));
assert!(!html.contains("{{TROLL_"));
let html = render_index(r#"a"'><&"#, 8123);
assert!(html.contains(r#"<meta name="troll-token" content="a"'><&">"#));
}
#[test]
fn embedded_page_uses_only_local_assets_and_safe_dom_apis() {
for (asset, source) in [("app.js", SCRIPT), ("actions.js", ACTIONS)] {
let script: String = source.chars().filter(|ch| !ch.is_whitespace()).collect();
for forbidden in [
"innerHTML",
"outerHTML",
"insertAdjacentHTML",
"document.write",
r#"document["write"#,
"document['write",
"document[`write",
"newFunction",
"alert(",
"confirm(",
"prompt(",
] {
assert!(!script.contains(forbidden), "{asset} contains {forbidden}");
}
for name in source.split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) {
assert_ne!(name, "eval", "{asset} contains eval");
}
for timer in ["setTimeout(", "setInterval("] {
for arguments in script.split(timer).skip(1) {
let arguments = arguments.trim_start_matches('(');
assert!(
!arguments.starts_with(['\'', '"', '`']),
"{asset} passes a string to {timer}",
);
}
}
}
let css: String = STYLE
.to_ascii_lowercase()
.chars()
.filter(|ch| !ch.is_whitespace())
.collect();
assert!(!css.contains("@import"), "style.css imports a resource");
for arguments in css.split("url(").skip(1) {
assert!(
!arguments
.trim_start_matches(['\'', '"'])
.starts_with("http"),
"style.css contains a remote resource URL",
);
}
let html = INDEX.to_ascii_lowercase();
for protocol in ["http:", "https:"] {
assert!(!html.contains(protocol), "index.html contains {protocol}");
}
let icons: Vec<_> = html.split("<link rel=\"icon\"").skip(1).collect();
assert!(!icons.is_empty(), "missing favicon link");
for icon in icons {
let (attributes, _) = icon.split_once('>').expect("unterminated icon link");
assert!(
attributes
.split_whitespace()
.any(|attr| attr.starts_with("href=\"data:")),
"favicon must use a data URL"
);
}
assert!(!html.contains("<style"));
for (index, _) in html.match_indices("style") {
let (before, after) = html.split_at(index);
assert!(
!(before.ends_with(char::is_whitespace)
&& after["style".len()..].trim_start().starts_with('=')),
"found an inline style attribute"
);
}
for (index, _) in html.match_indices("on") {
let (before, after) = html.split_at(index);
let name_len = after
.find(|c: char| c.is_whitespace() || "=/>\"'<".contains(c))
.unwrap_or(after.len());
assert!(
!(before.ends_with(char::is_whitespace)
&& after[name_len..].trim_start().starts_with('=')),
"found an HTML event-handler attribute"
);
}
let mut scripts = html.split("<script").skip(1);
for expected in ["/app.js", "/actions.js"] {
let script = scripts.next().expect("missing external script");
let (attributes, rest) = script.split_once('>').unwrap();
let (body, _) = rest.split_once("</script>").unwrap();
assert_eq!(attributes.trim(), format!(r#"src="{expected}" defer"#));
assert!(body.trim().is_empty(), "found inline script content");
}
assert!(scripts.next().is_none(), "found an unexpected script tag");
}
}
#[cfg(test)]
mod palettes {
use std::{collections::BTreeMap, fmt::Write};
use super::STYLE;
const THEMES: [(&str, &str); 6] = [
("slate", "dark"),
("graphite", "dark"),
("harbor", "dark"),
("daylight", "light"),
("meridian", "light"),
("parchment", "light"),
];
const SYSTEM_DARK: &str = "system dark";
const TOKENS: &[&str] = &[
"canvas",
"surface",
"band",
"soft",
"highlight",
"text",
"muted",
"rule",
"control",
"button",
"press",
"accent",
"accent-line",
"accent-fill",
"accent-text",
"accent-hover",
"accent-soft",
"live",
"live-bg",
"live-line",
"quiet",
"quiet-bg",
"warning",
"warning-bg",
"danger",
"danger-bg",
"danger-line",
"dFill",
"dFillInk",
"focus",
"chip-a",
"chip-b",
"chip-line",
"chip-ink",
"mark-top",
"mark-front",
"mark-side",
];
const TEXT_MINIMUM: f64 = 4.5;
const NON_TEXT_MINIMUM: f64 = 3.0;
struct Pair {
ink: &'static str,
ground: &'static str,
use_: &'static str,
minimum: f64,
}
const fn text(ink: &'static str, ground: &'static str, use_: &'static str) -> Pair {
Pair {
ink,
ground,
use_,
minimum: TEXT_MINIMUM,
}
}
const fn edge(ink: &'static str, ground: &'static str, use_: &'static str) -> Pair {
Pair {
ink,
ground,
use_,
minimum: NON_TEXT_MINIMUM,
}
}
const PAIRS: &[Pair] = &[
text("text", "surface", "Cards, inputs, dialogs and tooltips"),
text("text", "canvas", "Page headings and body"),
text("text", "band", "Insets, groups and hovered metrics"),
text("text", "soft", "Neutral button hover and read-only fields"),
text("text", "button", "Neutral buttons and selects"),
text("text", "accent-soft", "Pressed metrics and matched rows"),
text("muted", "surface", "Hints, binds and row notes"),
text("muted", "canvas", "Toolbar labels and sweep hint"),
text("muted", "band", "Headers, insets and metric hover"),
text("muted", "soft", "Disabled buttons"),
text("muted", "accent-soft", "Pressed labels and matched rows"),
text("accent", "surface", "Links and dialog summary"),
text("accent", "canvas", "Links on the page"),
text("accent", "accent-soft", "Links in matched rows"),
text("accent", "soft", "Hovered Open link"),
text(
"accent-text",
"accent-fill",
"Primary, pressed layout and current screen",
),
text(
"accent-text",
"accent-hover",
"Hovered primary, layout and screen",
),
text("warning", "surface", "Positive expiry counts"),
text("warning", "band", "Hovered expiry counts"),
text("warning", "accent-soft", "Pressed expiry counts"),
text("danger", "surface", "Positive conflict counts"),
text("danger", "band", "Hovered conflict counts"),
text("danger", "accent-soft", "Pressed conflict counts"),
text("danger", "button", "Release or removal opener"),
text("danger", "danger-bg", "Release hover, errors and pills"),
text("dFillInk", "dFill", "Destructive confirmation states"),
text("chip-ink", "chip-a", "Port chips and project marks"),
text("live", "live-bg", "Listening pills"),
text("quiet", "quiet-bg", "Silent and unknown pills"),
text("warning", "warning-bg", "Warning pills, banners and insets"),
edge("control", "canvas", "Control edge on the page"),
edge("control", "surface", "Control edge on a card or dialog"),
edge("control", "band", "Edge on a header or inset"),
edge("control", "soft", "Hover and read-only edge"),
edge("control", "button", "Resting button edge"),
edge("control", "accent-fill", "Resting primary edge"),
edge("control", "accent-soft", "Edge in a matched row"),
edge("control", "danger-bg", "Error banner and danger edge"),
edge("control", "warning-bg", "Warning banner or inset edge"),
edge("accent", "band", "Lease meter fill on its track"),
edge("warning", "band", "Warm lease meter fill on its track"),
edge(
"accent-text",
"canvas",
"Hovered primary, layout and screen edge",
),
edge(
"accent-text",
"surface",
"Hovered primary edge on a card or dialog",
),
edge("live", "surface", "Success banner indicator"),
edge("focus", "canvas", "Focus on the page"),
edge("focus", "surface", "Focus on a card or dialog"),
edge("focus", "band", "Focus on a header or inset"),
edge("focus", "accent-soft", "Focus within a matched row"),
edge("focus", "danger-bg", "Focus in an error banner"),
edge("focus", "warning-bg", "Focus in a warning banner or inset"),
];
type Rgb = [u8; 3];
fn rgb(value: &str) -> Option<Rgb> {
let hex = value.strip_prefix('#')?;
if !matches!(hex.len(), 3 | 6) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let width = hex.len() / 3;
Some(std::array::from_fn(|index| {
let digits = &hex[index * width..(index + 1) * width];
let channel = u8::from_str_radix(digits, 16).expect("validated hex digits");
if width == 1 { channel * 17 } else { channel }
}))
}
fn luminance(rgb: Rgb) -> f64 {
let [r, g, b] = rgb.map(|channel| {
let c = f64::from(channel) / 255.0;
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
});
0.2126 * r + 0.7152 * g + 0.0722 * b
}
#[derive(Debug, Default)]
struct Palette {
line: usize,
scheme_seen: bool,
colors: BTreeMap<String, Rgb>,
}
impl Palette {
fn ratio(&self, pair: &Pair) -> f64 {
let a = luminance(self.colors[pair.ink]);
let b = luminance(self.colors[pair.ground]);
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
}
type Palettes = BTreeMap<&'static str, Palette>;
struct CssItem {
text: String,
line: usize,
end: char,
}
fn ends_with_url_identifier(text: &str) -> bool {
let Some(name) = text.as_bytes().last_chunk::<3>() else {
return false;
};
name.eq_ignore_ascii_case(b"url")
&& !text[..text.len() - name.len()].ends_with(|ch: char| {
ch.is_ascii_alphanumeric()
|| !ch.is_ascii()
|| matches!(ch, '-' | '_' | '#' | '@' | '\0')
})
}
fn css_items(css: &str) -> Result<Vec<CssItem>, String> {
let mut items = Vec::new();
let mut chars = css.chars().peekable();
let mut pending = String::new();
let mut groups = Vec::new();
let mut quote = None;
let mut line = 1;
let mut start = 1;
while let Some(ch) = chars.next() {
if ch == '\\' {
return Err(format!(
"line {line}: CSS escapes are outside the palette format"
));
}
if quote.is_none() && ch == '/' && chars.peek() == Some(&'*') {
chars.next();
let mut closed = false;
while let Some(comment) = chars.next() {
if comment == '\n' {
line += 1;
} else if comment == '*' && chars.peek() == Some(&'/') {
chars.next();
closed = true;
break;
}
}
if !closed {
return Err(format!("line {line}: unclosed CSS comment"));
}
pending.push(' ');
continue;
}
if pending.trim_ascii().is_empty() && !ch.is_ascii_whitespace() {
start = line;
}
if let Some(delimiter) = quote {
if ch == delimiter {
quote = None;
} else if matches!(ch, '\n' | '\r' | '\x0c') {
return Err(format!("line {line}: newline in CSS string"));
}
} else {
match ch {
'\'' | '"' => quote = Some(ch),
'<' if chars.clone().take(3).eq("!--".chars()) => {
return Err(format!(
"line {line}: HTML comment tokens are outside the palette format"
));
}
'>' if pending.ends_with("--") => {
return Err(format!(
"line {line}: HTML comment tokens are outside the palette format"
));
}
'(' if ends_with_url_identifier(&pending)
&& !matches!(
chars.clone().find(|next| !next.is_ascii_whitespace()),
Some('\'' | '"')
) =>
{
return Err(format!(
"line {line}: unquoted url() is outside the palette format"
));
}
'(' => groups.push(')'),
'[' => groups.push(']'),
')' | ']' => {
if groups.pop() != Some(ch) {
return Err(format!("line {line}: unbalanced CSS delimiter {ch}"));
}
}
'{' | '}' | ';' if groups.is_empty() => {
items.push(CssItem {
text: std::mem::take(&mut pending),
line: start,
end: ch,
});
continue;
}
'{' | '}' => {
return Err(format!(
"line {line}: unexpected CSS delimiter {ch} inside a value"
));
}
_ => {}
}
}
pending.push(ch);
if ch == '\n' {
line += 1;
}
}
if quote.is_some() || !groups.is_empty() || !pending.trim_ascii().is_empty() {
return Err(format!("line {line}: incomplete CSS statement"));
}
Ok(items)
}
enum Block<'a> {
Media {
dark: bool,
},
Rule {
selector: &'a str,
palette: Option<(&'static str, &'static str)>,
},
}
fn named_theme(selector: &str) -> Option<&str> {
let attribute = selector.strip_prefix(":root[")?.strip_suffix(']')?;
let (name, value) = attribute.split_once('=')?;
if name.trim_ascii() != "data-theme" {
return None;
}
let value = value.trim_ascii();
['"', '\'']
.into_iter()
.find_map(|quote| value.strip_prefix(quote)?.strip_suffix(quote))
}
fn palette_rule(selector: &str, parents: &[Block<'_>]) -> Option<(&'static str, &'static str)> {
if matches!(parents, [Block::Media { dark: true }]) && selector == ":root:not([data-theme])"
{
return Some((SYSTEM_DARK, "dark"));
}
if !parents.is_empty() {
return None;
}
if let Some((left, right)) = selector.split_once(',') {
return ((left.trim_ascii() == ":root"
&& named_theme(right.trim_ascii()) == Some("daylight"))
|| (right.trim_ascii() == ":root"
&& named_theme(left.trim_ascii()) == Some("daylight")))
.then_some(("daylight", "light"));
}
let name = named_theme(selector)?;
THEMES
.into_iter()
.find(|&(theme, _)| theme == name && name != "daylight")
}
fn parse_palettes(css: &str) -> Result<Palettes, String> {
let items = css_items(css)?;
let mut palettes = BTreeMap::new();
let mut blocks = Vec::new();
for item in &items {
let source = item.text.trim_ascii();
let line = item.line;
if item.end == '{' {
if source.is_empty() || matches!(blocks.last(), Some(Block::Rule { .. })) {
return Err(format!(
"line {line}: unsupported nested CSS block {source:?}"
));
}
if let Some(query) = source.strip_prefix("@media").map(str::trim_ascii_start)
&& query.starts_with('(')
{
let dark = query
.strip_prefix('(')
.and_then(|q| q.strip_suffix(')'))
.and_then(|q| q.split_once(':'))
.is_some_and(|(name, value)| {
name.trim_ascii() == "prefers-color-scheme"
&& value.trim_ascii() == "dark"
});
blocks.push(Block::Media { dark });
} else if source.starts_with('@') {
return Err(format!("line {line}: unsupported CSS at-rule {source:?}"));
} else {
let palette = palette_rule(source, &blocks);
if palette.is_none() && named_theme(source).is_some() {
return Err(format!("line {line}: unexpected palette selector {source}"));
}
if let Some((theme, _)) = palette
&& palettes
.insert(
theme,
Palette {
line,
..Palette::default()
},
)
.is_some()
{
return Err(format!("line {line}: duplicate {theme} palette"));
}
blocks.push(Block::Rule {
selector: source,
palette,
});
}
continue;
}
if !source.is_empty() {
let Some(Block::Rule { selector, palette }) = blocks.last() else {
return Err(format!(
"line {line}: declaration outside a CSS style rule: {source}"
));
};
let (name, value) = source
.split_once(':')
.ok_or_else(|| format!("line {line}: invalid CSS declaration {source:?}"))?;
let (name, value) = (name.trim_ascii(), value.trim_ascii());
let token = name
.strip_prefix("--")
.filter(|token| TOKENS.contains(token));
if let Some((theme, scheme)) = palette {
let palette = palettes.get_mut(theme).expect("palette was opened");
if name.eq_ignore_ascii_case("color-scheme") {
if palette.scheme_seen || value != *scheme {
return Err(format!(
"line {line}: {theme} requires one color-scheme: {scheme}"
));
}
palette.scheme_seen = true;
} else if let Some(token) = token {
let color = rgb(value).ok_or_else(|| {
format!("line {line}: {theme} --{token} requires a literal sRGB hex colour, found {value:?}")
})?;
if palette.colors.insert(token.to_owned(), color).is_some() {
return Err(format!("line {line}: {theme} repeats --{token}"));
}
} else {
return Err(format!(
"line {line}: unexpected declaration {name} in {theme}"
));
}
} else if token.is_some() || name.eq_ignore_ascii_case("color-scheme") {
return Err(format!(
"line {line}: protected {name} outside a palette in {selector}"
));
}
}
if item.end == '}' && blocks.pop().is_none() {
return Err(format!("line {line}: unmatched CSS closing brace"));
}
}
if !blocks.is_empty() {
return Err("unclosed CSS block".into());
}
for (theme, _) in THEMES.into_iter().chain([(SYSTEM_DARK, "dark")]) {
let palette = palettes
.get(theme)
.ok_or_else(|| format!("missing {theme} palette"))?;
if !palette.scheme_seen {
return Err(format!(
"line {}: {theme} missing color-scheme",
palette.line
));
}
for &token in TOKENS {
if !palette.colors.contains_key(token) {
return Err(format!("line {}: {theme} missing --{token}", palette.line));
}
}
}
let fallback = &palettes[SYSTEM_DARK];
for &token in TOKENS {
if fallback.colors[token] != palettes["slate"].colors[token] {
return Err(format!(
"line {}: system dark --{token} differs from slate",
fallback.line
));
}
}
Ok(palettes)
}
fn check_contrast(palettes: &Palettes) -> Result<(), String> {
for (theme, _) in THEMES {
for pair in PAIRS {
let ratio = palettes[theme].ratio(pair);
if ratio < pair.minimum {
return Err(format!(
"{theme}: --{} on --{} ({}) has contrast {ratio:.3}:1, minimum {:.1}:1",
pair.ink, pair.ground, pair.use_, pair.minimum,
));
}
}
}
Ok(())
}
fn measurement_table(palettes: &Palettes) -> String {
let mut table = String::from(
"| Pair | Use | Minimum | Slate | Graphite | Harbor | Daylight | Meridian | Parchment |\n\
|---|---|---:|---:|---:|---:|---:|---:|---:|\n",
);
for pair in PAIRS {
write!(
&mut table,
"| `{}` on `{}` | {} | {:.1} |",
pair.ink, pair.ground, pair.use_, pair.minimum
)
.expect("write table");
for (theme, _) in THEMES {
write!(&mut table, " {:.2} |", palettes[theme].ratio(pair)).expect("write ratio");
}
table.push('\n');
}
table
}
fn check_published_table(doc: &str, expected: &str) -> Result<(), String> {
let actual: Vec<_> = doc.lines().filter(|line| line.starts_with('|')).collect();
let expected: Vec<_> = expected.lines().collect();
for (found, want) in actual.iter().zip(&expected) {
if found != want {
return Err(format!(
"accessibility.md contrast row differs:\nfound: {found}\nwant: {want}"
));
}
}
if actual.len() != expected.len() {
return Err(format!(
"accessibility.md has {} table lines, expected {}",
actual.len(),
expected.len(),
));
}
Ok(())
}
#[test]
fn palette_meets_contrast_minimums() {
let palettes = parse_palettes(STYLE).unwrap_or_else(|error| panic!("{error}"));
check_contrast(&palettes).unwrap_or_else(|error| panic!("{error}"));
println!(
"{} named palettes, {} pairs each. System light uses Daylight. System dark matches Slate.",
THEMES.len(),
PAIRS.len(),
);
print!("{}", measurement_table(&palettes));
}
#[test]
fn published_palette_record_matches_stylesheet() {
let palettes = parse_palettes(STYLE).unwrap();
let doc =
include_str!("../../../../docs/design/console-design-system/project/accessibility.md");
check_published_table(doc, &measurement_table(&palettes))
.unwrap_or_else(|error| panic!("{error}"));
let source =
include_str!("../../../../docs/design/console-design-system/project/tokens.json");
let json: serde_json::Value = serde_json::from_str(source).expect("valid tokens.json");
let color = &json["color"];
let mut expected_themes = THEMES.map(|(theme, _)| Some(theme));
let mut saved_themes: Vec<_> = color["themes"]
.as_array()
.unwrap()
.iter()
.map(|theme| theme["id"].as_str())
.collect();
assert_eq!(
saved_themes.first(),
Some(&Some("daylight")),
"tokens.json default theme"
);
saved_themes.sort_unstable();
expected_themes.sort_unstable();
assert_eq!(saved_themes, expected_themes, "tokens.json theme IDs");
let mut published = BTreeMap::new();
for entry in color["tokens"].as_array().expect("colour token list") {
let name = entry["name"].as_str().expect("colour token name");
assert!(
TOKENS.contains(&name),
"unexpected tokens.json colour --{name}"
);
assert!(
published.insert(name, &entry["value"]).is_none(),
"duplicate tokens.json colour --{name}"
);
}
for &token in TOKENS {
let saved = published
.get(token)
.unwrap_or_else(|| panic!("tokens.json missing --{token}"));
assert_eq!(
saved.as_object().unwrap().len(),
THEMES.len(),
"tokens.json --{token} theme count"
);
for (theme, _) in THEMES {
let found = saved[theme].as_str().and_then(rgb);
assert_eq!(
found,
Some(palettes[theme].colors[token]),
"tokens.json {theme} --{token}"
);
}
}
let bundle = include_str!(
"../../../../docs/design/console-design-system/project/components/bundle.css"
);
let components = "* { box-sizing: border-box; }";
let components_in =
|asset: &'static str| asset.split_once(components).expect("component rules").1;
assert_eq!(
components_in(bundle),
components_in(STYLE),
"design component rules differ from shipped CSS"
);
}
#[test]
fn palette_parser_handles_css_boundaries() {
let css = STYLE.replacen(
" --canvas: #f4f6fa;\n --surface: #ffffff;",
" /* Unmatched } and --control: #000; are inert. */\n --canvas/**/: #f4f6fa; --surface: #fff;",
1,
);
assert_ne!(css, STYLE, "fixture must exercise palette formatting");
let css = format!(
"{css}\n@media (max-width: 40rem) {{ @media (orientation: landscape) {{\n .brand::before {{ content: \"}}; --control: #000; url(/images/*)\"; --sample: custom-url(icon) }}\n}} }}"
);
let expected = parse_palettes(STYLE).unwrap();
let parsed = parse_palettes(&css).unwrap();
assert_eq!(parsed["daylight"].colors, expected["daylight"].colors);
}
#[test]
fn palette_parser_rejects_bad_declarations() {
let dark_selector = " :root:not([data-theme]) {";
let (before_dark, dark_and_after) = STYLE.split_once(dark_selector).unwrap();
let (before_graphite, graphite_and_after) = STYLE
.split_once(":root[data-theme=\"graphite\"] {")
.unwrap();
let after_graphite = graphite_and_after.split_once('}').unwrap().1;
let fixtures = [
(
"missing colour",
STYLE.replacen(" --muted: #505e73;\n", "", 1),
"daylight missing --muted",
),
(
"missing palette",
format!("{before_graphite}{after_graphite}"),
"missing graphite palette",
),
(
"wrong dark fallback",
format!(
"{before_dark}{dark_selector}{}",
dark_and_after.replacen("--canvas: #0a1018", "--canvas: #ffffff", 1)
),
"system dark --canvas differs from slate",
),
(
"later root override",
format!("{STYLE}\n:root {{ --control: #000 }}"),
"protected --control outside a palette in :root",
),
(
"later media override",
format!(
"{STYLE}\n@media (prefers-color-scheme: dark) {{ :root {{ --control: #000 }} }}"
),
"protected --control outside a palette in :root",
),
(
"scoped override",
format!(
"{STYLE}\n@media (max-width: 45rem) {{ @media (orientation: landscape) {{ .button:hover {{ --danger: #fff }} }} }}"
),
"protected --danger outside a palette in .button:hover",
),
(
"duplicate palette",
format!("{STYLE}\n:root[data-theme=\"slate\"] {{}}"),
"duplicate slate palette",
),
(
"unexpected palette",
format!("{STYLE}\n:root[data-theme=\"violet\"] {{}}"),
"unexpected palette selector",
),
(
"duplicate token",
STYLE.replacen(
"--control: #7d8699;",
"--control: #7d8699; --control: #000;",
1,
),
"daylight repeats --control",
),
(
"unsupported value",
STYLE.replacen("--control: #7d8699;", "--control: rgb(0 0 0);", 1),
"daylight --control requires a literal sRGB hex colour",
),
(
"unsupported at-rule",
format!("{STYLE}\n@property --control {{ initial-value: #000; }}"),
"unsupported CSS at-rule \"@property --control\"",
),
(
"escaped property",
format!("{STYLE}\n.button {{ --contr\\6f l: #000; }}"),
"CSS escapes are outside the palette format",
),
];
for (fixture, css, expected) in fixtures {
let error = parse_palettes(&css).expect_err(fixture);
println!("{fixture}: {error}");
assert!(error.contains(expected), "{fixture}: {error}");
}
}
#[test]
fn palette_parser_rejects_unquoted_urls() {
let prefix = format!("{STYLE}\n#zone-table {{\n");
let url_line = prefix.bytes().filter(|&byte| byte == b'\n').count() + 1;
for declarations in [
" --sample-first: url(/images/*);\n --control: var(--canvas);\n --sample-last: url(/images*/icon);",
" --sample-first: URL(/images/icon);",
" --sample-first: url(\n /images/icon);",
r#" --sample-first: url(/* comment */ "image");"#,
] {
let css = format!("{prefix}{declarations}\n}}");
let error = parse_palettes(&css).expect_err(declarations);
assert_eq!(
error,
format!("line {url_line}: unquoted url() is outside the palette format"),
"{declarations}"
);
}
}
#[test]
fn palette_parser_rejects_html_comment_tokens() {
let prefix = format!("{STYLE}\n#zone-table {{\n");
let token_line = prefix.bytes().filter(|&byte| byte == b'\n').count() + 1;
for declarations in [
" --a: <!--url(/images/*);\n --control: var(--canvas);\n --b: <!--url(x*/);",
" --a: x <!-- y;",
" --a: x --> y;",
" --a: (x -->);",
] {
let css = format!("{prefix}{declarations}\n}}");
let error = parse_palettes(&css).expect_err(declarations);
assert_eq!(
error,
format!("line {token_line}: HTML comment tokens are outside the palette format"),
"{declarations}"
);
}
let css = format!("{prefix} --a: x\n y -->;\n}}");
let error = parse_palettes(&css).expect_err("token on a later line");
assert_eq!(
error,
format!(
"line {}: HTML comment tokens are outside the palette format",
token_line + 1
)
);
}
#[test]
fn palette_parser_accepts_html_comment_tokens_in_strings_and_comments() {
parse_palettes(STYLE).expect("the shipped stylesheet is in the palette format");
let css = format!(
"{STYLE}\n#zone-table {{ content: \"<!-- -->\"; /* <!-- --> */ --a: 1 /* --> */; }}"
);
parse_palettes(&css).expect("tokens in strings and comments are inert");
}
#[test]
fn palette_parser_handles_quoted_urls() {
let urls = "--sample-first: url(\n \"/images/*\"); --sample-last: URL('/images/*');";
let css = format!("{STYLE}\n#zone-table {{ {urls} }}");
parse_palettes(&css).expect("quoted URLs are allowed");
let css = format!("{STYLE}\n#zone-table {{ {urls} --control: var(--canvas); }}");
let error = parse_palettes(&css).expect_err("protected declaration after a quoted URL");
assert!(
error.contains("protected --control outside a palette in #zone-table"),
"{error}"
);
}
#[test]
fn palette_guard_rejects_bad_ratios_and_stale_measurements() {
for (fixture, old, new, expected, minimum) in [
(
"unreadable destructive ink",
"--dFillInk: #ffffff;",
"--dFillInk: #b3261e;",
"daylight: --dFillInk on --dFill",
TEXT_MINIMUM,
),
(
"invisible operable edge",
"--control: #7d8699;",
"--control: #f4f6fa;",
"daylight: --control on --canvas",
NON_TEXT_MINIMUM,
),
] {
let css = STYLE.replacen(old, new, 1);
let error = check_contrast(&parse_palettes(&css).unwrap()).expect_err(fixture);
println!("{fixture}: {error}");
assert!(error.contains(expected), "{fixture}: {error}");
assert!(
error.contains(&format!("1.000:1, minimum {minimum:.1}:1")),
"{error}"
);
}
let palettes = parse_palettes(STYLE).unwrap();
let table = measurement_table(&palettes);
let first_ratio = palettes["slate"].ratio(&PAIRS[0]);
let stale = table.replacen(&format!("| {first_ratio:.2} |"), "| 0.00 |", 1);
let error = check_published_table(&stale, &table).expect_err("stale published figure");
println!("stale published figure: {error}");
assert!(error.contains("contrast row differs"), "{error}");
}
}