canvist_layout 0.2.0

Incremental text and block layout for the canvist editor: line breaking, bidi, hit testing, display lists, and SVG/HTML renderers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
//! Semantic HTML plus CSS that wraps exactly where the canvas does.
//!
//! The HTML is ordinary flow content (`<p>`, `<h2>`, `<ul><li>`, `<strong>`,
//! …) for no-JavaScript readers and search engines. The CSS is generated from
//! the same resolved styles layout uses and pins every property that affects
//! line breaking, so a browser rendering the HTML at the layout width breaks
//! lines at the same places as [`DocumentLayout`](crate::DocumentLayout)
//! with the browser's own measurer. The full contract is in
//! `docs/internal/ssr-css-contract.md`.

use std::fmt::Write;
use std::sync::Arc;

use canvist_model::Block;
use canvist_model::Content;
use canvist_model::Document;
use canvist_model::Embed;
use canvist_model::InlineText;
use canvist_model::Mark;
use canvist_model::RunRef;
use canvist_model::Value;
use canvist_model::is_safe_link_url;

use super::attribute;
use super::escape_into;
use super::num;
use crate::Color;
use crate::document::InkDrawing;
#[cfg(feature = "tables")]
use crate::document::column_widths;
use crate::document::span_attr;
#[cfg(feature = "tables")]
use crate::document::table_cells;
#[cfg(feature = "tables")]
use crate::document::table_map;
use crate::style::BlockStyle;
use crate::style::StyleId;
use crate::style::Styles;
use crate::style::attr;
use crate::style::attr_px;
use crate::style::line_height;
use crate::text::slice;
use crate::theme::AttrBinding;
use crate::theme::EmbedStyle;
use crate::theme::FontSize;
use crate::theme::INK_WIDTH;
use crate::theme::LeafStyle;
use crate::theme::MarkerKind;
use crate::theme::Motion;
use crate::theme::TableRole;
use crate::theme::TextPatch;
use crate::theme::TextStyle;
use crate::theme::Theme;

/// The `textAlign` values layout understands, which are also CSS
/// `text-align` keywords.
const ALIGNMENTS: [&str; 4] = ["left", "center", "right", "justify"];

/// Options for [`to_html`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HtmlOptions {
	/// The content width, which must equal the layout width.
	pub width: f32,
}

impl HtmlOptions {
	/// Options for a document `width` pixels wide.
	#[must_use]
	pub const fn new(width: f32) -> Self {
		Self { width }
	}
}

/// Server-rendered HTML and the CSS it needs.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HtmlDocument {
	/// A `<div class="cv-doc">` fragment.
	pub html: String,
	/// The stylesheet, scoped under `.cv-doc`.
	pub css: String,
}

impl HtmlDocument {
	/// A complete HTML page holding the fragment and its stylesheet, with no
	/// body margin.
	#[must_use]
	pub fn page(&self) -> String {
		format!(
			"<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" \
			 content=\"width=device-width\"><style>{}</style></head><body \
			 style=\"margin:0\">{}</body></html>",
			self.css, self.html
		)
	}
}

/// Render `doc` with `theme` as semantic HTML and CSS.
#[must_use]
pub fn to_html(doc: &Document, theme: &Arc<Theme>, options: &HtmlOptions) -> HtmlDocument {
	let mut writer = Writer {
		doc,
		styles: Styles::new(theme.clone(), doc.schema().clone()),
		out: String::new(),
		stacked_tables: 0,
		header_scope: None,
	};
	writer.out.push_str("<div class=\"cv-doc\">");
	writer.children(None, None, 0, options.width);
	writer.out.push_str("</div>");

	let css = stylesheet(&writer.styles, options.width);
	HtmlDocument {
		html: writer.out,
		css,
	}
}

struct Writer<'a> {
	doc: &'a Document,
	styles: Styles,
	out: String,
	/// How many tables enclose the block being written that stack their
	/// cells, as layout does for a table nested in a cell.
	stacked_tables: usize,
	/// The `scope` of the grid cell about to be written, if it is a header:
	/// `col` across the first row, `row` down the first column. Only its
	/// table knows where a cell sits.
	header_scope: Option<&'static str>,
}

