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
//! Enable the dom to lay itself out using taffy
//!
//! In servo, style and layout happen together during traversal
//! However, in Blitz, we do a style pass then a layout pass.
//! This is slower, yes, but happens fast enough that it's not a huge issue.
use crate::node::{ImageData, NodeData, SpecialElementData};
use crate::{document::BaseDocument, dom_node_id, node::Node, taffy_node_id};
use markup5ever::local_name;
use std::cell::Ref;
use std::sync::Arc;
use style::Atom;
use style::values::computed::CSSPixelLength;
use style::values::computed::length_percentage::CalcLengthPercentage;
use taffy::{
BlockContext, CollapsibleMarginSet, FlexDirection, LayoutPartialTree, MaybeResolve, NodeId,
ResolveOrZero, RoundTree, Style, TraversePartialTree, TraverseTree, compute_block_layout,
compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout,
prelude::*,
};
/// Name the element a layout panic happened on. `BLITZ_TRACE_LAYOUT_PANIC=1`.
///
/// Layout runs percentages, `calc()` and every length through stylo, and when
/// stylo gives up it does so with `unreachable!()` deep inside its own value
/// types. The message names a line in a registry crate and not one frame of
/// ours, and a release backtrace is 78 frames of `__mh_execute_header`, so the
/// log says a value was impossible without saying which value, on which
/// element, in which document. AgencyZero 0.6.1 aborted two seconds after boot
/// on exactly that and the log could not narrow it past "stylo".
///
/// This keeps a stack of one-line element descriptions for the nodes currently
/// being laid out and prints the innermost few from a panic hook. Off unless
/// the variable is set: it formats a string per node, which is far too much for
/// a shipping build and nothing at all for a debugging run.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod layout_panic_probe {
use std::cell::RefCell;
use std::sync::OnceLock;
thread_local! {
static IN_FLIGHT: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
/// Deepest node entered, kept past the unwind on purpose: `pop` only
/// runs on the way out, so after a panic this still names the culprit.
static INNERMOST: std::cell::Cell<Option<blitz_traits::node_id::NodeId>> =
const { std::cell::Cell::new(None) };
}
pub(crate) fn enabled() -> bool {
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| {
let on = std::env::var_os("BLITZ_TRACE_LAYOUT_PANIC").is_some();
if on {
install_hook();
}
on
})
}
/// Chained, never replacing: the hook already installed is what writes the
/// panic to the application's log file, and an app whose stderr goes
/// nowhere loses the message entirely if this takes that job over.
fn install_hook() {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
IN_FLIGHT.with(|stack| {
let stack = stack.borrow();
if stack.is_empty() {
eprintln!("[blitz-layout-panic] no layout in flight on this thread");
} else {
eprintln!("[blitz-layout-panic] innermost first:");
for entry in stack.iter().rev().take(12) {
eprintln!("[blitz-layout-panic] {entry}");
}
eprintln!("[blitz-layout-panic] ({} deep)", stack.len());
}
});
previous(info);
}));
}
/// Deeper than any real document nests. A page that reaches this is
/// recursing, not laying out.
const RUNAWAY_DEPTH: usize = 512;
/// The node whose layout was in flight when everything stopped, so the
/// caller that still holds the document can serialize its markup.
pub(crate) fn innermost_node() -> Option<blitz_traits::node_id::NodeId> {
INNERMOST.with(std::cell::Cell::get)
}
pub(crate) fn push(node_id: blitz_traits::node_id::NodeId, description: String) {
INNERMOST.with(|cell| cell.set(Some(node_id)));
IN_FLIGHT.with(|stack| {
let mut stack = stack.borrow_mut();
stack.push(description);
if stack.len() == RUNAWAY_DEPTH {
// Reported here rather than left to the panic hook, because
// runaway layout does not reliably panic: it exhausts the
// stack, and what comes back is a `SIGSEGV` on the guard page
// or "fatal runtime error: stack overflow", neither of which
// runs a hook or leaves a line in the log. This is the last
// moment the evidence still exists.
eprintln!(
"[blitz-layout-panic] runaway: {RUNAWAY_DEPTH} nested layouts, innermost first:"
);
for entry in stack.iter().rev().take(24) {
eprintln!("[blitz-layout-panic] {entry}");
}
}
});
}
pub(crate) fn pop() {
IN_FLIGHT.with(|stack| {
stack.borrow_mut().pop();
});
}
}
/// How much of the tree a single resolve actually recomputed.
///
/// Phase timings say layout is expensive; they cannot say whether that is a
/// handful of slow nodes or the whole tree missing its cache. These counters
/// answer that, and a wrong answer sends the fix to the wrong place entirely.
/// Thread-local and read once per resolve, so the counting itself is free.
#[cfg(feature = "log-phase-times")]
pub mod layout_counters {
use blitz_traits::node_id::NodeId;
use std::cell::Cell;
thread_local! {
static ACTIVE: Cell<bool> = const { Cell::new(false) };
static COMPUTED: Cell<u64> = const { Cell::new(0) };
static CACHES_CLEARED: Cell<u64> = const { Cell::new(0) };
static LOOKUPS: Cell<u64> = const { Cell::new(0) };
static HITS: Cell<u64> = const { Cell::new(0) };
/// Distinct nodes recomputed, to tell "the whole tree once" apart from
/// "a few nodes many times". Those have completely different fixes and
/// the totals alone cannot distinguish them.
static DISTINCT: std::cell::RefCell<std::collections::HashMap<NodeId, u32>> =
std::cell::RefCell::new(std::collections::HashMap::new());
}
/// Select collection once for the whole resolve and reset its scratch data.
pub(crate) fn begin(active: bool) {
ACTIVE.with(|enabled| enabled.set(active));
if !active {
return;
}
COMPUTED.with(|count| count.set(0));
CACHES_CLEARED.with(|count| count.set(0));
LOOKUPS.with(|count| count.set(0));
HITS.with(|count| count.set(0));
DISTINCT.with(|seen| seen.borrow_mut().clear());
}
#[inline(always)]
fn active() -> bool {
ACTIVE.with(Cell::get)
}
pub(crate) fn note_computed(node_id: NodeId) {
if !active() {
return;
}
COMPUTED.with(|count| count.set(count.get() + 1));
DISTINCT.with(|seen| {
*seen.borrow_mut().entry(node_id).or_insert(0u32) += 1;
});
}
/// The nodes recomputed most often, worst first.
///
/// Totals say the work is concentrated; only the identities say where. A
/// node recomputed a hundred times is either being measured under a hundred
/// different constraints or sitting under a container that re-descends, and
/// naming it is the difference between fixing that and guessing again.
pub(crate) fn worst_offenders(limit: usize) -> Vec<(NodeId, u32)> {
DISTINCT.with(|seen| {
let mut rows: Vec<(NodeId, u32)> = seen
.borrow()
.iter()
.map(|(id, count)| (*id, *count))
.collect();
rows.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
rows.truncate(limit);
rows
})
}
pub(crate) fn note_cache_cleared() {
if !active() {
return;
}
CACHES_CLEARED.with(|count| count.set(count.get() + 1));
}
pub(crate) fn note_lookup(hit: bool) {
if !active() {
return;
}
LOOKUPS.with(|count| count.set(count.get() + 1));
if hit {
HITS.with(|count| count.set(count.get() + 1));
}
}
/// Public so a test or a harness can read what a single resolve cost without
/// scraping the per-frame stdout line. Feature-gated with the counting itself,
/// so a release build has neither.
#[derive(Clone, Copy)]
pub struct LayoutCounts {
pub computed: u64,
pub distinct: usize,
pub caches_cleared: u64,
pub lookups: u64,
pub hits: u64,
}
impl LayoutCounts {
const ZERO: Self = Self {
computed: 0,
distinct: 0,
caches_cleared: 0,
lookups: 0,
hits: 0,
};
}
thread_local! {
/// A copy of the most recent `take`, because the per-frame printer
/// takes them at the end of every resolve: without this, anything else
/// reading them always sees zero.
static LAST: Cell<LayoutCounts> = const { Cell::new(LayoutCounts::ZERO) };
}
/// The counts from the most recent `take`, without resetting anything.
#[must_use]
pub fn last() -> LayoutCounts {
LAST.with(Cell::get)
}
/// Counts since the last call, then reset.
pub fn take() -> LayoutCounts {
if !active() {
LAST.with(|last| last.set(LayoutCounts::ZERO));
return LayoutCounts::ZERO;
}
let counts = LayoutCounts {
computed: COMPUTED.with(|count| count.replace(0)),
distinct: DISTINCT.with(|seen| {
let mut seen = seen.borrow_mut();
let len = seen.len();
seen.clear();
len
}),
caches_cleared: CACHES_CLEARED.with(|count| count.replace(0)),
lookups: LOOKUPS.with(|count| count.replace(0)),
hits: HITS.with(|count| count.replace(0)),
};
ACTIVE.with(|active| active.set(false));
LAST.with(|last| last.set(counts));
counts
}
}
pub(crate) mod construct;
pub(crate) mod damage;
pub(crate) mod inline;
pub(crate) mod list;
pub(crate) mod replaced;
pub(crate) mod table;
use self::replaced::{ReplacedContext, is_replaced_element, replaced_measure_function};
use self::table::TableTreeWrapper;
pub(crate) fn resolve_calc_value(calc_ptr: *const (), parent_size: f32) -> f32 {
let calc = unsafe { &*(calc_ptr as *const CalcLengthPercentage) };
let result = calc.resolve(CSSPixelLength::new(parent_size));
result.px()
}
impl BaseDocument {
fn node_from_id(&self, node_id: taffy::prelude::NodeId) -> &Node {
&self.nodes[dom_node_id(node_id)]
}
fn node_from_id_mut(&mut self, node_id: taffy::prelude::NodeId) -> &mut Node {
&mut self.nodes[dom_node_id(node_id)]
}
/// One line naming an element well enough to find it in the source that
/// produced it: the tag, its `id`, its classes, and the sizes that were
/// being resolved when layout entered it. See [`layout_panic_probe`].
#[cfg(not(target_arch = "wasm32"))]
fn describe_node_for_panic(
&self,
node_id: blitz_traits::node_id::NodeId,
inputs: &taffy::LayoutInput,
) -> String {
let Some(node) = self.nodes.get(node_id) else {
return format!("node {node_id} (gone)");
};
let Some(element) = node.data.downcast_element() else {
return format!("node {node_id} <{:?}>", node.data.kind());
};
let attr = |name: &str| -> Option<&str> {
element
.attrs
.iter()
.find(|a| a.name.local.as_ref() == name)
.map(|a| a.value.as_ref())
};
// Not the computed style's own width and height: `CompactLength`'s
// `Debug` is a tagged pointer, which reads as noise. What the resolve
// was actually given is what matters here anyway.
format!(
"node {node_id} <{}{}{}> known={:?}x{:?} avail={:?}x{:?} mode={:?}/{:?}",
element.name.local,
attr("id").map(|v| format!(" id={v}")).unwrap_or_default(),
attr("class")
.map(|v| format!(" class=\"{}\"", &v[..v.len().min(160)]))
.unwrap_or_default(),
inputs.known_dimensions.width,
inputs.known_dimensions.height,
inputs.available_space.width,
inputs.available_space.height,
inputs.run_mode,
inputs.axis,
)
}
}
impl BaseDocument {
fn compute_child_layout_internal(
&mut self,
node_id: NodeId,
inputs: taffy::tree::LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> taffy::tree::LayoutOutput {
// Counted, not timed. The layout phase dominates a script-forced
// resolve, and the two explanations (a few nodes that are each slow, or
// the whole tree recomputing) call for opposite fixes. Only the blast
// radius separates them, and a cache hit never reaches this function.
#[cfg(feature = "log-phase-times")]
layout_counters::note_computed(dom_node_id(node_id));
let node = &mut self.nodes[dom_node_id(node_id)];
let font_styles = node.primary_styles().map(|style| {
use style::values::computed::font::LineHeight;
let font_size = style.clone_font_size().used_size().px();
let line_height = match style.clone_line_height() {
LineHeight::Normal => font_size * 1.2,
LineHeight::Number(num) => font_size * num.0,
LineHeight::Length(value) => value.0.px(),
};
(font_size, line_height)
});
let font_size = font_styles.map(|s| s.0);
let resolved_line_height = font_styles.map(|s| s.1);
match &mut node.data {
NodeData::Text(data) => {
// With the new "inline context" architecture all text nodes should be wrapped in an "inline layout context"
// and should therefore never be measured individually.
#[cfg(feature = "tracing")]
tracing::error!(
node_id = ?dom_node_id(node_id),
data = ?data,
"Tried to lay out text node individually",
);
#[cfg(not(feature = "tracing"))]
let _ = data;
taffy::LayoutOutput::HIDDEN
// unreachable!();
// compute_leaf_layout(inputs, &node.style, |known_dimensions, available_space| {
// let context = TextContext {
// text_content: &data.content.trim(),
// writing_mode: WritingMode::Horizontal,
// };
// let font_metrics = FontMetrics {
// char_width: 8.0,
// char_height: 16.0,
// };
// text_measure_function(
// known_dimensions,
// available_space,
// &context,
// &font_metrics,
// )
// })
}
NodeData::Element(element_data) | NodeData::AnonymousBlock(element_data) => {
// TODO: deduplicate with single-line text input
if *element_data.name.local == *"textarea" {
let rows = element_data
.attr(local_name!("rows"))
.and_then(|val| val.parse::<f32>().ok())
.unwrap_or(2.0);
let cols = element_data
.attr(local_name!("cols"))
.and_then(|val| val.parse::<f32>().ok());
let intrinsic_height = resolved_line_height.unwrap_or(16.0) * rows;
// Give the editor the width it has to lay out within, so a
// long line wraps instead of running off the side. Without
// this the editor is built with `set_width(None)` and never
// told otherwise: `wrap="soft"` and `overflow-wrap` in the
// stylesheet have nothing to act on, and typing past the
// right edge walks the text out of the box and out of sight.
//
// The node's own `width` comes first. `known_dimensions` is
// what the parent has decided so far and does not yet
// include this element's style size, so reading only that
// hands the editor the parent's width and it wraps, when it
// wraps at all, to the wrong measure.
let content_width = node
.style()
.size
.width
.maybe_resolve(inputs.parent_size.width, resolve_calc_value)
.or(inputs.known_dimensions.width)
.or(match inputs.available_space.width {
taffy::AvailableSpace::Definite(width) => Some(width),
_ => None,
})
.map(|width| {
let inset = node
.style()
.padding
.resolve_or_zero(inputs.parent_size, resolve_calc_value)
.horizontal_components()
.sum()
+ node
.style()
.border
.resolve_or_zero(inputs.parent_size, resolve_calc_value)
.horizontal_components()
.sum();
(width - inset).max(0.0)
});
// The wrapped text may be taller than the box. That excess
// is exactly what `scrollHeight` reports and what an
// autosizing composer grows by, so it has to reach Taffy as
// content size rather than be rounded away into the box
// height.
let mut content_height = intrinsic_height;
if let Some(width) = content_width.filter(|width| *width > 0.0) {
let font_ctx = self.font_ctx.clone();
let layout_ctx = &mut self.layout_ctx;
let node = &mut self.nodes[dom_node_id(node_id)];
if let Some(input) = node
.data
.downcast_element_mut()
.and_then(|el| el.text_input_data_mut())
{
input.sync_multiline_width(
&mut font_ctx.lock().unwrap(),
layout_ctx,
width,
);
if let Some(layout) = input.editor.try_layout() {
content_height = content_height.max(layout.height());
}
}
}
let node = &mut self.nodes[dom_node_id(node_id)];
let mut output = compute_leaf_layout(
inputs,
node.style(),
resolve_calc_value,
|_known_size, _available_space| taffy::Size {
width: cols
.map(|cols| cols * font_size.unwrap_or(16.0) * 0.6)
.unwrap_or(300.0),
height: intrinsic_height,
},
);
output.content_size.height = output.content_size.height.max(content_height);
output.content_size.width = output.content_size.width.max(output.size.width);
return output;
}
if *element_data.name.local == *"input" {
match element_data.attr(local_name!("type")) {
// if the input type is hidden, hide it
Some("hidden") => {
node.style_mut().display = Display::None;
return taffy::LayoutOutput::HIDDEN;
}
Some("checkbox") => {
return compute_leaf_layout(
inputs,
node.style(),
resolve_calc_value,
|_known_size, _available_space| {
let width = node.style().size.width.resolve_or_zero(
inputs.parent_size.width,
resolve_calc_value,
);
let height = node.style().size.height.resolve_or_zero(
inputs.parent_size.height,
resolve_calc_value,
);
let min_size = width.min(height);
taffy::Size {
width: min_size,
height: min_size,
}
},
);
}
None | Some("text" | "password" | "email" | "tel" | "url" | "search") => {
return compute_leaf_layout(
inputs,
node.style(),
resolve_calc_value,
|_known_size, _available_space| taffy::Size {
width: match inputs.available_space.width {
AvailableSpace::Definite(limit) => limit.min(300.0),
AvailableSpace::MinContent => 0.0,
AvailableSpace::MaxContent => 300.0,
},
height: resolved_line_height.unwrap_or(16.0),
},
);
}
_ => {}
}
}
if is_replaced_element(&element_data.name.local) {
// Get width and height attributes on image element
//
// TODO: smarter sizing using these (depending on object-fit, they shouldn't
// necessarily just override the native size)
let mut attr_size = taffy::Size {
width: element_data
.attr(local_name!("width"))
.and_then(|val| val.parse::<f32>().ok()),
height: element_data
.attr(local_name!("height"))
.and_then(|val| val.parse::<f32>().ok()),
};
// Get the element's intrinsic size and aspect ratio
let (inherent_size, inherent_ratio) = match &element_data.special_data {
SpecialElementData::Image(image_data) => match &**image_data {
ImageData::Raster(image) => {
let size = taffy::Size {
width: image.width as f32,
height: image.height as f32,
};
(size, Some(size.width / size.height))
}
#[cfg(feature = "svg")]
ImageData::Svg(svg) => {
// For an inline `<svg>` element the width/height attributes are
// presentation attributes: percentages resolve against the
// containing block. For SVG loaded as an image the intrinsic
// dimensions are context-free.
if *element_data.name.local == local_name!("svg") {
attr_size = taffy::Size {
width: svg.resolved_width(inputs.parent_size.width),
height: svg.resolved_height(inputs.parent_size.height),
};
}
let (mut width, mut height) = svg.intrinsic_size();
// A replaced element with only an intrinsic aspect ratio uses the
// stretch-fit width in normal flow (CSS2 §10.3.2): fill the
// definite available width and derive the height from the ratio.
// Shrink-to-fit contexts (floats, abspos) keep the default object
// size that `intrinsic_size` already applied.
if svg.intrinsic_width().is_none()
&& svg.intrinsic_height().is_none()
{
if let (
Some(ratio),
AvailableSpace::Definite(available_width),
) =
(svg.viewbox_aspect_ratio(), inputs.available_space.width)
{
width = available_width;
height = available_width / ratio;
}
}
(taffy::Size { width, height }, Some(svg.aspect_ratio()))
}
ImageData::None => (taffy::Size::ZERO, None),
},
// Canvas has an intrinsic size and aspect ratio given by its
// width/height attributes, defaulting to 300x150. Other replaced
// elements without intrinsic dimensions (video, iframe, embed) use
// the 300x150 default object size but have no intrinsic ratio.
SpecialElementData::Canvas(_)
| SpecialElementData::SubDocument(_)
| SpecialElementData::None => {
let tag_name = &element_data.name.local;
if *tag_name == local_name!("img") || *tag_name == local_name!("svg") {
(taffy::Size::ZERO, None)
} else {
let size = taffy::Size {
width: attr_size.width.unwrap_or(300.0),
height: attr_size.height.unwrap_or(150.0),
};
let ratio = (*tag_name == local_name!("canvas"))
.then(|| size.width / size.height);
(size, ratio)
}
}
_ => unreachable!(),
};
let replaced_context = ReplacedContext {
inherent_size,
attr_size,
inherent_ratio,
};
let computed = replaced_measure_function(
inputs.known_dimensions,
inputs.parent_size,
inputs.available_space,
&replaced_context,
node.style(),
inputs.sizing_mode,
inputs.axis,
);
return taffy::LayoutOutput {
size: computed,
content_size: computed,
first_baselines: taffy::Point::NONE,
top_margin: CollapsibleMarginSet::ZERO,
bottom_margin: CollapsibleMarginSet::ZERO,
margins_can_collapse_through: false,
};
}
if node.flags.is_table_root() {
let SpecialElementData::TableRoot(context) = &self.nodes[dom_node_id(node_id)]
.data
.downcast_element()
.unwrap()
.special_data
else {
panic!("Node marked as table root but doesn't have TableContext");
};
let context = Arc::clone(context);
let mut table_wrapper = TableTreeWrapper {
doc: self,
ctx: context,
};
let mut output = compute_grid_layout(&mut table_wrapper, node_id, inputs);
// HACK: Cap content size at node size to prevent scrolling
output.content_size.width = output.content_size.width.min(output.size.width);
output.content_size.height = output.content_size.height.min(output.size.height);
return output;
}
if node.flags.is_inline_root() {
return self.compute_inline_layout(dom_node_id(node_id), inputs, block_ctx);
}
// The default CSS file will set
match node.style().display {
Display::Block => compute_block_layout(self, node_id, inputs, block_ctx),
Display::FlowRoot => compute_block_layout(self, node_id, inputs, None),
Display::Flex => compute_flexbox_layout(self, node_id, inputs),
Display::Grid => compute_grid_layout(self, node_id, inputs),
Display::None => taffy::LayoutOutput::HIDDEN,
}
}
NodeData::Document(_) => compute_block_layout(self, node_id, inputs, None),
_ => taffy::LayoutOutput::HIDDEN,
}
}
}
impl TraversePartialTree for BaseDocument {
type ChildIter<'a> = RefCellChildIter<'a>;
fn child_ids(&self, node_id: NodeId) -> Self::ChildIter<'_> {
let layout_children = self.node_from_id(node_id).layout_children.borrow(); //.unwrap().as_ref();
RefCellChildIter::new(Ref::map(layout_children, |children| {
children.as_ref().map(|c| c.as_slice()).unwrap_or(&[])
}))
}
fn child_count(&self, node_id: NodeId) -> usize {
self.node_from_id(node_id)
.layout_children
.borrow()
.as_ref()
.map(|c| c.len())
.unwrap_or(0)
}
fn get_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
taffy_node_id(
self.node_from_id(node_id)
.layout_children
.borrow()
.as_ref()
.unwrap()[index],
)
}
}
impl TraverseTree for BaseDocument {}
impl LayoutPartialTree for BaseDocument {
type CoreContainerStyle<'a>
= &'a taffy::Style<Atom>
where
Self: 'a;
type CustomIdent = Atom;
fn get_core_container_style(&self, node_id: NodeId) -> &Style<Atom> {
self.node_from_id(node_id).style()
}
fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
*self.node_from_id_mut(node_id).unrounded_layout_mut() = *layout;
}
fn resolve_calc_value(&self, calc_ptr: *const (), parent_size: f32) -> f32 {
resolve_calc_value(calc_ptr, parent_size)
}
#[inline(always)]
fn compute_child_layout(
&mut self,
node_id: NodeId,
inputs: taffy::LayoutInput,
) -> taffy::LayoutOutput {
#[cfg(not(target_arch = "wasm32"))]
let probing = layout_panic_probe::enabled();
#[cfg(not(target_arch = "wasm32"))]
if probing {
layout_panic_probe::push(
dom_node_id(node_id),
self.describe_node_for_panic(dom_node_id(node_id), &inputs),
);
}
let output = compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
tree.compute_child_layout_internal(node_id, inputs, None)
});
// Only on the way out, so a panic leaves the stack standing for the
// hook to read. Nothing here runs after an abort.
#[cfg(not(target_arch = "wasm32"))]
if probing {
layout_panic_probe::pop();
}
output
}
}
impl taffy::CacheTree for BaseDocument {
#[inline]
fn cache_get(
&self,
node_id: NodeId,
inputs: &taffy::LayoutInput,
) -> Option<taffy::LayoutOutput> {
let found = self.node_from_id(node_id).cache().get(inputs);
#[cfg(feature = "log-phase-times")]
layout_counters::note_lookup(found.is_some());
found
}
#[inline]
fn cache_store(
&mut self,
node_id: NodeId,
inputs: &taffy::LayoutInput,
layout_output: taffy::LayoutOutput,
) {
self.node_from_id_mut(node_id)
.cache_mut()
.store(inputs, layout_output);
}
#[inline]
fn cache_clear(&mut self, node_id: NodeId) {
self.node_from_id_mut(node_id).cache_mut().clear();
}
}
impl taffy::LayoutBlockContainer for BaseDocument {
type BlockContainerStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
type BlockItemStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
self.get_core_container_style(node_id)
}
fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
self.get_core_container_style(child_node_id)
}
#[inline(always)]
fn compute_block_child_layout(
&mut self,
node_id: NodeId,
inputs: taffy::LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> taffy::LayoutOutput {
compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
tree.compute_child_layout_internal(node_id, inputs, block_ctx)
})
}
}
impl taffy::LayoutFlexboxContainer for BaseDocument {
type FlexboxContainerStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
type FlexboxItemStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
self.get_core_container_style(node_id)
}
fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
self.get_core_container_style(child_node_id)
}
}
impl taffy::LayoutGridContainer for BaseDocument {
type GridContainerStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
type GridItemStyle<'a>
= &'a Style<Atom>
where
Self: 'a;
fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
self.get_core_container_style(node_id)
}
fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
self.get_core_container_style(child_node_id)
}
fn set_detailed_grid_info(
&mut self,
node_id: NodeId,
detailed_grid_info: taffy::DetailedGridInfo,
) {
let node = self.node_from_id_mut(node_id);
if let Some(element) = node.element_data_mut() {
element.detailed_grid_info = Some(Box::new(detailed_grid_info));
}
}
}
impl RoundTree for BaseDocument {
fn get_unrounded_layout(&self, node_id: NodeId) -> Layout {
*self.node_from_id(node_id).unrounded_layout()
}
fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
*self.node_from_id_mut(node_id).final_layout_mut() = *layout;
}
}
impl PrintTree for BaseDocument {
fn get_debug_label(&self, node_id: NodeId) -> &'static str {
let node = &self.node_from_id(node_id);
match node.data {
NodeData::Document(_) => "DOCUMENT",
// NodeData::Doctype { .. } => return "DOCTYPE",
NodeData::Text { .. } => node.node_debug_str().leak(),
NodeData::Comment { .. } => "COMMENT",
NodeData::ShadowRoot(_) => "SHADOW ROOT",
NodeData::AnonymousBlock(_) => "ANONYMOUS BLOCK",
NodeData::Element(_) => {
let style = node.style();
let display = match style.display {
Display::Flex => match style.flex_direction {
FlexDirection::Row | FlexDirection::RowReverse => "FLEX ROW",
FlexDirection::Column | FlexDirection::ColumnReverse => "FLEX COL",
},
Display::Grid => "GRID",
Display::Block => "BLOCK",
Display::FlowRoot => "FLOW ROOT",
Display::None => "NONE",
};
format!("{} ({})", node.node_debug_str(), display).leak()
} // NodeData::ProcessingInstruction { .. } => return "PROCESSING INSTRUCTION",
}
}
fn get_final_layout(&self, node_id: NodeId) -> Layout {
*self.node_from_id(node_id).final_layout()
}
}
// pub struct ChildIter<'a>(std::slice::Iter<'a, usize>);
// impl<'a> Iterator for ChildIter<'a> {
// type Item = NodeId;
// fn next(&mut self) -> Option<Self::Item> {
// self.0.next().copied().map(NodeId::from)
// }
// }
pub struct RefCellChildIter<'a> {
items: Ref<'a, [crate::NodeId]>,
idx: usize,
}
impl<'a> RefCellChildIter<'a> {
fn new(items: Ref<'a, [crate::NodeId]>) -> RefCellChildIter<'a> {
RefCellChildIter { items, idx: 0 }
}
}
impl Iterator for RefCellChildIter<'_> {
type Item = NodeId;
fn next(&mut self) -> Option<Self::Item> {
self.items.get(self.idx).map(|id| {
self.idx += 1;
taffy_node_id(*id)
})
}
}