Skip to main content

waft_markdown/
style_sheet.rs

1//! The look of rendered Markdown, and the inherited widget that sets it for a subtree.
2
3use std::rc::Rc;
4
5use waft_embedder::{Brightness, Color, FontStyle, FontWeight, TextAlign, TextDecoration};
6use waft_foundation::App;
7use waft_painting::{
8    Border, BorderRadius, BorderSide, BorderStyle, BoxDecoration, EdgeInsets, K_DEFAULT_FONT_SIZE,
9    TextStyle,
10};
11use waft_rendering::{
12    FlexColumnWidth, TableBorder, TableCellVerticalAlignment, TableColumnWidthRef,
13};
14use waft_widgets::{
15    BuildContext, DefaultTextStyle, InheritedWidget, IntoWidget, KeyRef, MediaQuery, WidgetRef,
16};
17
18/// The light and dark values of Apple's system colors [`MarkdownStyleSheet::from_text_style`]
19/// paints with, the ones flutter_markdown's Cupertino style sheet reads.
20mod system_colors {
21    use waft_embedder::Color;
22
23    pub(super) const LINK: (Color, Color) = (Color::new(0xFF007AFF), Color::new(0xFF0984FF));
24    pub(super) const BLUE: (Color, Color) = (Color::new(0xFF007AFF), Color::new(0xFF0A84FF));
25    pub(super) const GREY_6: (Color, Color) = (Color::new(0xFFF2F2F7), Color::new(0xFF1C1C1E));
26    pub(super) const GREY_4: (Color, Color) = (Color::new(0xFFD1D1D6), Color::new(0xFF3A3A3C));
27    pub(super) const SEPARATOR: (Color, Color) = (Color::new(0x493C3C43), Color::new(0x99545458));
28}
29
30/// How each element of a Markdown document looks.
31///
32/// [`text`](Self::text) is the style of body text. Every other text style is merged onto the
33/// style of the text around the element, so it may set only what differs: a link's color, a
34/// heading's size.
35///
36/// A sheet is replaced whole, never merged field by field: build one from
37/// [`from_text_style`](Self::from_text_style) or [`DefaultMarkdownStyle::of`] and change the
38/// fields that should differ.
39#[derive(Clone, Debug, PartialEq)]
40pub struct MarkdownStyleSheet {
41    pub text: TextStyle,
42    /// The headings from level 1 to 6.
43    pub headings: [HeadingStyle; 6],
44    pub link: TextStyle,
45    pub inline_code: TextStyle,
46    pub code_block: BlockStyle,
47    pub quote: BlockStyle,
48    pub list: ListStyle,
49    pub table: TableStyle,
50    /// Painted on a box of the full width and no height.
51    pub rule: BoxDecoration,
52    /// The vertical space between blocks, and between the items of a loose list.
53    pub block_spacing: f64,
54}
55
56/// How a heading looks.
57#[derive(Clone, Debug, PartialEq)]
58pub struct HeadingStyle {
59    pub text: TextStyle,
60    pub padding: EdgeInsets,
61}
62
63/// How a block drawn in a box looks: a quote or a code block.
64#[derive(Clone, Debug, PartialEq)]
65pub struct BlockStyle {
66    /// Merged onto the text style of the blocks inside.
67    pub text: TextStyle,
68    /// Between the decoration's edge and the content.
69    pub padding: EdgeInsets,
70    pub decoration: BoxDecoration,
71}
72
73/// How a list looks.
74#[derive(Clone, Debug, PartialEq)]
75pub struct ListStyle {
76    /// The width of the column that holds the bullets, past their padding.
77    pub indent: f64,
78    /// The style of a bullet or a number.
79    pub bullet: TextStyle,
80    pub bullet_padding: EdgeInsets,
81    /// A task item's checkbox is drawn as a glyph of this style: its color, at its font size.
82    pub checkbox: TextStyle,
83}
84
85/// How a table looks.
86#[derive(Clone, Debug)]
87pub struct TableStyle {
88    pub head: TextStyle,
89    pub body: TextStyle,
90    /// The alignment of a head cell whose column states none; a body cell's is the start.
91    pub head_align: TextAlign,
92    pub border: TableBorder,
93    pub cell_padding: EdgeInsets,
94    /// Painted behind every other body row, from the second.
95    pub stripe: Option<BoxDecoration>,
96    /// A column width that sizes to its content lets the table scroll sideways.
97    pub column_width: TableColumnWidthRef,
98    pub vertical_alignment: TableCellVerticalAlignment,
99}
100
101impl PartialEq for TableStyle {
102    fn eq(&self, other: &TableStyle) -> bool {
103        self.head == other.head
104            && self.body == other.body
105            && self.head_align == other.head_align
106            && self.border == other.border
107            && self.cell_padding == other.cell_padding
108            && self.stripe == other.stripe
109            && Rc::ptr_eq(&self.column_width, &other.column_width)
110            && self.vertical_alignment == other.vertical_alignment
111    }
112}
113
114impl MarkdownStyleSheet {
115    /// The look flutter_markdown's Cupertino style sheet gives, worked out from one text style:
116    /// links and checkboxes in Apple's blue, headings larger and in weight 500, quotes, code
117    /// blocks and every other table row on a light grey (dark grey when `brightness` is dark).
118    ///
119    /// A `text` with no font size counts as [`K_DEFAULT_FONT_SIZE`], the size it is drawn at,
120    /// for the sizes worked out from it.
121    pub fn from_text_style(text: TextStyle, brightness: Brightness) -> MarkdownStyleSheet {
122        let by_brightness = |(light, dark): (Color, Color)| match brightness {
123            Brightness::Dark => dark,
124            Brightness::Light => light,
125        };
126        let font_size = text.font_size.unwrap_or(K_DEFAULT_FONT_SIZE);
127        let heading = |size_increase: Option<f64>| {
128            let mut style = text.copy_with().font_weight(FontWeight::W500);
129            if let Some(increase) = size_increase {
130                style = style.font_size(font_size + increase);
131            }
132            HeadingStyle {
133                text: style,
134                padding: EdgeInsets::ZERO,
135            }
136        };
137        let code = text
138            .copy_with()
139            .font_family("monospace")
140            .font_size(font_size * 0.85);
141        let grey_6 = by_brightness(system_colors::GREY_6);
142        let grey_4 = by_brightness(system_colors::GREY_4);
143        let side = |width: f64| {
144            BorderSide::new(
145                grey_4,
146                width,
147                BorderStyle::Solid,
148                BorderSide::STROKE_ALIGN_INSIDE,
149            )
150        };
151        MarkdownStyleSheet {
152            text: text.clone(),
153            headings: [
154                heading(Some(10.0)),
155                heading(Some(8.0)),
156                heading(Some(6.0)),
157                heading(Some(4.0)),
158                heading(Some(2.0)),
159                heading(None),
160            ],
161            link: TextStyle::new().color(by_brightness(system_colors::LINK)),
162            inline_code: code.clone(),
163            code_block: BlockStyle {
164                text: code,
165                padding: EdgeInsets::all(8.0),
166                decoration: BoxDecoration::new().color(grey_6),
167            },
168            quote: BlockStyle {
169                text: text.clone(),
170                padding: EdgeInsets::all(16.0),
171                decoration: BoxDecoration::new().color(grey_6).border(Border {
172                    left: side(4.0),
173                    top: BorderSide::NONE,
174                    right: BorderSide::NONE,
175                    bottom: BorderSide::NONE,
176                }),
177            },
178            list: ListStyle {
179                indent: 24.0,
180                bullet: text.clone(),
181                bullet_padding: EdgeInsets::only(0.0, 0.0, 4.0, 0.0),
182                checkbox: text.copy_with().color(by_brightness(system_colors::BLUE)),
183            },
184            table: TableStyle {
185                head: text.copy_with().font_weight(FontWeight::W600),
186                body: text.clone(),
187                head_align: TextAlign::Center,
188                border: TableBorder::all(
189                    by_brightness(system_colors::SEPARATOR),
190                    0.0,
191                    BorderStyle::Solid,
192                    BorderRadius::ZERO,
193                ),
194                cell_padding: EdgeInsets::from_ltrb(16.0, 8.0, 16.0, 8.0),
195                stripe: Some(BoxDecoration::new().color(grey_6)),
196                column_width: FlexColumnWidth::default_width(),
197                vertical_alignment: TableCellVerticalAlignment::Middle,
198            },
199            rule: BoxDecoration::new().border(Border {
200                top: side(1.0),
201                right: BorderSide::NONE,
202                bottom: BorderSide::NONE,
203                left: BorderSide::NONE,
204            }),
205            block_spacing: 8.0,
206        }
207    }
208
209    /// The style of emphasised text inside text of `style`.
210    pub(crate) fn emphasis(style: &TextStyle) -> TextStyle {
211        style.copy_with().font_style(FontStyle::Italic)
212    }
213
214    /// The style of strong text inside text of `style`.
215    pub(crate) fn strong(style: &TextStyle) -> TextStyle {
216        style.copy_with().font_weight(FontWeight::BOLD)
217    }
218
219    /// The style of struck-through text inside text of `style`.
220    pub(crate) fn strikethrough(style: &TextStyle) -> TextStyle {
221        style.copy_with().decoration(TextDecoration::LINE_THROUGH)
222    }
223}
224
225/// The [`MarkdownStyleSheet`] of the Markdown widgets below it that are given none of their
226/// own; a kit or an app sets it, as [`DefaultTextStyle`] sets text's style.
227#[derive(Debug)]
228pub struct DefaultMarkdownStyle {
229    pub key: Option<KeyRef>,
230    pub style_sheet: MarkdownStyleSheet,
231    pub child: WidgetRef,
232}
233
234impl DefaultMarkdownStyle {
235    /// Sets `style_sheet` for the Markdown below `child`.
236    pub fn new<K>(
237        style_sheet: MarkdownStyleSheet,
238        child: impl IntoWidget<K>,
239    ) -> DefaultMarkdownStyle {
240        DefaultMarkdownStyle {
241            key: None,
242            style_sheet,
243            child: child.into_widget(),
244        }
245    }
246
247    /// Sets the key.
248    pub fn key(mut self, key: KeyRef) -> DefaultMarkdownStyle {
249        self.key = Some(key);
250        self
251    }
252
253    /// The style sheet of the closest [`DefaultMarkdownStyle`] above `context`, if any; the
254    /// context rebuilds when it changes.
255    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<MarkdownStyleSheet> {
256        context
257            .depend_on_inherited_widget_of_exact_type::<DefaultMarkdownStyle>(app)
258            .map(|widget| widget.style_sheet.clone())
259    }
260
261    /// The style sheet of the closest [`DefaultMarkdownStyle`] above `context`, or else
262    /// [`MarkdownStyleSheet::from_text_style`] of the ambient [`DefaultTextStyle`] in the
263    /// platform's brightness; the context rebuilds when any of them changes.
264    pub fn of(app: &mut App, context: BuildContext) -> MarkdownStyleSheet {
265        Self::maybe_of(app, context).unwrap_or_else(|| {
266            let text = DefaultTextStyle::of(app, context).style;
267            let brightness = MediaQuery::platform_brightness_of(app, context);
268            MarkdownStyleSheet::from_text_style(text, brightness)
269        })
270    }
271}
272
273impl InheritedWidget for DefaultMarkdownStyle {
274    fn key(&self) -> Option<&KeyRef> {
275        self.key.as_ref()
276    }
277
278    fn child(&self) -> &WidgetRef {
279        &self.child
280    }
281
282    fn update_should_notify(&self, old_widget: &DefaultMarkdownStyle) -> bool {
283        self.style_sheet != old_widget.style_sheet
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn from_text_style_sizes_the_headings_from_the_text() {
293        let text = TextStyle::new().font_size(15.0);
294        let sheet = MarkdownStyleSheet::from_text_style(text.clone(), Brightness::Light);
295        assert_eq!(sheet.text, text);
296        let sizes: Vec<Option<f64>> = sheet
297            .headings
298            .iter()
299            .map(|heading| heading.text.font_size)
300            .collect();
301        assert_eq!(
302            sizes,
303            [
304                Some(25.0),
305                Some(23.0),
306                Some(21.0),
307                Some(19.0),
308                Some(17.0),
309                Some(15.0)
310            ]
311        );
312        assert_eq!(sheet.code_block.text.font_size, Some(15.0 * 0.85));
313        let without_size = MarkdownStyleSheet::from_text_style(TextStyle::new(), Brightness::Light);
314        assert_eq!(
315            without_size.headings[0].text.font_size,
316            Some(K_DEFAULT_FONT_SIZE + 10.0)
317        );
318    }
319
320    #[test]
321    fn from_text_style_takes_the_colors_of_the_brightness() {
322        let light = MarkdownStyleSheet::from_text_style(TextStyle::new(), Brightness::Light);
323        let dark = MarkdownStyleSheet::from_text_style(TextStyle::new(), Brightness::Dark);
324        assert_eq!(light.link.color.as_deref(), Some(&system_colors::LINK.0));
325        assert_eq!(dark.link.color.as_deref(), Some(&system_colors::LINK.1));
326        assert_ne!(light.quote, dark.quote);
327        assert_ne!(light.table, dark.table);
328        assert_eq!(light, light.clone());
329    }
330}