impl Writer<'_> {
	fn children(
		&mut self,
		parent: Option<&Block>,
		parent_style: Option<StyleId>,
		lists: usize,
		width: f32,
	) {
		let doc = self.doc;
		let marker = parent_style.and_then(|style| self.styles.get(style).marker);
		let open = parent.is_none_or(|parent| crate::document::is_open(doc, parent));
		let shown = if open { usize::MAX } else { 1 };
		let mut previous_after = None;

		for (index, &id) in doc
			.children(parent.map(Block::id))
			.iter()
			.enumerate()
			.take(shown)
		{
			let Some(block) = doc.block(id) else {
				continue;
			};
			let marker = marker.filter(|&kind| kind != MarkerKind::Disclosure || index == 0);

			let style = self
				.styles
				.resolve(block, parent.map(Block::kind), parent_style);
			let resolved = self.styles.get(style);
			let margin = previous_after.map_or(0.0, |after: f32| after.max(resolved.space_before));
			previous_after = Some(resolved.space_after);
			let marker = marker.map(|kind| {
				let depth = if kind == MarkerKind::Disclosure {
					usize::from(open)
				} else {
					lists.saturating_sub(1)
				};
				(kind, depth)
			});
			self.block(block, style, margin, marker, (lists, width));
		}
	}

	/// Write `block` as one element, then its text or child blocks.
	///
	/// Void elements such as `<hr>` stop after the opening tag, task items
	/// get their checkbox before the content, and nested lists count their
	/// depth so bullets cycle through the theme's markers.
	fn block(
		&mut self,
		block: &Block,
		style: StyleId,
		margin: f32,
		marker: Option<(MarkerKind, usize)>,
		(lists, width): (usize, f32),
	) {
		let resolved = self.styles.get(style).clone();
		let tag = tag_name(&resolved.tag);

		if self.table(block, (style, &resolved), margin, (lists, width)) {
			return;
		}

		self.open_tag(block, style, tag, marker);

		// A host draws a slot's picture into the empty element, so the
		// element carries the picture's text alternative.
		if let (Content::Leaf, LeafStyle::Slot { .. }) = (block.content(), resolved.leaf)
			&& let Some(alt) = block
				.attrs()
				.get("alt")
				.and_then(Value::as_str)
				.filter(|alt| !alt.is_empty())
		{
			attribute(&mut self.out, "role", "img");
			attribute(&mut self.out, "aria-label", alt);
		}

		let mut inline_style = self.inline_style(block, &resolved, margin);

		if self.stacks(&resolved) {
			inline_style.push_str("display:flow-root;");
		}

		let inner = (width - resolved.inset_left() - resolved.inset_right()).max(0.0);

		if let (Content::Leaf, LeafStyle::Ink { height, .. }) = (block.content(), resolved.leaf) {
			let height = attr_px(block.attrs(), "height").unwrap_or(height) * inner / INK_WIDTH;
			let _ = write!(inline_style, "height:{}px;", num(height));
			// To assistive technology a drawing is one image; its strokes
			// carry no text of their own.
			attribute(&mut self.out, "role", "img");
			attribute(&mut self.out, "aria-label", "Drawing");
		}

		if !inline_style.is_empty() {
			attribute(&mut self.out, "style", &inline_style);
		}

		self.out.push('>');

		if is_void(tag) {
			return;
		}

		if marker.is_some_and(|(kind, _)| kind == MarkerKind::Task) {
			self.checkbox(block, &resolved);
		}

		// The HTML parser drops a newline straight after `<pre>`, so a leading
		// newline in the text needs a sacrificial one in front of it.
		if let Content::Inline(inline) = block.content()
			&& tag == "pre"
			&& inline.as_str().starts_with('\n')
		{
			self.out.push('\n');
		}

		match block.content() {
			Content::Inline(inline) => self.inline(inline, &resolved.text),
			Content::Blocks(_) => self.child_blocks(block, (style, &resolved), (lists, width)),
			Content::Leaf => self.ink(block, &resolved),
		}

		let _ = write!(self.out, "</{tag}>");
	}

	/// An ink block's drawing, as an SVG filling it: strokes in the text
	/// colour and the theme's width unless they set their own.
	fn ink(&mut self, block: &Block, resolved: &BlockStyle) {
		let LeafStyle::Ink { height, stroke } = resolved.leaf else {
			return;
		};
		let Some(drawing) = cfg!(feature = "ink")
			.then(|| InkDrawing::from_attrs(block.attrs()))
			.flatten()
		else {
			return;
		};
		let height = attr_px(block.attrs(), "height").unwrap_or(height);
		let _ = write!(
			self.out,
			"<svg class=\"cv-ink\" viewBox=\"0 0 {} {}\" preserveAspectRatio=\"none\" \
			 aria-hidden=\"true\">",
			num(INK_WIDTH),
			num(height)
		);

		for line in &drawing.strokes {
			let color = line
				.color
				.map_or_else(|| "currentColor".to_owned(), |color| color.to_string());
			let _ = write!(
				self.out,
				"<path d=\"{}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"{}\" \
				 stroke-linecap=\"round\" stroke-linejoin=\"round\"/>",
				super::stroke_path(&line.points),
				num(line.width.unwrap_or(stroke))
			);
		}

		self.out.push_str("</svg>");
	}

	/// Write a container's children, inside its insets.
	fn child_blocks(
		&mut self,
		block: &Block,
		(style, resolved): (StyleId, &BlockStyle),
		(lists, width): (usize, f32),
	) {
		let lists = lists + usize::from(resolved.marker.is_some());
		let inner = (width - resolved.inset_left() - resolved.inset_right()).max(0.0);
		let table = matches!(resolved.table, Some(TableRole::Table { .. }));
		self.stacked_tables += usize::from(table);
		self.children(Some(block), Some(style), lists, inner);
		self.stacked_tables -= usize::from(table);
	}

	/// Whether a block styled `resolved` is a table, row, or cell that
	/// stacks as plain blocks: a table layout could not place on a grid, or
	/// any part of one.
	fn stacks(&self, resolved: &BlockStyle) -> bool {
		match resolved.table {
			Some(TableRole::Table { .. }) => true,
			Some(_) => self.stacked_tables > 0,
			None => false,
		}
	}

	#[cfg(feature = "tables")]
	/// Write a table whose cells layout places on a grid: a `<colgroup>`
	/// with the column widths layout uses, then its rows and cells, each
	/// cell's content as wide as its columns. Returns `false`, writing
	/// nothing, for any other block, a table nested in a cell, and a table
	/// without cells, which are written as containers.
	fn table(
		&mut self,
		block: &Block,
		(style, resolved): (StyleId, &BlockStyle),
		margin: f32,
		(lists, width): (usize, f32),
	) -> bool {
		let Some(TableRole::Table { rule }) = resolved.table else {
			return false;
		};
		let rule = rule.width;
		let doc = self.doc;
		let cells = table_cells(doc, block);
		let (map, hints) = table_map(doc, &cells);

		if self.stacked_tables > 0 || map.cells().is_empty() {
			return false;
		}

		let inner = (width - resolved.inset_left() - resolved.inset_right()).max(0.0);
		let widths = column_widths(&map, &hints, (inner - rule).max(0.0));
		let tag = tag_name(&resolved.tag);
		self.open_tag(block, style, tag, None);
		let mut inline_style = self.inline_style(block, resolved, margin);
		let _ = write!(
			inline_style,
			"width:{}px;",
			num(widths.iter().sum::<f32>() + rule)
		);
		attribute(&mut self.out, "style", &inline_style);
		self.out.push_str("><colgroup>");

		for width in &widths {
			let _ = write!(self.out, "<col style=\"width:{}px\">", num(*width));
		}

		self.out.push_str("</colgroup><tbody>");

		for (row, (row_block, row_cells)) in cells.iter().enumerate() {
			let row_style = self
				.styles
				.resolve(row_block, Some(block.kind()), Some(style));
			let row_tag = tag_name(&self.styles.get(row_style).tag).to_owned();
			self.open_tag(row_block, row_style, &row_tag, None);
			self.out.push('>');

			for (index, cell) in row_cells.iter().enumerate() {
				let Some(placed) = map.find(row, index).map(|found| map.cells()[found]) else {
					continue;
				};
				let cell_width: f32 = widths[placed.columns()].iter().sum::<f32>() - rule;
				let cell_style = self
					.styles
					.resolve(cell, Some(row_block.kind()), Some(row_style));
				self.header_scope = match (placed.row, placed.column) {
					(0, _) => Some("col"),
					(_, 0) => Some("row"),
					_ => None,
				};
				self.block(cell, cell_style, 0.0, None, (lists, cell_width.max(0.0)));
			}

			let _ = write!(self.out, "</{row_tag}>");
		}

		let _ = write!(self.out, "</tbody></{tag}>");
		true
	}

	/// Without the `tables` feature every table is written as a container.
	#[cfg(not(feature = "tables"))]
	#[allow(
		clippy::unused_self,
		clippy::trivially_copy_pass_by_ref,
		reason = "the same signature as the grid writer"
	)]
	fn table(
		&mut self,
		_block: &Block,
		_style: (StyleId, &BlockStyle),
		_margin: f32,
		_frame: (usize, f32),
	) -> bool {
		false
	}

	/// Write the start of `block`'s opening tag: its classes, `data-id`, and,
	/// for text blocks, `dir`. The tag is left open for the inline style.
	fn open_tag(
		&mut self,
		block: &Block,
		style: StyleId,
		tag: &str,
		marker: Option<(MarkerKind, usize)>,
	) {
		let defaults = &self.doc.schema().block(block.kind()).attrs;
		let type_name = class_name(&self.doc.schema().block(block.kind()).name);
		let _ = write!(
			self.out,
			"<{tag} class=\"cv-b cv-s{} cv-t-{type_name}",
			style.index()
		);

		if let Some((kind, depth)) = marker {
			let bullets = self.styles.theme().markers().bullets.len().max(1);

			let _ = match kind {
				MarkerKind::Bullet => write!(self.out, " cv-mk cv-mk-b{}", depth % bullets),
				MarkerKind::Ordered => write!(self.out, " cv-mk cv-mk-o"),
				MarkerKind::Task => write!(self.out, " cv-mk-t"),
				// For a disclosure, the depth slot carries whether it is open.
				MarkerKind::Disclosure => write!(self.out, " cv-mk cv-mk-d{depth}"),
			};
		}

		self.out.push('"');

		// Only the extensions' blocks need ARIA beyond their tags.
		if cfg!(feature = "theme-extensions") {
			self.accessibility(block);
		}

		attribute(&mut self.out, "data-id", &block.id().to_string());

		// Without grid layout, cells stack like any container's children,
		// so they have no spans to declare.
		if cfg!(feature = "tables") && self.styles.get(style).table == Some(TableRole::Cell) {
			self.cell_spans(block, tag);
		}

		if matches!(block.content(), Content::Inline(_)) {
			let dir = attr(block.attrs(), defaults, "dir")
				.and_then(Value::as_str)
				.filter(|dir| matches!(*dir, "ltr" | "rtl"))
				.unwrap_or("auto");
			attribute(&mut self.out, "dir", dir);
		}
	}

	/// A cell's `colspan` and `rowspan` attributes, when it spans more than
	/// one column or row, and a header cell's `scope`, so assistive
	/// technology reads each data cell with the headers that label it.
	fn cell_spans(&mut self, cell: &Block, tag: &str) {
		if let Some(scope) = self.header_scope.take().filter(|_| tag == "th") {
			attribute(&mut self.out, "scope", scope);
		}

		for key in ["colspan", "rowspan"] {
			let span = span_attr(self.doc, cell, key);

			if span > 1 {
				attribute(&mut self.out, key, &span.to_string());
			}
		}
	}

	/// The per-block declarations a shared class cannot carry: the collapsed
	/// top margin, an ordered list's start number, text alignment, and a
	/// slot's height.
	fn inline_style(&self, block: &Block, resolved: &BlockStyle, margin: f32) -> String {
		let defaults = &self.doc.schema().block(block.kind()).attrs;
		let mut inline_style = String::new();

		if margin > 0.0 {
			let _ = write!(inline_style, "margin-top:{}px;", num(margin));
		}

		if resolved.marker == Some(MarkerKind::Ordered) {
			let start = attr(block.attrs(), defaults, "start")
				.and_then(Value::as_int)
				.unwrap_or(1);
			let _ = write!(inline_style, "counter-reset:cv-n {};", start - 1);
		}

		let align = attr(block.attrs(), defaults, "textAlign").and_then(Value::as_str);

		if let Some(align) = align.filter(|align| ALIGNMENTS.contains(align))
			&& matches!(block.content(), Content::Inline(_))
		{
			let _ = write!(inline_style, "text-align:{align};");
		}

		if let (Content::Leaf, LeafStyle::Slot { height }) = (block.content(), resolved.leaf) {
			let height = attr_px(block.attrs(), "height").unwrap_or(height);
			let _ = write!(inline_style, "height:{}px;", num(height));
		}

		inline_style
	}

	fn checkbox(&mut self, block: &Block, style: &BlockStyle) {
		let defaults = &self.doc.schema().block(block.kind()).attrs;
		let checked = attr(block.attrs(), defaults, "checked")
			.and_then(Value::as_bool)
			.unwrap_or(false);
		let size = self.styles.theme().markers().checkbox;
		let top = (style.text.line_height_px() - size) / 2.0;
		let _ = write!(
			self.out,
			"<input type=\"checkbox\" class=\"cv-check\" disabled{} style=\"top:{}px\">",
			if checked { " checked" } else { "" },
			num(top)
		);
	}

	/// ARIA for blocks whose meaning only their look carries: a callout is
	/// a note whose type only its colour shows, and a block formula is an
	/// empty slot the host typesets, so it is labelled with its LaTeX.
	fn accessibility(&mut self, block: &Block) {
		let doc = self.doc;
		let schema = doc.schema();
		let defaults = &schema.block(block.kind()).attrs;
		let string = |key| attr(block.attrs(), defaults, key).and_then(Value::as_str);

		match &*schema.block(block.kind()).name {
			"callout" => {
				attribute(&mut self.out, "role", "note");
				let label = match string("type") {
					Some("blank") => None,
					Some("warning") => Some("Warning"),
					Some("error") => Some("Error"),
					Some("success") => Some("Success"),
					_ => Some("Info"),
				};

				if let Some(label) = label {
					attribute(&mut self.out, "aria-label", label);
				}
			}
			"blockMath" => {
				attribute(&mut self.out, "role", "math");
				attribute(
					&mut self.out,
					"aria-label",
					string("latex").unwrap_or_default(),
				);
			}
			_ => {}
		}
	}

	fn inline(&mut self, inline: &InlineText, base: &TextStyle) {
		let text = inline.as_str();
		let mut open: Vec<Mark> = Vec::new();
		let mut ends_with_break = text.is_empty();

		for run in inline.runs() {
			self.sync_marks(&mut open, run.marks.as_slice());
			ends_with_break = self.run_content(text, &run, base);
		}

		self.sync_marks(&mut open, &[]);

		if ends_with_break {
			self.out.push_str("<br class=\"cv-br\">");
		}
	}

	/// Write one run of `text`, returning whether it ends in a line break.
	fn run_content(&mut self, text: &str, run: &RunRef<'_>, base: &TextStyle) -> bool {
		if let Some(embed) = run.embed {
			return self.embed(embed, base, run.marks);
		}

		escape_into(&mut self.out, slice(text, &run.range));
		run.text.ends_with(crate::text::is_newline)
	}

	/// Move from the `open` mark elements to `marks`, closing only the
	/// elements past their shared prefix so adjacent runs that share marks
	/// share elements too.
	fn sync_marks(&mut self, open: &mut Vec<Mark>, marks: &[Mark]) {
		let common = open
			.iter()
			.zip(marks)
			.take_while(|(open_mark, mark)| open_mark == mark)
			.count();

		for mark in open.drain(common..).rev() {
			let _ = write!(self.out, "</{}>", self.mark_tag(&mark));
		}

		for mark in &marks[common..] {
			self.open_mark(mark);
			open.push(mark.clone());
		}
	}

	fn mark_tag(&self, mark: &Mark) -> String {
		self.styles
			.mark_tag(mark.kind)
			.map_or("span", |tag| tag_name(tag))
			.to_owned()
	}

	fn open_mark(&mut self, mark: &Mark) {
		let tag = self.mark_tag(mark);
		let name = class_name(&self.doc.schema().mark(mark.kind).name);
		let _ = write!(self.out, "<{tag} class=\"cv-m cv-m-{name}\"");

		let href = mark.attrs.get("href").and_then(Value::as_str);

		if let Some(href) = href.filter(|href| tag == "a" && is_safe_link_url(href)) {
			attribute(&mut self.out, "href", href);
		}

		let style = bindings_css(&self.styles, mark);

		if !style.is_empty() {
			attribute(&mut self.out, "style", &style);
		}

		self.out.push('>');
	}

	/// Write an embed, returning whether it is a line break.
	fn embed(&mut self, embed: &Embed, base: &TextStyle, marks: &canvist_model::MarkSet) -> bool {
		let name = class_name(&self.doc.schema().embed(embed.kind).name);

		let (width, height) = match self.styles.embed_style(embed.kind) {
			Some(EmbedStyle::LineBreak) => {
				self.out.push_str("<br>");

				return true;
			}
			Some(label @ EmbedStyle::Label { .. }) => {
				let text = label.label_text(&embed.attrs).unwrap_or_default();
				self.label(embed, &name, &text);

				return false;
			}
			Some(EmbedStyle::Box { width, height }) => (*width, *height),
			None => {
				let size = self.styles.run_style(base, marks).font.size;
				(size, size)
			}
		};

		let width = attr_px(&embed.attrs, "width").unwrap_or(width);
		let height = attr_px(&embed.attrs, "height").unwrap_or(height);
		let _ = write!(
			self.out,
			"<span class=\"cv-e cv-e-{name}\" style=\"width:{}px;height:{}px\"",
			num(width),
			num(height)
		);
		attribute(
			&mut self.out,
			"data-type",
			&self.doc.schema().embed(embed.kind).name,
		);
		self.out.push_str("></span>");
		false
	}

	/// Write a label embed as a text span of class `name` holding `text`, the
	/// theme's prefix followed by the embed's label attribute.
	fn label(&mut self, embed: &Embed, name: &str, text: &str) {
		let _ = write!(self.out, "<span class=\"cv-e cv-e-{name}\" dir=\"auto\"");
		attribute(
			&mut self.out,
			"data-type",
			&self.doc.schema().embed(embed.kind).name,
		);
		self.out.push('>');
		escape_into(&mut self.out, text);
		self.out.push_str("</span>");
	}
}

