use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use canvist_model::Value;
use crate::Color;
use crate::FontSpec;
use crate::Insets;
#[cfg(feature = "json")]
mod json;
mod starter_kit;
pub use starter_kit::ColorScheme;
pub use starter_kit::StarterKitOptions;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FontSize {
Px(f32),
Em(f32),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Decorations {
pub underline: bool,
pub strike: bool,
pub squiggle: bool,
pub color: Option<Color>,
}
impl Decorations {
#[must_use]
pub fn any(&self) -> bool {
self.underline || self.strike || self.squiggle
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
pub font: FontSpec,
pub line_height: f32,
pub color: Color,
pub background: Option<Color>,
pub decorations: Decorations,
pub letter_spacing: f32,
pub baseline_shift: f32,
pub motion: Motion,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Motion {
#[default]
None,
Wave,
Shake,
Pulse,
Rainbow,
}
impl Motion {
pub const ALL: [Self; 4] = [Self::Wave, Self::Shake, Self::Pulse, Self::Rainbow];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::None => "none",
Self::Wave => "wave",
Self::Shake => "shake",
Self::Pulse => "pulse",
Self::Rainbow => "rainbow",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|motion| motion.name() == name)
}
}
impl TextStyle {
#[must_use]
pub fn line_height_px(&self) -> f32 {
self.font.size * self.line_height
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextPatch {
pub family: Option<Arc<str>>,
pub size: Option<FontSize>,
pub weight: Option<u16>,
pub italic: Option<bool>,
pub line_height: Option<f32>,
pub color: Option<Color>,
pub background: Option<Color>,
pub underline: Option<bool>,
pub strike: Option<bool>,
pub squiggle: Option<bool>,
pub decoration_color: Option<Color>,
pub letter_spacing: Option<f32>,
pub baseline_shift: Option<f32>,
}
impl TextPatch {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn family(mut self, family: &str) -> Self {
self.family = Some(Arc::from(family));
self
}
#[must_use]
pub fn size(mut self, size: FontSize) -> Self {
self.size = Some(size);
self
}
#[must_use]
pub fn weight(mut self, weight: u16) -> Self {
self.weight = Some(weight);
self
}
#[must_use]
pub fn italic(mut self, italic: bool) -> Self {
self.italic = Some(italic);
self
}
#[must_use]
pub fn line_height(mut self, line_height: f32) -> Self {
self.line_height = Some(line_height);
self
}
#[must_use]
pub fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
#[must_use]
pub fn background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
#[must_use]
pub fn underline(mut self, on: bool) -> Self {
self.underline = Some(on);
self
}
#[must_use]
pub fn strike(mut self, on: bool) -> Self {
self.strike = Some(on);
self
}
#[must_use]
pub fn squiggle(mut self, on: bool) -> Self {
self.squiggle = Some(on);
self
}
#[must_use]
pub fn letter_spacing(mut self, px: f32) -> Self {
self.letter_spacing = Some(px);
self
}
#[must_use]
pub fn baseline_shift(mut self, em: f32) -> Self {
self.baseline_shift = Some(em);
self
}
pub fn apply(&self, style: &mut TextStyle) {
if let Some(family) = &self.family {
style.font.family = family.clone();
}
match self.size {
Some(FontSize::Px(px)) => style.font.size = px,
Some(FontSize::Em(em)) => style.font.size *= em,
None => {}
}
set(&mut style.font.weight, self.weight);
set(&mut style.font.italic, self.italic);
set(&mut style.line_height, self.line_height);
set(&mut style.color, self.color);
set(&mut style.letter_spacing, self.letter_spacing);
set(&mut style.decorations.underline, self.underline);
set(&mut style.decorations.strike, self.strike);
set(&mut style.decorations.squiggle, self.squiggle);
if self.background.is_some() {
style.background = self.background;
}
if self.decoration_color.is_some() {
style.decorations.color = self.decoration_color;
}
if let Some(em) = self.baseline_shift {
style.baseline_shift += em * style.font.size;
}
}
}
fn set<T: Copy>(target: &mut T, value: Option<T>) {
if let Some(value) = value {
*target = value;
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Border {
pub width: f32,
pub color: Color,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MarkerKind {
Bullet,
Ordered,
Task,
Disclosure,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TableRole {
Table {
rule: Border,
},
Row,
Cell,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LeafStyle {
Rule {
thickness: f32,
color: Color,
},
Slot {
height: f32,
},
Ink {
height: f32,
stroke: f32,
},
}
pub const INK_WIDTH: f32 = 1000.0;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BlockPatch {
pub text: TextPatch,
pub padding: Option<Insets>,
pub border_left: Option<Border>,
pub background: Option<Color>,
pub radius: Option<f32>,
pub space_before: Option<f32>,
pub space_after: Option<f32>,
pub marker: Option<MarkerKind>,
pub leaf: Option<LeafStyle>,
pub table: Option<TableRole>,
pub tag: Option<Arc<str>>,
}
impl BlockPatch {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn text(mut self, text: TextPatch) -> Self {
self.text = text;
self
}
#[must_use]
pub fn padding(mut self, padding: Insets) -> Self {
self.padding = Some(padding);
self
}
#[must_use]
pub fn border_left(mut self, width: f32, color: Color) -> Self {
self.border_left = Some(Border { width, color });
self
}
#[must_use]
pub fn background(mut self, color: Color, radius: f32) -> Self {
self.background = Some(color);
self.radius = Some(radius);
self
}
#[must_use]
pub fn space(mut self, before: f32, after: f32) -> Self {
self.space_before = Some(before);
self.space_after = Some(after);
self
}
#[must_use]
pub fn marker(mut self, marker: MarkerKind) -> Self {
self.marker = Some(marker);
self
}
#[must_use]
pub fn leaf(mut self, leaf: LeafStyle) -> Self {
self.leaf = Some(leaf);
self
}
#[must_use]
pub fn table(mut self, role: TableRole) -> Self {
self.table = Some(role);
self
}
#[must_use]
pub fn tag(mut self, tag: &str) -> Self {
self.tag = Some(Arc::from(tag));
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct BlockRule {
pub block: Arc<str>,
pub when: Option<(Arc<str>, Value)>,
pub parent: Option<Arc<str>>,
pub patch: BlockPatch,
}
impl BlockRule {
#[must_use]
pub fn new(block: &str, patch: BlockPatch) -> Self {
Self {
block: Arc::from(block),
when: None,
parent: None,
patch,
}
}
#[must_use]
pub fn when(mut self, key: &str, value: impl Into<Value>) -> Self {
self.when = Some((Arc::from(key), value.into()));
self
}
#[must_use]
pub fn within(mut self, parent: &str) -> Self {
self.parent = Some(Arc::from(parent));
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AttrBinding {
Color(Arc<str>),
Background(Arc<str>),
FontFamily(Arc<str>),
FontSize(Arc<str>),
LineHeight(Arc<str>),
Motion(Arc<str>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct MarkRule {
pub mark: Arc<str>,
pub patch: TextPatch,
pub bindings: Vec<AttrBinding>,
pub tag: Arc<str>,
}
impl MarkRule {
#[must_use]
pub fn new(mark: &str, tag: &str, patch: TextPatch) -> Self {
Self {
mark: Arc::from(mark),
patch,
bindings: Vec::new(),
tag: Arc::from(tag),
}
}
#[must_use]
pub fn bind(mut self, binding: AttrBinding) -> Self {
self.bindings.push(binding);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum EmbedStyle {
LineBreak,
Box {
width: f32,
height: f32,
},
Label {
attr: Arc<str>,
prefix: Arc<str>,
patch: TextPatch,
fallback: Option<Arc<str>>,
},
}
impl EmbedStyle {
#[must_use]
pub fn label_text(&self, attrs: &canvist_model::Attrs) -> Option<String> {
let Self::Label {
attr,
prefix,
fallback,
..
} = self
else {
return None;
};
let text = |key: &str| attrs.get(key).and_then(Value::as_str);
Some(match (text(attr), fallback.as_deref().and_then(text)) {
(Some(value), _) => format!("{prefix}{value}"),
(None, Some(fallback)) if prefix.is_empty() => format!(":{fallback}:"),
(None, Some(fallback)) => format!("{prefix}{fallback}"),
(None, None) => prefix.to_string(),
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct EmbedRule {
pub embed: Arc<str>,
pub style: EmbedStyle,
}
impl EmbedRule {
#[must_use]
pub fn new(embed: &str, style: EmbedStyle) -> Self {
Self {
embed: Arc::from(embed),
style,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Chrome {
pub background: Color,
pub selection: Color,
pub caret: Color,
pub caret_width: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MarkerStyle {
pub gap: f32,
pub bullets: Vec<Arc<str>>,
pub checkbox: f32,
pub color: Option<Color>,
}
const DEFAULT_SELECTION: Color = Color::rgba(0, 120, 215, 64);
static NEXT_VERSION: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug)]
pub struct Theme {
base: TextStyle,
tab_size: u32,
chrome: Chrome,
markers: MarkerStyle,
blocks: Vec<BlockRule>,
marks: Vec<MarkRule>,
embeds: Vec<EmbedRule>,
version: u64,
}
impl Theme {
#[must_use]
pub fn builder(base: TextStyle) -> ThemeBuilder {
ThemeBuilder {
theme: Self {
base,
tab_size: 8,
chrome: Chrome {
background: Color::rgb(0xff, 0xff, 0xff),
selection: DEFAULT_SELECTION,
caret: Color::rgb(0, 0, 0),
caret_width: 2.0,
},
markers: MarkerStyle {
gap: 6.0,
bullets: vec![Arc::from("•"), Arc::from("◦"), Arc::from("▪")],
checkbox: 14.0,
color: None,
},
blocks: Vec::new(),
marks: Vec::new(),
embeds: Vec::new(),
version: 0,
},
}
}
#[must_use]
pub fn to_builder(&self) -> ThemeBuilder {
ThemeBuilder {
theme: self.clone(),
}
}
#[must_use]
pub fn version(&self) -> u64 {
self.version
}
#[must_use]
pub fn base(&self) -> &TextStyle {
&self.base
}
#[must_use]
pub fn tab_size(&self) -> u32 {
self.tab_size
}
#[must_use]
pub fn chrome(&self) -> &Chrome {
&self.chrome
}
#[must_use]
pub fn markers(&self) -> &MarkerStyle {
&self.markers
}
#[must_use]
pub fn block_rules(&self) -> &[BlockRule] {
&self.blocks
}
#[must_use]
pub fn mark_rules(&self) -> &[MarkRule] {
&self.marks
}
#[must_use]
pub fn embed_rules(&self) -> &[EmbedRule] {
&self.embeds
}
}
#[derive(Clone, Debug)]
pub struct ThemeBuilder {
theme: Theme,
}
impl ThemeBuilder {
#[must_use]
pub fn tab_size(mut self, spaces: u32) -> Self {
self.theme.tab_size = spaces.max(1);
self
}
#[must_use]
pub fn chrome(mut self, chrome: Chrome) -> Self {
self.theme.chrome = chrome;
self
}
#[must_use]
pub fn markers(mut self, markers: MarkerStyle) -> Self {
self.theme.markers = markers;
self
}
#[must_use]
pub fn block(mut self, rule: BlockRule) -> Self {
self.theme.blocks.push(rule);
self
}
#[must_use]
pub fn mark(mut self, rule: MarkRule) -> Self {
self.theme.marks.push(rule);
self
}
#[must_use]
pub fn embed(mut self, rule: EmbedRule) -> Self {
self.theme.embeds.push(rule);
self
}
#[must_use]
pub fn build(mut self) -> Theme {
self.theme.version = NEXT_VERSION.fetch_add(1, Ordering::Relaxed);
self.theme
}
}
#[cfg(test)]
#[allow(
clippy::float_cmp,
reason = "the values compared are exactly representable"
)]
mod tests {
use super::*;
#[test]
fn patches_override_and_scale() {
const BOLD: u16 = 700;
let mut style = Theme::starter_kit().base().clone();
TextPatch::new()
.size(FontSize::Em(0.5))
.weight(BOLD)
.underline(true)
.apply(&mut style);
assert_eq!(style.font.size, 8.0);
assert_eq!(style.font.weight, BOLD);
assert!(style.decorations.underline);
assert!(!style.decorations.strike);
}
#[test]
fn every_build_gets_a_new_version() {
let theme = Theme::starter_kit();
let extended = theme.to_builder().tab_size(4).build();
assert_ne!(theme.version(), extended.version());
assert_eq!(extended.tab_size(), 4);
}
}