use super::names::{class_of_element, data_attribute, style_property};
use crate::stdlib::backends::pres::{self, DocRole, I48F16, Length, LengthUnit};
pub const STYLE_ATTRIBUTE: &str = "style";
pub const TAB_PROPERTY: &str = "--flm-tab";
pub fn css_length(length: &Length) -> String {
match length.unit {
LengthUnit::Tabs => format!("calc({} * var({TAB_PROPERTY}))", length.amount_decimal()),
LengthUnit::Ems
| LengthUnit::Points
| LengthUnit::Millimeters
| LengthUnit::Centimeters
| LengthUnit::Inches => length.to_string(),
}
}
pub fn css_ratio(first: &Length, second: &Length) -> Option<String> {
let points = |length: &Length| {
length
.convert_to(LengthUnit::Points)
.ok()
.filter(|converted| converted.amount > I48F16::ZERO)
};
let (first, second) = (points(first)?, points(second)?);
Some(format!("{} / {}", first.amount_decimal(), second.amount_decimal()))
}
pub const CONTENT_CLASS: &str = "flm-content";
pub const LIST_LABEL_CLASS: &str = "flm-pres-list-label";
pub const UNKNOWN_MARKER_CLASS: &str = "flm-pres-unknown-marker";
pub const AUXILIARY_CLASSES: [&str; 3] =
[CONTENT_CLASS, LIST_LABEL_CLASS, UNKNOWN_MARKER_CLASS];
pub const STYLE_CORE: &str = "flm.html.style.core";
pub const STYLE_HEADINGS: &str = "flm.html.style.headings";
pub const STYLE_VERBATIM: &str = "flm.html.style.verbatim";
pub const STYLE_MATH_PASSTHROUGH: &str = "flm.html.style.math-passthrough";
pub const STYLE_LISTS: &str = "flm.html.style.lists";
pub const STYLE_ERRORS: &str = "flm.html.style.errors";
pub const SCRIPT_MATHJAX: &str = "flm.html.mathjax";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TagRule {
Fixed(&'static str),
ParagraphContent,
HeadingLevel,
SpanStyle,
Display {
inline: &'static str,
block: &'static str,
},
VerbatimKindAndDisplay,
ListKind,
BlockRole,
None,
}
impl TagRule {
pub fn describe(self) -> String {
match self {
TagRule::Fixed(tag) => format!("`<{tag}>`"),
TagRule::ParagraphContent => format!(
"`<p>`; `<{PARAGRAPH_FLOW_TAG}>` with `role=\"{PARAGRAPH_ROLE}\"` when the \
paragraph holds flow content"
),
TagRule::HeadingLevel => String::from(
"`<h1>`–`<h6>` by level counted from `root_heading_level`, `<h6>` five levels \
below it and deeper; a render option maps a heading kind to a tag of its own",
),
TagRule::SpanStyle => String::from("by style; `<span>` otherwise"),
TagRule::Display { inline, block } => {
format!("`<{inline}>` inline, `<{block}>` as a block")
}
TagRule::VerbatimKindAndDisplay => String::from(
"for the kind `code`, `<code>` inline, `<pre><code>` as a block; for every other \
kind, `<span>` inline, `<div>` as a block",
),
TagRule::ListKind => String::from(
"`<ol>`, `<ul>` or `<dl>` by the kind `numbered`, `unnumbered` or `terms`; `<ul>` \
otherwise",
),
TagRule::BlockRole => {
let mapped: Vec<String> = BLOCK_TAGS
.iter()
.map(|entry| format!("`<{}>` for the role `{}`", entry.tag, entry.role))
.collect();
format!("by role: {}; `<{DEFAULT_BLOCK_TAG}>` otherwise", mapped.join(", "))
}
TagRule::None => String::from("none of its own"),
}
}
}
pub const PARAGRAPH_FLOW_TAG: &str = "div";
pub const PARAGRAPH_ROLE: &str = "paragraph";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockTag {
pub role: &'static str,
pub tag: &'static str,
}
pub const DEFAULT_BLOCK_TAG: &str = "div";
pub static BLOCK_TAGS: &[BlockTag] = &[
BlockTag { role: "flm.quote", tag: "blockquote" },
BlockTag { role: "flm.floats.float", tag: "figure" },
BlockTag { role: "flm.floats.float.caption", tag: "figcaption" },
BlockTag { role: "flm.toc", tag: "nav" },
];
pub fn block_tag(role: Option<&str>) -> &'static str {
role.and_then(|role| BLOCK_TAGS.iter().find(|entry| entry.role == role))
.map_or(DEFAULT_BLOCK_TAG, |entry| entry.tag)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Written {
Own(&'static str),
Data(&'static str),
Style,
Ratio(&'static str, &'static str),
RoleClass,
BlockClass,
Entry(&'static str),
EntryData(&'static str),
Dropped(&'static str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Field {
pub field: &'static str,
pub written: Written,
}
impl Field {
pub fn attribute(&self) -> Option<String> {
match self.written {
Written::Own(name) => Some(String::from(name)),
Written::Data(stem) => Some(data_attribute(stem)),
Written::Style
| Written::Ratio(..)
| Written::RoleClass
| Written::BlockClass
| Written::Entry(_)
| Written::EntryData(_)
| Written::Dropped(_) => None,
}
}
pub fn style_property(&self) -> Option<String> {
match self.written {
Written::Style | Written::Ratio(..) => Some(style_property(self.field)),
_ => None,
}
}
pub fn entry_attribute(&self) -> Option<String> {
match self.written {
Written::Entry(name) => Some(String::from(name)),
Written::EntryData(token) => Some(data_attribute(token)),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Convention {
pub element: &'static str,
pub tag: TagRule,
pub fields: &'static [Field],
pub style: Option<&'static str>,
}
impl Convention {
pub fn class(&self) -> String {
class_of_element(self.element)
}
pub fn field(&self, field: &str) -> Option<&Field> {
self.fields.iter().find(|entry| entry.field == field)
}
pub fn has_role(&self) -> bool {
self.fields.iter().any(|entry| entry.written == Written::RoleClass)
}
}
const fn own(field: &'static str, attribute: &'static str) -> Field {
Field { field, written: Written::Own(attribute) }
}
const fn data(field: &'static str) -> Field {
Field { field, written: Written::Data(field) }
}
const fn data_as(field: &'static str, stem: &'static str) -> Field {
Field { field, written: Written::Data(stem) }
}
const fn entry(field: &'static str, attribute: &'static str) -> Field {
Field { field, written: Written::Entry(attribute) }
}
const fn entry_data(field: &'static str, token: &'static str) -> Field {
Field { field, written: Written::EntryData(token) }
}
const fn style(field: &'static str) -> Field {
Field { field, written: Written::Style }
}
const fn ratio(name: &'static str, first: &'static str, second: &'static str) -> Field {
Field { field: name, written: Written::Ratio(first, second) }
}
const fn role(field: &'static str) -> Field {
Field { field, written: Written::RoleClass }
}
const fn block_class(field: &'static str) -> Field {
Field { field, written: Written::BlockClass }
}
const fn dropped(field: &'static str, why: &'static str) -> Field {
Field { field, written: Written::Dropped(why) }
}
pub static CONVENTIONS: &[Convention] = &[
Convention {
element: pres::PAR,
tag: TagRule::ParagraphContent,
fields: &[own("anchor", "id")],
style: Some(STYLE_CORE),
},
Convention {
element: pres::BLOCK,
tag: TagRule::BlockRole,
fields: &[
own("anchor", "id"),
role("role"),
own("doc_role", "role"),
data_as("kinds", "kind"),
],
style: Some(STYLE_CORE),
},
Convention {
element: pres::BLOCK_HEADING,
tag: TagRule::HeadingLevel,
fields: &[
own("anchor", "id"),
data_as("name", "heading"),
data("level"),
data_as("in_toc", "toc"),
dropped("number", "the number stands in the content"),
],
style: Some(STYLE_HEADINGS),
},
Convention {
element: pres::RUNIN_HEADING,
tag: TagRule::Fixed("span"),
fields: &[
own("anchor", "id"),
data_as("name", "heading"),
data("level"),
data_as("in_toc", "toc"),
dropped("number", "the number stands in the content"),
],
style: Some(STYLE_CORE),
},
Convention {
element: pres::SPAN,
tag: TagRule::SpanStyle,
fields: &[
own("anchor", "id"),
role("role"),
own("doc_role", "role"),
data("style"),
data_as("kinds", "kind"),
],
style: Some(STYLE_CORE),
},
Convention {
element: pres::LIST,
tag: TagRule::ListKind,
fields: &[
own("anchor", "id"),
data_as("kinds", "kind"),
entry("entry_anchors", "id"),
entry_data("entry_levels", "level"),
],
style: Some(STYLE_LISTS),
},
Convention {
element: pres::CELLS,
tag: TagRule::Fixed("table"),
fields: &[
dropped(
"rows",
"the grid's size is its shape: one `<tr>` per row, and in it one element per \
position a span does not cover, an empty `<td>` where there is no cell",
),
dropped("cols", "the grid's size is its shape, as for `rows`"),
dropped(
"cells",
"each entry is a `<td>`, or a `<th>` for a header, at its top-left position, \
holding its `cell` slot, its fields written as the attributes of each entry",
),
entry("row_span", "rowspan"),
entry("col_span", "colspan"),
entry("header", "scope"),
entry_data("align", "align"),
entry_data("rules", "rules"),
entry_data("styles", "style-"),
],
style: Some(crate::stdlib::features::cells::STYLE),
},
Convention {
element: pres::LINES,
tag: TagRule::Fixed("div"),
fields: &[],
style: Some(STYLE_LISTS),
},
Convention {
element: pres::LINE,
tag: TagRule::Fixed("div"),
fields: &[style("indent_left"), style("indent_right"), data("align")],
style: Some(STYLE_LISTS),
},
Convention {
element: pres::VERBATIM,
tag: TagRule::VerbatimKindAndDisplay,
fields: &[data("kind"), data("display"), data("lang")],
style: Some(STYLE_VERBATIM),
},
Convention {
element: pres::MATH_PASSTHROUGH,
tag: TagRule::Fixed("span"),
fields: &[role("role"), data("display"), data("env")],
style: Some(STYLE_MATH_PASSTHROUGH),
},
Convention {
element: pres::MATH_TEXT,
tag: TagRule::Fixed("span"),
fields: &[
own("anchor", "id"),
data("command"),
dropped(
"at_tag",
"the content is written at the position of an equation line's tag; no attribute: a \
pair of dollar signs is written around the element instead, inside the \
formula",
),
],
style: Some(STYLE_MATH_PASSTHROUGH),
},
Convention {
element: pres::LINK,
tag: TagRule::Fixed("a"),
fields: &[
own("href", "href"),
own("doc_role", "role"),
own("label", "aria-label"),
data("kind"),
],
style: Some(STYLE_CORE),
},
Convention {
element: pres::IMAGE,
tag: TagRule::Fixed("img"),
fields: &[
own("anchor", "id"),
own("src", "src"),
block_class("display"),
own("alt", "alt"),
own("srcset", "srcset"),
style("width"),
style("height"),
ratio("aspect_ratio", "width", "height"),
],
style: Some(STYLE_CORE),
},
Convention {
element: pres::UNSUPPORTED,
tag: TagRule::Fixed("span"),
fields: &[
data("element"),
dropped("message", "the reason is reported as a diagnostic, not shown in the page"),
],
style: Some(STYLE_ERRORS),
},
Convention {
element: pres::DROPPED,
tag: TagRule::Fixed("span"),
fields: &[
data("condition"),
dropped(
"detail",
"written as the element's content, after `dropped: `, so that it shows without a \
stylesheet",
),
],
style: Some(STYLE_ERRORS),
},
Convention {
element: pres::UNKNOWN,
tag: TagRule::Display { inline: "span", block: "div" },
fields: &[
data("kind"),
data("name"),
dropped(
"spelling",
"what the author typed, written as the element's content: a macro's spelling, an \
environment's `\\begin` and `\\end` lines",
),
],
style: Some(STYLE_ERRORS),
},
Convention {
element: pres::DECO_RUNIN,
tag: TagRule::Fixed("span"),
fields: &[],
style: Some(STYLE_CORE),
},
Convention {
element: pres::DECO_FINAL,
tag: TagRule::Fixed("span"),
fields: &[],
style: Some(STYLE_CORE),
},
Convention {
element: pres::DECO_MARGIN,
tag: TagRule::Fixed("span"),
fields: &[],
style: Some(STYLE_CORE),
},
Convention {
element: pres::DECO_MARK,
tag: TagRule::None,
fields: &[dropped("slot", "identifies the decoration written in the mark's place")],
style: None,
},
Convention {
element: pres::SUBTREE,
tag: TagRule::None,
fields: &[dropped("tree", "identifies the document tree written in the node's place")],
style: None,
},
];
pub fn doc_role_value(role: DocRole) -> String {
format!("doc-{}", role.as_str())
}
pub fn row(element: &str) -> Option<&'static Convention> {
CONVENTIONS.iter().find(|convention| convention.element == element)
}
pub fn markdown_table() -> String {
let mut out = String::from(
"| element | tag | classes | attributes | dropped | style definition |\n\
|---|---|---|---|---|---|\n",
);
for convention in CONVENTIONS {
let writes_an_element = convention.tag != TagRule::None;
let mut classes = if writes_an_element {
vec![format!("`{}`", convention.class())]
} else {
Vec::new()
};
let mut attributes: Vec<String> = Vec::new();
let mut dropped: Vec<String> = Vec::new();
let properties: Vec<String> = convention
.fields
.iter()
.filter_map(|field| {
field.style_property().map(|property| match field.written {
Written::Ratio(first, second) => {
format!("`{first}` ÷ `{second}` as `{property}`")
}
_ => format!("`{}` as `{property}`", field.field),
})
})
.collect();
let mut style_written = false;
for field in convention.fields {
match field.written {
Written::Style | Written::Ratio(..) => {
if !style_written {
attributes.push(format!(
"`{STYLE_ATTRIBUTE}` ← {} (custom properties, none for a zero length)",
properties.join(", ")
));
style_written = true;
}
}
Written::Own(name) => {
attributes.push(format!("`{name}` ← `{}`", field.field));
}
Written::Data(stem) => {
attributes.push(format!("`{}` ← `{}`", data_attribute(stem), field.field));
}
Written::Entry(_) | Written::EntryData(_) => {
if let Some(name) = field.entry_attribute() {
let place = if name.ends_with('-') { "<name>" } else { "" };
attributes.push(format!("each entry's `{name}{place}` ← `{}`", field.field));
}
}
Written::RoleClass => classes.push(String::from("the role's own class")),
Written::BlockClass => classes.push(format!(
"`{}` before it where `{}` is `block`",
class_of_element(pres::BLOCK),
field.field
)),
Written::Dropped(why) => dropped.push(format!("`{}` ({why})", field.field)),
}
}
let join = |parts: Vec<String>| {
if parts.is_empty() { String::from("—") } else { parts.join(", ") }
};
out.push_str(&format!(
"| `{}` | {} | {} | {} | {} | {} |\n",
convention.element,
convention.tag.describe(),
join(classes),
join(attributes),
join(dropped),
convention.style.map_or_else(|| String::from("—"), |style| format!("`{style}`")),
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_element_of_the_vocabulary_has_exactly_one_row() {
assert_eq!(CONVENTIONS.len(), pres::ALL.len());
for element in pres::ALL {
assert!(row(element).is_some(), "no row for `{element}`");
}
for convention in CONVENTIONS {
assert!(
pres::ALL.contains(&convention.element),
"`{}` is not an element of the vocabulary",
convention.element
);
}
}
#[test]
fn a_rows_attribute_names_are_writable_and_occur_once() {
for convention in CONVENTIONS {
let mut names: Vec<String> =
convention.fields.iter().filter_map(|field| field.attribute()).collect();
let count = names.len();
names.sort();
names.dedup();
assert_eq!(names.len(), count, "`{}` writes one attribute twice", convention.element);
let mut entry: Vec<String> = convention
.fields
.iter()
.filter_map(|field| field.entry_attribute())
.collect();
let count = entry.len();
entry.sort();
entry.dedup();
assert_eq!(entry.len(), count, "`{}` writes one attribute twice", convention.element);
for name in names.into_iter().chain(entry) {
assert!(
super::super::names::is_valid_attribute_name(&name),
"`{name}` is not writable"
);
}
}
}
#[test]
fn a_length_is_spelled_as_a_css_length_in_every_unit() {
let spelled = |text: &str| css_length(&Length::parse(text).expect("a length"));
assert_eq!(css_length(&Length::tabs(1)), "calc(1 * var(--flm-tab))");
assert_eq!(css_length(&Length::tabs(2)), "calc(2 * var(--flm-tab))");
assert_eq!(spelled("1.5tab"), "calc(1.5 * var(--flm-tab))");
assert_eq!(spelled("-1tab"), "calc(-1 * var(--flm-tab))");
assert_eq!(spelled("1.5em"), "1.5em");
assert_eq!(spelled("10pt"), "10pt");
assert_eq!(spelled("3mm"), "3mm");
assert_eq!(spelled("2cm"), "2cm");
assert_eq!(spelled("0.25in"), "0.25in");
assert_eq!(spelled(".5in"), "0.5in");
for unit in LengthUnit::ALL {
let css = css_length(&Length::new(Length::tabs(3).amount, unit));
if unit == LengthUnit::Tabs {
assert_eq!(css, format!("calc(3 * var({TAB_PROPERTY}))"));
} else {
assert_eq!(css, format!("3{}", unit.as_str()));
}
}
}
#[test]
fn a_length_field_is_a_custom_property_of_the_style_attribute_and_nothing_else() {
let line = row(pres::LINE).expect("a row");
let properties: Vec<String> =
line.fields.iter().filter_map(|field| field.style_property()).collect();
assert_eq!(properties, ["--flm-element-indent-left", "--flm-element-indent-right"]);
let attributes: Vec<String> = line.fields.iter().filter_map(|field| field.attribute()).collect();
assert_eq!(attributes, ["data-flm-align"]);
for convention in CONVENTIONS {
let mut names: Vec<String> =
convention.fields.iter().filter_map(|field| field.style_property()).collect();
let count = names.len();
names.sort();
names.dedup();
assert_eq!(names.len(), count, "`{}` writes one property twice", convention.element);
}
}
#[test]
fn the_printed_row_of_a_line_reads_the_two_properties() {
let table = markdown_table();
let line = table
.lines()
.find(|line| line.starts_with("| `flm.pres.line` |"))
.expect("the row");
assert!(
line.contains(
"`style` ← `indent_left` as `--flm-element-indent-left`, `indent_right` as \
`--flm-element-indent-right`"
),
"{line}"
);
assert!(!line.contains("data-flm-indent"), "{line}");
}
#[test]
fn every_document_role_is_written_as_a_digital_publishing_role() {
let values: Vec<String> = DocRole::ALL.into_iter().map(doc_role_value).collect();
assert_eq!(
values,
[
"doc-endnotes",
"doc-footnote",
"doc-noteref",
"doc-backlink",
"doc-bibliography",
"doc-biblioref",
"doc-toc"
]
);
}
#[test]
fn the_printed_table_holds_one_line_per_element() {
let table = markdown_table();
assert_eq!(table.lines().count(), pres::ALL.len() + 2);
for element in pres::ALL {
assert!(table.contains(&format!("| `{element}` |")), "`{element}` is not in the table");
}
}
}