/// Inline CSS for the attribute bindings of `mark`, such as a colour mark's
/// `color`. Values from document content are validated before they reach a
/// style attribute.
fn bindings_css(styles: &Styles, mark: &Mark) -> String {
	let Some(rule) = styles.mark_rule(mark.kind) else {
		return String::new();
	};

	rule.bindings
		.iter()
		.filter_map(|binding| binding_css(binding, mark))
		.collect()
}

/// The declaration `binding` produces for `mark`, or `None` when the
/// attribute is missing or fails validation.
fn binding_css(binding: &AttrBinding, mark: &Mark) -> Option<String> {
	let string = |key: &str| mark.attrs.get(key).and_then(Value::as_str);

	match binding {
		AttrBinding::Color(key) => {
			string(key)
				.and_then(Color::parse_hex)
				.map(|color| format!("color:{color};"))
		}
		AttrBinding::Background(key) => {
			string(key)
				.and_then(Color::parse_hex)
				.map(|color| format!("background-color:{color};"))
		}
		AttrBinding::FontFamily(key) => {
			string(key)
				.filter(|family| is_safe_family(family))
				.map(|family| format!("font-family:{family};"))
		}
		AttrBinding::FontSize(key) => {
			attr_px(&mark.attrs, key)
				.filter(|size| *size > 0.0)
				.map(|size| format!("font-size:{}px;", num(size)))
		}
		AttrBinding::LineHeight(key) => {
			line_height(&mark.attrs, key).map(|height| format!("line-height:{};", num(height)))
		}
		AttrBinding::Motion(key) if cfg!(feature = "kinetic") => {
			string(key).and_then(Motion::from_name).map(motion_css)
		}
		AttrBinding::Motion(_) => None,
	}
}

/// The animation of kinetic text in HTML. CSS cannot move each glyph on
/// its own without wrapping it, so the whole run moves together; offsets
/// come from `position: relative`, which leaves line breaking alone.
fn motion_css(motion: Motion) -> String {
	let timing = match motion {
		Motion::Shake => "0.4s steps(4)",
		Motion::Pulse => "1.25s ease-in-out",
		Motion::Rainbow => "4s linear",
		Motion::Wave | Motion::None => "1.1s ease-in-out",
	};

	format!(
		"position:relative;animation:cv-k-{} {timing} infinite;",
		motion.name()
	)
}

/// The keyframes kinetic text animates with, and the rule that keeps it
/// still for readers who prefer reduced motion.
const MOTION_CSS: &str = "@keyframes cv-k-wave{0%,100%{top:0}50%{top:-0.16em}}@keyframes \
                          cv-k-shake{0%{left:0;top:0}25%{left:0.05em;top:-0.04em}50%{left:-0.04em;\
                          top:0.05em}75%{left:0.04em;top:0.03em}100%{left:0;top:0}}@keyframes \
                          cv-k-pulse{0%,100%{opacity:1}50%{opacity:0.35}}@keyframes \
                          cv-k-rainbow{from{filter:hue-rotate(0deg)}to{filter:\
                          hue-rotate(360deg)}}@media (prefers-reduced-motion:reduce){.cv-doc \
                          [style*=\"cv-k-\"]{animation:none!important}}";

/// The stylesheet for every style `styles` resolved, plus the fixed rules of
/// the CSS contract.
fn stylesheet(styles: &Styles, width: f32) -> String {
	let theme = styles.theme();
	let base = theme.base();
	let mut css = String::new();

	let _ = write!(
		css,
		".cv-doc{{box-sizing:content-box;width:{}px;margin:0;padding:0;background-color:{};\
		 {}white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;line-break:strict;\
		 hyphens:manual;text-align:start;text-indent:0;text-transform:none;word-spacing:0;\
		 tab-size:{};font-kerning:normal;font-variant:normal;font-variant-ligatures:normal;\
		 font-feature-settings:normal;font-variation-settings:normal;font-size-adjust:none;\
		 font-stretch:normal;text-rendering:auto;text-wrap:wrap;text-autospace:no-autospace;\
		 text-spacing-trim:normal;-webkit-text-size-adjust:100%;text-size-adjust:100%}}",
		num(width),
		theme.chrome().background,
		text_css(base),
		theme.tab_size()
	);
	css.push_str(
		".cv-doc :where(*){margin:0;padding:0;border:0 solid \
		 transparent;font:inherit;color:inherit;background:none;text-decoration:none;list-style:\
		 none;vertical-align:baseline;white-space:inherit;letter-spacing:inherit;box-sizing:\
		 content-box}",
	);
	css.push_str(".cv-doc :where(.cv-b){display:flow-root}");
	css.push_str(".cv-doc :where(.cv-e){display:inline-block;white-space:nowrap;text-indent:0}");

	for (id, style) in styles.all() {
		let _ = write!(
			css,
			".cv-doc .cv-s{}{{{}",
			id.index(),
			text_css(&style.text)
		);
		box_css(&mut css, style);
		css.push('}');
		grid_css(&mut css, id, style);
	}

	marker_css(&mut css, theme);

	let schema = styles.schema();
	let moves = theme.mark_rules().iter().any(|rule| {
		schema.mark_type(&rule.mark).is_some()
			&& rule
				.bindings
				.iter()
				.any(|binding| matches!(binding, AttrBinding::Motion(_)))
	});

	if moves {
		css.push_str(MOTION_CSS);
	}

	let draws = theme.block_rules().iter().any(|rule| {
		schema.block_type(&rule.block).is_some()
			&& matches!(rule.patch.leaf, Some(LeafStyle::Ink { .. }))
	});

	if draws {
		css.push_str(".cv-doc .cv-ink{display:block;width:100%;height:100%;overflow:visible}");
	}

	for rule in theme.mark_rules() {
		let _ = write!(
			css,
			".cv-doc .cv-m-{}{{{}}}",
			class_name(&rule.mark),
			patch_css(&rule.patch)
		);
	}

	for rule in theme.embed_rules() {
		if let EmbedStyle::Label { patch, .. } = &rule.style {
			let _ = write!(
				css,
				".cv-doc .cv-e-{}{{{}}}",
				class_name(&rule.embed),
				patch_css(patch)
			);
		}
	}

	css
}

/// Every text property, resolved to absolute values.
fn text_css(style: &TextStyle) -> String {
	let font = &style.font;
	let mut css = format!(
		"font-family:{};font-size:{}px;font-weight:{};font-style:{};line-height:{};color:{};\
		 letter-spacing:{}px;",
		font.family,
		num(font.size),
		font.weight,
		font_style(font.italic),
		num(style.line_height),
		style.color,
		num(style.letter_spacing)
	);
	let decorations = style.decorations;

	if decorations.any() {
		css.push_str(&decoration_css(
			decorations.underline || decorations.squiggle,
			decorations.strike,
			decorations.squiggle,
		));
	}

	css
}

/// The CSS `font-style` keyword for an italic or upright face.
fn font_style(italic: bool) -> &'static str {
	if italic { "italic" } else { "normal" }
}

fn decoration_css(underline: bool, strike: bool, wavy: bool) -> String {
	let lines: Vec<&str> = [(underline, "underline"), (strike, "line-through")]
		.into_iter()
		.filter_map(|(on, name)| on.then_some(name))
		.collect();

	if lines.is_empty() {
		return String::new();
	}

	format!(
		"text-decoration-line:{};text-decoration-style:{};",
		lines.join(" "),
		if wavy { "wavy" } else { "solid" }
	)
}

/// Append the box properties of `style`: padding, left border, background,
/// corner radius, and a rule's line.
///
/// Each property is written only when the style sets it, so plain blocks
/// keep the reset from the contract's base rules and get no box
/// declarations at all.
fn box_css(css: &mut String, style: &BlockStyle) {
	let padding = style.padding;

	if padding != crate::Insets::ZERO {
		let _ = write!(
			css,
			"padding:{}px {}px {}px {}px;",
			num(padding.top),
			num(padding.right),
			num(padding.bottom),
			num(padding.left)
		);
	}

	if let Some(border) = style.border_left {
		let _ = write!(
			css,
			"border-left:{}px solid {};",
			num(border.width),
			border.color
		);
	}

	if let Some(background) = style.background {
		let _ = write!(css, "background-color:{background};");
	}

	if style.radius > 0.0 {
		let _ = write!(css, "border-radius:{}px;", num(style.radius));
	}

	if let LeafStyle::Rule { thickness, color } = style.leaf {
		let _ = write!(css, "height:{}px;background-color:{color};", num(thickness));
	}

	match style.table {
		Some(TableRole::Table { .. }) => {
			css.push_str("display:table;table-layout:fixed;border-collapse:collapse;");
		}
		Some(TableRole::Row) => css.push_str("display:table-row;"),
		Some(TableRole::Cell) => {
			css.push_str("display:table-cell;vertical-align:top;text-align:start;");
		}
		None => {}
	}
}

/// The grid lines of a table styled `id`, on its own cells: collapsed
/// borders centred on each cell edge, as layout draws them.
fn grid_css(css: &mut String, id: StyleId, style: &BlockStyle) {
	if let Some(TableRole::Table { rule }) = style.table {
		let _ = write!(
			css,
			".cv-doc .cv-s{}>tbody>tr>.cv-b{{border:{}px solid {}}}",
			id.index(),
			num(rule.width),
			rule.color
		);
	}
}

fn marker_css(css: &mut String, theme: &Theme) {
	let markers = theme.markers();
	let color = markers
		.color
		.map(|color| format!("color:{color};"))
		.unwrap_or_default();
	let gap = num(markers.gap);
	let size = num(markers.checkbox);

	let _ = write!(
		css,
		".cv-doc .cv-mk,.cv-doc .cv-mk-t{{position:relative}}.cv-doc \
		 .cv-mk::before{{position:absolute;top:0;right:100%;margin-right:{gap}px;white-space:\
		 nowrap;{color}}}.cv-doc .cv-mk-o{{counter-increment:cv-n}}.cv-doc \
		 .cv-mk-o::before{{content:counter(cv-n) \".\"}}"
	);

	for open in [false, true] {
		let _ = write!(
			css,
			".cv-doc .cv-mk-d{}::before{{content:\"{}\"}}",
			usize::from(open),
			crate::document::disclosure(open)
		);
	}

	for (index, bullet) in markers.bullets.iter().enumerate() {
		let _ = write!(
			css,
			".cv-doc .cv-mk-b{index}::before{{content:\"{}\"}}",
			css_string(bullet)
		);
	}

	let _ = write!(
		css,
		".cv-doc .cv-check{{appearance:none;-webkit-appearance:none;position:absolute;right:100%;\
		 margin:0 {gap}px 0 0;width:{size}px;height:{size}px;box-sizing:border-box;border:1px \
		 solid #8a8580;border-radius:3px;background:none}}.cv-doc \
		 .cv-check:checked{{background:#2e2b29}}"
	);
}

/// CSS for a relative patch, as applied by a mark or label.
fn patch_css(patch: &TextPatch) -> String {
	let declarations = [
		patch
			.family
			.as_ref()
			.map(|family| format!("font-family:{family};")),
		patch.size.map(|size| {
			match size {
				FontSize::Px(px) => format!("font-size:{}px;", num(px)),
				FontSize::Em(em) => format!("font-size:{}em;", num(em)),
			}
		}),
		patch.weight.map(|weight| format!("font-weight:{weight};")),
		patch
			.italic
			.map(|italic| format!("font-style:{};", font_style(italic))),
		patch
			.line_height
			.map(|line_height| format!("line-height:{};", num(line_height))),
		patch.color.map(|color| format!("color:{color};")),
		patch
			.background
			.map(|background| format!("background-color:{background};")),
		patch
			.letter_spacing
			.map(|spacing| format!("letter-spacing:{}px;", num(spacing))),
		patch
			.baseline_shift
			.map(|em| format!("vertical-align:{}em;", num(em))),
	];
	let mut css: String = declarations.into_iter().flatten().collect();

	let underline = patch.underline.unwrap_or(false) || patch.squiggle.unwrap_or(false);
	css.push_str(&decoration_css(
		underline,
		patch.strike.unwrap_or(false),
		patch.squiggle.unwrap_or(false),
	));

	css
}

/// `tag` if it is a plain lowercase element name, otherwise `div`.
fn tag_name(tag: &str) -> &str {
	let valid = !tag.is_empty()
		&& tag
			.bytes()
			.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
		&& tag.as_bytes()[0].is_ascii_lowercase();

	if valid { tag } else { "div" }
}

fn is_void(tag: &str) -> bool {
	matches!(tag, "hr" | "br" | "img" | "input")
}

/// A type name reduced to characters safe in a class name.
fn class_name(name: &str) -> String {
	name.chars()
		.map(|character| {
			if character.is_ascii_alphanumeric() || matches!(character, '-' | '_') {
				character
			} else {
				'_'
			}
		})
		.collect()
}

fn css_string(value: &str) -> String {
	value.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Whether a font family from document content is safe inside a style
/// attribute.
fn is_safe_family(family: &str) -> bool {
	family.chars().all(|character| {
		character.is_alphanumeric() || matches!(character, ' ' | ',' | '-' | '_' | '"' | '\'')
	})
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn rejects_script_urls() {
		assert!(is_safe_link_url("https://example.com"));
		assert!(is_safe_link_url("/docs#top"));
		assert!(is_safe_link_url("mailto:a@b.c"));
		assert!(!is_safe_link_url("javascript:alert(1)"));
		assert!(!is_safe_link_url(" JavaScript:alert(1)"));
		assert!(!is_safe_link_url("data:text/html,x"));
	}

	#[test]
	fn sanitizes_names() {
		assert_eq!(tag_name("h2"), "h2");
		assert_eq!(tag_name("script onload"), "div");
		assert_eq!(class_name("bullet list"), "bullet_list");
		assert!(!is_safe_family("x;background:url(evil)"));
	}
}