1use crate::geometry::{LayoutGeometry, Rect};
4use std::cell::{Cell, RefCell};
5use strata_style::types::{ComputedStyle, Display};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum StrokeLineCap {
10 #[default]
11 Butt,
12 Round,
13 Square,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum StrokeLineJoin {
19 #[default]
20 Miter,
21 Round,
22 Bevel,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum FillRule {
28 #[default]
29 NonZero,
30 EvenOdd,
31}
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct SvgTextData {
36 pub content: String,
37 pub x: f32,
38 pub y: f32,
39 pub font_size: f32,
40 pub font_weight: strata_style::types::FontWeight,
41 pub text_anchor: strata_style::TextAlign,
42}
43
44#[derive(Debug, Clone, PartialEq)]
46pub struct SvgItem {
47 pub path_data: String,
48 pub text: Option<SvgTextData>,
49 pub stroke_color: Option<strata_style::types::Color>,
50 pub fill_color: Option<strata_style::types::Color>,
51 pub stroke_is_current_color: bool,
52 pub fill_is_current_color: bool,
53 pub stroke_width: f32,
54 pub stroke_linecap: StrokeLineCap,
55 pub stroke_linejoin: StrokeLineJoin,
56 pub stroke_dasharray: Vec<f32>,
57 pub fill_rule: FillRule,
58 pub view_box: (f32, f32),
59}
60
61impl SvgItem {
62 pub fn new(path_data: String, view_box: (f32, f32)) -> Self {
63 Self {
64 path_data,
65 text: None,
66 stroke_color: None,
67 fill_color: None,
68 stroke_is_current_color: false,
69 fill_is_current_color: false,
70 stroke_width: 1.0,
71 stroke_linecap: StrokeLineCap::Butt,
72 stroke_linejoin: StrokeLineJoin::Miter,
73 stroke_dasharray: Vec::new(),
74 fill_rule: FillRule::NonZero,
75 view_box,
76 }
77 }
78}
79
80use crate::typography::{InlineItem, LineBox};
81
82#[derive(Debug, Clone, PartialEq)]
84pub struct ImageResource {
85 pub data: std::sync::Arc<Vec<u8>>,
86 pub width: u32,
87 pub height: u32,
88}
89
90#[inline]
93pub(crate) fn layout_style_pin_hash(style: &ComputedStyle) -> u64 {
94 use strata_style::types::Dimension;
95 #[inline(always)]
96 fn dim_bits(d: Dimension) -> u64 {
97 match d {
98 Dimension::Auto => 0x01,
99 Dimension::Px(v) => 0x02 | ((v.to_bits() as u64) << 8),
100 Dimension::Percent(v) => 0x03 | ((v.to_bits() as u64) << 8),
101 Dimension::Vw(v) => 0x04 | ((v.to_bits() as u64) << 8),
102 Dimension::Vh(v) => 0x05 | ((v.to_bits() as u64) << 8),
103 Dimension::Rem(v) => 0x06 | ((v.to_bits() as u64) << 8),
104 Dimension::Em(v) => 0x07 | ((v.to_bits() as u64) << 8),
105 Dimension::Calc(id) => 0x08 | ((id.0 as u64) << 8),
106 Dimension::MinContent => 0x09,
107 Dimension::MaxContent => 0x0A,
108 Dimension::FitContent(v) => 0x0B | ((v.to_bits() as u64) << 8),
109 }
110 }
111 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
112 let mut mix = |v: u64| {
113 h ^= v;
114 h = h.wrapping_mul(0x100_0000_01b3);
115 };
116 mix(dim_bits(style.width));
117 mix(dim_bits(style.height));
118 mix(dim_bits(style.min_width));
119 mix(dim_bits(style.max_width));
120 mix(dim_bits(style.min_height));
121 mix(dim_bits(style.max_height));
122 mix(dim_bits(style.flex_basis));
123 mix(style.flex_grow.to_bits() as u64);
124 mix(style.flex_shrink.to_bits() as u64);
125 mix(((style.overflow_x as u64) << 16)
126 | ((style.overflow_y as u64) << 8)
127 | ((style.white_space as u64) << 4)
128 | (style.text_overflow as u64));
129 h
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Default)]
134pub struct LayoutCacheEntry {
135 pub available_w: f32,
136 pub available_h: f32,
137 pub result_w: f32,
138 pub result_h: f32,
139 pub origin_x: f32,
140 pub origin_y: f32,
141 pub style_pin_hash: u64,
142 pub is_valid: bool,
143}
144
145impl LayoutCacheEntry {
146 #[inline]
147 pub const fn invalid() -> Self {
148 Self {
149 available_w: 0.0,
150 available_h: 0.0,
151 result_w: 0.0,
152 result_h: 0.0,
153 origin_x: 0.0,
154 origin_y: 0.0,
155 style_pin_hash: 0,
156 is_valid: false,
157 }
158 }
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Default)]
165pub struct MeasureCacheEntry {
166 pub available_w: f32,
167 pub available_h: f32,
168 pub style_pin_hash: u64,
169 pub result_w: f32,
170 pub result_h: f32,
171 pub baseline_offset: f32,
172 pub is_valid: bool,
173}
174
175impl MeasureCacheEntry {
176 #[inline]
177 pub const fn invalid() -> Self {
178 Self {
179 available_w: 0.0,
180 available_h: 0.0,
181 style_pin_hash: 0,
182 result_w: 0.0,
183 result_h: 0.0,
184 baseline_offset: 0.0,
185 is_valid: false,
186 }
187 }
188}
189
190pub struct IntrinsicCacheCell {
197 keys: [std::sync::atomic::AtomicU64; 2],
198 vals: [std::sync::atomic::AtomicU64; 2],
199}
200
201impl IntrinsicCacheCell {
202 #[inline]
203 pub const fn empty() -> Self {
204 Self {
205 keys: [
206 std::sync::atomic::AtomicU64::new(0),
207 std::sync::atomic::AtomicU64::new(0),
208 ],
209 vals: [
210 std::sync::atomic::AtomicU64::new(0),
211 std::sync::atomic::AtomicU64::new(0),
212 ],
213 }
214 }
215
216 #[inline]
217 fn encode_key(parent_size: Option<f32>) -> (usize, u64) {
218 match parent_size {
219 None => (0, 1),
220 Some(w) => (1, 2u64.wrapping_add(w.to_bits() as u64)),
221 }
222 }
223
224 #[inline]
225 pub fn get(&self, parent_size: Option<f32>) -> Option<crate::intrinsic::MinMaxSizes> {
226 let (slot, expected_key) = Self::encode_key(parent_size);
227 let k = self.keys[slot].load(std::sync::atomic::Ordering::Relaxed);
228 if k == expected_key {
229 let v = self.vals[slot].load(std::sync::atomic::Ordering::Relaxed);
230 let min_c = f32::from_bits(v as u32);
231 let max_c = f32::from_bits((v >> 32) as u32);
232 Some(crate::intrinsic::MinMaxSizes::new(min_c, max_c))
233 } else {
234 None
235 }
236 }
237
238 #[inline]
239 pub fn set(&self, parent_size: Option<f32>, sizes: crate::intrinsic::MinMaxSizes) {
240 let (slot, key) = Self::encode_key(parent_size);
241 let packed = (sizes.min_content.to_bits() as u64) | ((sizes.max_content.to_bits() as u64) << 32);
242 self.vals[slot].store(packed, std::sync::atomic::Ordering::Relaxed);
243 self.keys[slot].store(key, std::sync::atomic::Ordering::Relaxed);
244 }
245
246 #[inline]
247 pub fn clear(&self) {
248 self.keys[0].store(0, std::sync::atomic::Ordering::Relaxed);
249 self.keys[1].store(0, std::sync::atomic::Ordering::Relaxed);
250 }
251}
252
253impl Clone for IntrinsicCacheCell {
254 fn clone(&self) -> Self {
255 Self {
256 keys: [
257 std::sync::atomic::AtomicU64::new(
258 self.keys[0].load(std::sync::atomic::Ordering::Relaxed),
259 ),
260 std::sync::atomic::AtomicU64::new(
261 self.keys[1].load(std::sync::atomic::Ordering::Relaxed),
262 ),
263 ],
264 vals: [
265 std::sync::atomic::AtomicU64::new(
266 self.vals[0].load(std::sync::atomic::Ordering::Relaxed),
267 ),
268 std::sync::atomic::AtomicU64::new(
269 self.vals[1].load(std::sync::atomic::Ordering::Relaxed),
270 ),
271 ],
272 }
273 }
274}
275
276impl PartialEq for IntrinsicCacheCell {
277 fn eq(&self, _other: &Self) -> bool {
278 true
279 }
280}
281
282impl std::fmt::Debug for IntrinsicCacheCell {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.debug_struct("IntrinsicCacheCell").finish_non_exhaustive()
285 }
286}
287
288pub const MAX_LAYOUT_DEPTH: usize = 512;
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296pub struct LayoutDepthGuard {
297 depth: usize,
298 max_depth: usize,
299}
300
301impl LayoutDepthGuard {
302 #[inline]
304 pub const fn root() -> Self {
305 Self {
306 depth: 0,
307 max_depth: MAX_LAYOUT_DEPTH,
308 }
309 }
310
311 #[inline]
313 pub const fn with_max_depth(max_depth: usize) -> Self {
314 Self {
315 depth: 0,
316 max_depth,
317 }
318 }
319
320 #[inline]
322 pub fn enter(&self) -> Option<Self> {
323 if self.depth >= self.max_depth {
324 None
325 } else {
326 Some(Self {
327 depth: self.depth + 1,
328 max_depth: self.max_depth,
329 })
330 }
331 }
332
333 #[inline]
334 pub fn current_depth(&self) -> usize {
335 self.depth
336 }
337
338 #[inline]
339 pub fn max_depth(&self) -> usize {
340 self.max_depth
341 }
342
343 #[inline]
344 pub fn is_exhausted(&self) -> bool {
345 self.depth >= self.max_depth
346 }
347}
348
349type LayoutOverflowCallback = Box<dyn Fn(usize, usize) + Send + Sync>;
350
351thread_local! {
352 static LAYOUT_OVERFLOW_CALLBACK: RefCell<Option<LayoutOverflowCallback>> = const { RefCell::new(None) };
353 static LAST_LAYOUT_OVERFLOW: Cell<Option<(usize, usize)>> = const { Cell::new(None) };
354}
355
356pub fn set_on_layout_overflow<F: Fn(usize, usize) + Send + Sync + 'static>(cb: Option<F>) {
358 LAYOUT_OVERFLOW_CALLBACK.with(|c| {
359 *c.borrow_mut() = cb.map(|f| Box::new(f) as LayoutOverflowCallback);
360 });
361}
362
363pub fn last_layout_overflow() -> Option<(usize, usize)> {
365 LAST_LAYOUT_OVERFLOW.with(|c| c.get())
366}
367
368pub fn clear_layout_overflow() {
370 LAST_LAYOUT_OVERFLOW.with(|c| c.set(None));
371}
372
373pub fn record_layout_overflow(depth: usize, max_depth: usize) {
375 LAST_LAYOUT_OVERFLOW.with(|c| c.set(Some((depth, max_depth))));
376 LAYOUT_OVERFLOW_CALLBACK.with(|cb| {
377 if let Some(ref f) = *cb.borrow() {
378 f(depth, max_depth);
379 }
380 });
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
385pub enum AnchorPlacement {
386 Bottom,
387 BottomStart,
388 #[default]
389 BottomEnd,
390 Top,
391 TopStart,
392 TopEnd,
393 Left,
394 LeftStart,
395 LeftEnd,
396 Right,
397 RightStart,
398 RightEnd,
399}
400
401impl AnchorPlacement {
402 pub fn parse(raw: &str) -> Option<Self> {
404 match raw.trim().to_ascii_lowercase().as_str() {
405 "bottom" | "block-end" => Some(Self::Bottom),
406 "bottom-start" | "bottom_start" | "bottom-left" => Some(Self::BottomStart),
407 "bottom-end" | "bottom_end" | "bottom-right" => Some(Self::BottomEnd),
408 "top" | "block-start" => Some(Self::Top),
409 "top-start" | "top_start" | "top-left" => Some(Self::TopStart),
410 "top-end" | "top_end" | "top-right" => Some(Self::TopEnd),
411 "left" | "inline-start" => Some(Self::Left),
412 "left-start" | "left_start" | "left-top" => Some(Self::LeftStart),
413 "left-end" | "left_end" | "left-bottom" => Some(Self::LeftEnd),
414 "right" | "inline-end" => Some(Self::Right),
415 "right-start" | "right_start" | "right-top" => Some(Self::RightStart),
416 "right-end" | "right_end" | "right-bottom" => Some(Self::RightEnd),
417 _ => None,
418 }
419 }
420
421 pub const fn as_str(self) -> &'static str {
423 match self {
424 Self::Bottom => "bottom",
425 Self::BottomStart => "bottom-start",
426 Self::BottomEnd => "bottom-end",
427 Self::Top => "top",
428 Self::TopStart => "top-start",
429 Self::TopEnd => "top-end",
430 Self::Left => "left",
431 Self::LeftStart => "left-start",
432 Self::LeftEnd => "left-end",
433 Self::Right => "right",
434 Self::RightStart => "right-start",
435 Self::RightEnd => "right-end",
436 }
437 }
438
439 pub const fn opposite(self) -> Self {
441 match self {
442 Self::Bottom => Self::Top,
443 Self::BottomStart => Self::TopStart,
444 Self::BottomEnd => Self::TopEnd,
445 Self::Top => Self::Bottom,
446 Self::TopStart => Self::BottomStart,
447 Self::TopEnd => Self::BottomEnd,
448 Self::Left => Self::Right,
449 Self::LeftStart => Self::RightStart,
450 Self::LeftEnd => Self::RightEnd,
451 Self::Right => Self::Left,
452 Self::RightStart => Self::LeftStart,
453 Self::RightEnd => Self::LeftEnd,
454 }
455 }
456
457 #[inline]
458 fn raw_coords(
459 self,
460 anchor: crate::geometry::Rect,
461 floating_w: f32,
462 floating_h: f32,
463 offset: f32,
464 ) -> (f32, f32) {
465 match self {
466 Self::Bottom => (
467 anchor.x + (anchor.width - floating_w) * 0.5,
468 anchor.y + anchor.height + offset,
469 ),
470 Self::BottomStart => (anchor.x, anchor.y + anchor.height + offset),
471 Self::BottomEnd => (
472 anchor.x + anchor.width - floating_w,
473 anchor.y + anchor.height + offset,
474 ),
475 Self::Top => (
476 anchor.x + (anchor.width - floating_w) * 0.5,
477 anchor.y - floating_h - offset,
478 ),
479 Self::TopStart => (anchor.x, anchor.y - floating_h - offset),
480 Self::TopEnd => (
481 anchor.x + anchor.width - floating_w,
482 anchor.y - floating_h - offset,
483 ),
484 Self::Left => (
485 anchor.x - floating_w - offset,
486 anchor.y + (anchor.height - floating_h) * 0.5,
487 ),
488 Self::LeftStart => (anchor.x - floating_w - offset, anchor.y),
489 Self::LeftEnd => (
490 anchor.x - floating_w - offset,
491 anchor.y + anchor.height - floating_h,
492 ),
493 Self::Right => (
494 anchor.x + anchor.width + offset,
495 anchor.y + (anchor.height - floating_h) * 0.5,
496 ),
497 Self::RightStart => (anchor.x + anchor.width + offset, anchor.y),
498 Self::RightEnd => (
499 anchor.x + anchor.width + offset,
500 anchor.y + anchor.height - floating_h,
501 ),
502 }
503 }
504}
505
506#[allow(clippy::too_many_arguments)]
510pub fn solve_anchored_position(
511 anchor: crate::geometry::Rect,
512 floating_w: f32,
513 floating_h: f32,
514 placement: AnchorPlacement,
515 offset: f32,
516 flip: bool,
517 shift: bool,
518 padding: f32,
519 viewport: crate::geometry::Rect,
520) -> (f32, f32, AnchorPlacement) {
521 let min_x = viewport.x + padding;
522 let min_y = viewport.y + padding;
523 let max_x = (viewport.x + viewport.width - padding).max(min_x);
524 let max_y = (viewport.y + viewport.height - padding).max(min_y);
525
526 let axis_score = |cand: AnchorPlacement, cx: f32, cy: f32| -> f32 {
527 let left_ov = (min_x - cx).max(0.0);
528 let right_ov = (cx + floating_w - max_x).max(0.0);
529 let top_ov = (min_y - cy).max(0.0);
530 let bottom_ov = (cy + floating_h - max_y).max(0.0);
531 if !shift {
532 return left_ov + right_ov + top_ov + bottom_ov;
533 }
534 let cross_fits = left_ov <= 0.001 && right_ov <= 0.001;
537 let vert_fits = top_ov <= 0.001 && bottom_ov <= 0.001;
538 match cand {
539 AnchorPlacement::Bottom
540 | AnchorPlacement::BottomStart
541 | AnchorPlacement::BottomEnd
542 | AnchorPlacement::Top
543 | AnchorPlacement::TopStart
544 | AnchorPlacement::TopEnd => {
545 let main_ov = top_ov + bottom_ov;
546 if main_ov <= 0.001 && cross_fits {
547 0.0
548 } else {
549 main_ov
550 }
551 }
552 AnchorPlacement::Left
553 | AnchorPlacement::LeftStart
554 | AnchorPlacement::LeftEnd
555 | AnchorPlacement::Right
556 | AnchorPlacement::RightStart
557 | AnchorPlacement::RightEnd => {
558 let main_ov = left_ov + right_ov;
559 if main_ov <= 0.001 && vert_fits {
560 0.0
561 } else {
562 main_ov + (top_ov + bottom_ov) * 0.25
563 }
564 }
565 }
566 };
567
568 let candidates: [AnchorPlacement; 6] = if shift {
569 match placement {
570 AnchorPlacement::BottomStart => [
571 AnchorPlacement::BottomStart,
572 AnchorPlacement::TopStart,
573 AnchorPlacement::RightStart,
574 AnchorPlacement::LeftStart,
575 AnchorPlacement::BottomEnd,
576 AnchorPlacement::TopEnd,
577 ],
578 AnchorPlacement::BottomEnd => [
579 AnchorPlacement::BottomEnd,
580 AnchorPlacement::TopEnd,
581 AnchorPlacement::LeftEnd,
582 AnchorPlacement::RightEnd,
583 AnchorPlacement::BottomStart,
584 AnchorPlacement::TopStart,
585 ],
586 AnchorPlacement::Bottom => [
587 AnchorPlacement::Bottom,
588 AnchorPlacement::Top,
589 AnchorPlacement::Right,
590 AnchorPlacement::Left,
591 AnchorPlacement::BottomStart,
592 AnchorPlacement::BottomEnd,
593 ],
594 AnchorPlacement::TopStart => [
595 AnchorPlacement::TopStart,
596 AnchorPlacement::BottomStart,
597 AnchorPlacement::RightStart,
598 AnchorPlacement::LeftStart,
599 AnchorPlacement::TopEnd,
600 AnchorPlacement::BottomEnd,
601 ],
602 AnchorPlacement::TopEnd => [
603 AnchorPlacement::TopEnd,
604 AnchorPlacement::BottomEnd,
605 AnchorPlacement::LeftEnd,
606 AnchorPlacement::RightEnd,
607 AnchorPlacement::TopStart,
608 AnchorPlacement::BottomStart,
609 ],
610 AnchorPlacement::Top => [
611 AnchorPlacement::Top,
612 AnchorPlacement::Bottom,
613 AnchorPlacement::Right,
614 AnchorPlacement::Left,
615 AnchorPlacement::TopStart,
616 AnchorPlacement::TopEnd,
617 ],
618 AnchorPlacement::RightStart => [
619 AnchorPlacement::RightStart,
620 AnchorPlacement::LeftStart,
621 AnchorPlacement::BottomStart,
622 AnchorPlacement::TopStart,
623 AnchorPlacement::RightEnd,
624 AnchorPlacement::LeftEnd,
625 ],
626 AnchorPlacement::RightEnd => [
627 AnchorPlacement::RightEnd,
628 AnchorPlacement::LeftEnd,
629 AnchorPlacement::BottomEnd,
630 AnchorPlacement::TopEnd,
631 AnchorPlacement::RightStart,
632 AnchorPlacement::LeftStart,
633 ],
634 AnchorPlacement::Right => [
635 AnchorPlacement::Right,
636 AnchorPlacement::Left,
637 AnchorPlacement::Bottom,
638 AnchorPlacement::Top,
639 AnchorPlacement::RightStart,
640 AnchorPlacement::RightEnd,
641 ],
642 AnchorPlacement::LeftStart => [
643 AnchorPlacement::LeftStart,
644 AnchorPlacement::RightStart,
645 AnchorPlacement::BottomStart,
646 AnchorPlacement::TopStart,
647 AnchorPlacement::LeftEnd,
648 AnchorPlacement::RightEnd,
649 ],
650 AnchorPlacement::LeftEnd => [
651 AnchorPlacement::LeftEnd,
652 AnchorPlacement::RightEnd,
653 AnchorPlacement::BottomEnd,
654 AnchorPlacement::TopEnd,
655 AnchorPlacement::LeftStart,
656 AnchorPlacement::RightStart,
657 ],
658 AnchorPlacement::Left => [
659 AnchorPlacement::Left,
660 AnchorPlacement::Right,
661 AnchorPlacement::Bottom,
662 AnchorPlacement::Top,
663 AnchorPlacement::LeftStart,
664 AnchorPlacement::LeftEnd,
665 ],
666 }
667 } else {
668 match placement {
669 AnchorPlacement::BottomStart => [
670 AnchorPlacement::BottomStart,
671 AnchorPlacement::TopStart,
672 AnchorPlacement::BottomEnd,
673 AnchorPlacement::TopEnd,
674 AnchorPlacement::RightStart,
675 AnchorPlacement::LeftStart,
676 ],
677 AnchorPlacement::BottomEnd => [
678 AnchorPlacement::BottomEnd,
679 AnchorPlacement::TopEnd,
680 AnchorPlacement::BottomStart,
681 AnchorPlacement::TopStart,
682 AnchorPlacement::LeftEnd,
683 AnchorPlacement::RightEnd,
684 ],
685 AnchorPlacement::Bottom => [
686 AnchorPlacement::Bottom,
687 AnchorPlacement::Top,
688 AnchorPlacement::BottomStart,
689 AnchorPlacement::BottomEnd,
690 AnchorPlacement::Right,
691 AnchorPlacement::Left,
692 ],
693 AnchorPlacement::TopStart => [
694 AnchorPlacement::TopStart,
695 AnchorPlacement::BottomStart,
696 AnchorPlacement::TopEnd,
697 AnchorPlacement::BottomEnd,
698 AnchorPlacement::RightStart,
699 AnchorPlacement::LeftStart,
700 ],
701 AnchorPlacement::TopEnd => [
702 AnchorPlacement::TopEnd,
703 AnchorPlacement::BottomEnd,
704 AnchorPlacement::TopStart,
705 AnchorPlacement::BottomStart,
706 AnchorPlacement::LeftEnd,
707 AnchorPlacement::RightEnd,
708 ],
709 AnchorPlacement::Top => [
710 AnchorPlacement::Top,
711 AnchorPlacement::Bottom,
712 AnchorPlacement::TopStart,
713 AnchorPlacement::TopEnd,
714 AnchorPlacement::Right,
715 AnchorPlacement::Left,
716 ],
717 AnchorPlacement::RightStart => [
718 AnchorPlacement::RightStart,
719 AnchorPlacement::LeftStart,
720 AnchorPlacement::RightEnd,
721 AnchorPlacement::LeftEnd,
722 AnchorPlacement::BottomStart,
723 AnchorPlacement::TopStart,
724 ],
725 AnchorPlacement::RightEnd => [
726 AnchorPlacement::RightEnd,
727 AnchorPlacement::LeftEnd,
728 AnchorPlacement::RightStart,
729 AnchorPlacement::LeftStart,
730 AnchorPlacement::BottomEnd,
731 AnchorPlacement::TopEnd,
732 ],
733 AnchorPlacement::Right => [
734 AnchorPlacement::Right,
735 AnchorPlacement::Left,
736 AnchorPlacement::RightStart,
737 AnchorPlacement::RightEnd,
738 AnchorPlacement::Bottom,
739 AnchorPlacement::Top,
740 ],
741 AnchorPlacement::LeftStart => [
742 AnchorPlacement::LeftStart,
743 AnchorPlacement::RightStart,
744 AnchorPlacement::LeftEnd,
745 AnchorPlacement::RightEnd,
746 AnchorPlacement::BottomStart,
747 AnchorPlacement::TopStart,
748 ],
749 AnchorPlacement::LeftEnd => [
750 AnchorPlacement::LeftEnd,
751 AnchorPlacement::RightEnd,
752 AnchorPlacement::LeftStart,
753 AnchorPlacement::RightStart,
754 AnchorPlacement::BottomEnd,
755 AnchorPlacement::TopEnd,
756 ],
757 AnchorPlacement::Left => [
758 AnchorPlacement::Left,
759 AnchorPlacement::Right,
760 AnchorPlacement::LeftStart,
761 AnchorPlacement::LeftEnd,
762 AnchorPlacement::Bottom,
763 AnchorPlacement::Top,
764 ],
765 }
766 };
767
768 let mut chosen = placement;
769 let (mut x, mut y) = chosen.raw_coords(anchor, floating_w, floating_h, offset);
770
771 if flip {
772 let eval_len = if shift { 4 } else { candidates.len() };
773 let mut best_score = axis_score(chosen, x, y);
774 if best_score > 0.001 {
775 for &cand in &candidates[1..eval_len] {
776 let (cx, cy) = cand.raw_coords(anchor, floating_w, floating_h, offset);
777 let score = axis_score(cand, cx, cy);
778 if score + 0.001 < best_score {
779 best_score = score;
780 chosen = cand;
781 x = cx;
782 y = cy;
783 if best_score <= 0.001 {
784 break;
785 }
786 }
787 }
788 }
789 }
790
791 if shift {
792 let upper_x = (max_x - floating_w).max(min_x);
793 let upper_y = (max_y - floating_h).max(min_y);
794 x = x.clamp(min_x, upper_x);
795 y = y.clamp(min_y, upper_y);
796 }
797
798 (x, y, chosen)
799}
800
801#[derive(Debug, Clone, PartialEq)]
803pub struct PortalAnchorSpec {
804 pub anchor_id: String,
805 pub placement: AnchorPlacement,
806 pub offset: f32,
807 pub flip: bool,
808 pub shift: bool,
809 pub viewport_padding: f32,
810 pub match_width: bool,
811 pub min_width_from_anchor: bool,
812}
813
814impl PortalAnchorSpec {
815 pub fn new(anchor_id: impl Into<String>, placement: AnchorPlacement) -> Self {
816 Self {
817 anchor_id: anchor_id.into(),
818 placement,
819 offset: 4.0,
820 flip: true,
821 shift: true,
822 viewport_padding: 8.0,
823 match_width: false,
824 min_width_from_anchor: false,
825 }
826 }
827}
828
829#[derive(Clone)]
832pub struct ViewportSceneHandle(pub std::sync::Arc<dyn std::any::Any + Send + Sync>);
833
834impl std::fmt::Debug for ViewportSceneHandle {
835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836 f.debug_tuple("ViewportSceneHandle")
837 .field(&"<scene_3d>")
838 .finish()
839 }
840}
841
842impl PartialEq for ViewportSceneHandle {
843 fn eq(&self, other: &Self) -> bool {
844 std::sync::Arc::ptr_eq(&self.0, &other.0)
845 }
846}
847
848pub const SUBTREE_HAS_TOP_LAYER: u8 = 1 << 0;
850pub const SUBTREE_HAS_HOISTED: u8 = 1 << 1;
851pub const SUBTREE_HAS_TRANSFORM: u8 = 1 << 2;
852pub const SUBTREE_META_VALID: u8 = 1 << 3;
853pub const SUBTREE_HAS_HEIGHT_DEP_DESCENDANT: u8 = 1 << 4;
856
857#[derive(Debug, Clone, PartialEq)]
859pub struct LayoutNode {
860 pub style: ComputedStyle,
861 pub geometry: LayoutGeometry,
862 pub children: Vec<LayoutNode>,
863 pub text: Option<String>,
864 pub svg_path: Option<String>,
865 pub svg_items: Vec<SvgItem>,
866 pub image: Option<ImageResource>,
867 pub scene_3d: Option<ViewportSceneHandle>,
868 pub inline_items: Vec<InlineItem>,
869 pub line_boxes: Vec<LineBox>,
870 pub layout_cache: LayoutCacheEntry,
871 pub measure_cache: [MeasureCacheEntry; 2],
874 pub intrinsic_cache: IntrinsicCacheCell,
876 pub last_child_layout_content: Option<(f32, f32)>,
878 pub children_layout_clean: bool,
881 pub last_preserved_box: Option<(f32, f32, f32, f32, bool)>,
884 pub applied_relative_offset: (f32, f32),
887 pub table_grid: Option<crate::table::TableBorderGrid>,
889 pub entity_id: strata_primitives::EntityId,
891 pub active_transitions: bool,
893 pub element_id: Option<String>,
895 pub anchor_name: Option<String>,
897 pub is_top_layer: bool,
900 pub portal_anchor: Option<Box<PortalAnchorSpec>>,
902 pub subtree_hit_flags: u8,
904 pub subtree_bounds: Rect,
906 pub transition_layout_width_px: Option<f32>,
908 pub transition_layout_height_px: Option<f32>,
910}
911
912impl LayoutNode {
913 pub fn new(style: ComputedStyle) -> Self {
915 Self {
916 style,
917 geometry: LayoutGeometry::default(),
918 children: Vec::new(),
919 text: None,
920 svg_path: None,
921 svg_items: Vec::new(),
922 image: None,
923 scene_3d: None,
924 inline_items: Vec::new(),
925 line_boxes: Vec::new(),
926 layout_cache: LayoutCacheEntry::invalid(),
927 measure_cache: [MeasureCacheEntry::invalid(); 2],
928 intrinsic_cache: IntrinsicCacheCell::empty(),
929 last_child_layout_content: None,
930 children_layout_clean: false,
931 last_preserved_box: None,
932 applied_relative_offset: (0.0, 0.0),
933 table_grid: None,
934 entity_id: strata_primitives::EntityId::NONE,
935 active_transitions: false,
936 element_id: None,
937 anchor_name: None,
938 is_top_layer: false,
939 portal_anchor: None,
940 subtree_hit_flags: 0,
941 subtree_bounds: Rect::new(0.0, 0.0, 0.0, 0.0),
942 transition_layout_width_px: None,
943 transition_layout_height_px: None,
944 }
945 }
946
947 pub fn with_children(style: ComputedStyle, children: Vec<LayoutNode>) -> Self {
949 let mut node = Self::new(style);
950 node.children = children;
951 node
952 }
953
954 pub fn with_text(style: ComputedStyle, text: String) -> Self {
956 let mut node = Self::new(style);
957 node.text = Some(text);
958 node
959 }
960
961 pub fn with_inline_items(style: ComputedStyle, inline_items: Vec<InlineItem>) -> Self {
963 let mut node = Self::new(style);
964 node.inline_items = inline_items;
965 node
966 }
967
968 pub fn with_svg_path(style: ComputedStyle, svg_path: String) -> Self {
970 let mut node = Self::new(style);
971 node.svg_path = Some(svg_path.clone());
972 node.svg_items = vec![SvgItem {
973 path_data: svg_path,
974 stroke_color: None,
975 fill_color: None,
976 stroke_is_current_color: true,
977 fill_is_current_color: false,
978 stroke_width: 2.0,
979 stroke_linecap: StrokeLineCap::Round,
980 stroke_linejoin: StrokeLineJoin::Round,
981 stroke_dasharray: Vec::new(),
982 fill_rule: FillRule::NonZero,
983 view_box: (24.0, 24.0),
984 text: None,
985 }];
986 node
987 }
988
989 pub fn with_svg_items(style: ComputedStyle, svg_items: Vec<SvgItem>) -> Self {
991 let first_path = svg_items.first().map(|i| i.path_data.clone());
992 let mut node = Self::new(style);
993 node.svg_path = first_path;
994 node.svg_items = svg_items;
995 node
996 }
997
998 pub fn with_image(style: ComputedStyle, image: ImageResource) -> Self {
1000 let mut node = Self::new(style);
1001 node.image = Some(image);
1002 node
1003 }
1004
1005 pub fn has_active_transitions(&self) -> bool {
1007 let mut stack = vec![self];
1008 while let Some(node) = stack.pop() {
1009 if node.active_transitions {
1010 return true;
1011 }
1012 for child in &node.children {
1013 stack.push(child);
1014 }
1015 }
1016 false
1017 }
1018
1019 #[inline]
1022 pub fn transition_content_width(&self) -> Option<f32> {
1023 let inset_h = self.style.padding.left
1024 + self.style.padding.right
1025 + self.style.border_width.left
1026 + self.style.border_width.right;
1027 self.transition_layout_width_px
1028 .map(|w| (w - inset_h).max(0.0))
1029 }
1030
1031 #[inline]
1033 pub fn transition_content_height(&self) -> Option<f32> {
1034 let inset_v = self.style.padding.top
1035 + self.style.padding.bottom
1036 + self.style.border_width.top
1037 + self.style.border_width.bottom;
1038 self.transition_layout_height_px
1039 .map(|h| (h - inset_v).max(0.0))
1040 }
1041
1042 pub fn with_scene_3d(mut self, handle: ViewportSceneHandle) -> Self {
1044 self.scene_3d = Some(handle);
1045 self
1046 }
1047
1048 pub fn set_scene_3d(&mut self, handle: Option<ViewportSceneHandle>) {
1050 self.scene_3d = handle;
1051 }
1052
1053 pub fn with_entity_id(mut self, entity_id: strata_primitives::EntityId) -> Self {
1055 self.entity_id = entity_id;
1056 self
1057 }
1058
1059 pub fn set_entity_id(&mut self, entity_id: strata_primitives::EntityId) {
1061 self.entity_id = entity_id;
1062 }
1063
1064 pub fn find_by_entity_id(&self, target_id: strata_primitives::EntityId) -> Option<&LayoutNode> {
1066 if !target_id.is_valid() {
1067 return None;
1068 }
1069 let mut stack = vec![self];
1070 while let Some(node) = stack.pop() {
1071 if node.entity_id == target_id {
1072 return Some(node);
1073 }
1074 for child in node.children.iter().rev() {
1075 stack.push(child);
1076 }
1077 }
1078 None
1079 }
1080
1081 pub fn find_by_entity_id_mut(
1083 &mut self,
1084 target_id: strata_primitives::EntityId,
1085 ) -> Option<&mut LayoutNode> {
1086 if !target_id.is_valid() {
1087 return None;
1088 }
1089 let mut stack = vec![self];
1090 while let Some(node) = stack.pop() {
1091 if node.entity_id == target_id {
1092 return Some(node);
1093 }
1094 for child in node.children.iter_mut().rev() {
1095 stack.push(child);
1096 }
1097 }
1098 None
1099 }
1100
1101 pub fn add_child(&mut self, child: LayoutNode) {
1103 self.children.push(child);
1104 }
1105
1106 #[inline]
1108 pub fn establishes_stacking_context_in(
1109 &self,
1110 parent_display: Option<Display>,
1111 is_root: bool,
1112 ) -> bool {
1113 self.style
1114 .establishes_stacking_context_in(parent_display, is_root)
1115 }
1116
1117 pub fn translate(&mut self, dx: f32, dy: f32) {
1119 if dx == 0.0 && dy == 0.0 {
1120 return;
1121 }
1122
1123 let mut stack: Vec<&mut LayoutNode> = vec![self];
1124 while let Some(node) = stack.pop() {
1125 node.geometry.translate(dx, dy);
1126 node.subtree_bounds.x += dx;
1127 node.subtree_bounds.y += dy;
1128 node.layout_cache.origin_x += dx;
1129 node.layout_cache.origin_y += dy;
1130 if let Some(ref mut pb) = node.last_preserved_box {
1131 pb.0 += dx;
1132 pb.1 += dy;
1133 }
1134 for line in &mut node.line_boxes {
1135 line.bounds.x += dx;
1136 line.bounds.y += dy;
1137 for frag in &mut line.text_fragments {
1138 frag.bounds.x += dx;
1139 frag.bounds.y += dy;
1140 frag.baseline_y += dy;
1141 }
1142 for atomic in &mut line.atomic_fragments {
1143 atomic.bounds.x += dx;
1144 atomic.bounds.y += dy;
1145 }
1146 }
1147 if let Some(ref mut grid) = node.table_grid {
1148 grid.translate(dx, dy);
1149 }
1150 for child in &mut node.children {
1151 stack.push(child);
1152 }
1153 }
1154 }
1155
1156 pub fn translate_scrolled(
1163 &mut self,
1164 dx: f32,
1165 dy: f32,
1166 parent_is_abs_cb: bool,
1167 parent_is_fixed_cb: bool,
1168 ) {
1169 if dx == 0.0 && dy == 0.0 {
1170 return;
1171 }
1172
1173 let mut stack: Vec<(&mut LayoutNode, bool, bool)> =
1174 vec![(self, parent_is_abs_cb, parent_is_fixed_cb)];
1175 while let Some((node, abs_cb_inside, fixed_cb_inside)) = stack.pop() {
1176 if node.is_top_layer {
1177 continue;
1178 }
1179 match node.style.position {
1180 strata_style::types::Position::Fixed if !fixed_cb_inside => {
1181 continue;
1182 }
1183 strata_style::types::Position::Absolute if !abs_cb_inside => {
1184 continue;
1185 }
1186 _ => {}
1187 }
1188
1189 node.geometry.translate(dx, dy);
1190 node.subtree_bounds.x += dx;
1191 node.subtree_bounds.y += dy;
1192 node.layout_cache.origin_x += dx;
1193 node.layout_cache.origin_y += dy;
1194 if let Some(ref mut pb) = node.last_preserved_box {
1195 pb.0 += dx;
1196 pb.1 += dy;
1197 }
1198 for line in &mut node.line_boxes {
1199 line.bounds.x += dx;
1200 line.bounds.y += dy;
1201 for frag in &mut line.text_fragments {
1202 frag.bounds.x += dx;
1203 frag.bounds.y += dy;
1204 frag.baseline_y += dy;
1205 }
1206 for atomic in &mut line.atomic_fragments {
1207 atomic.bounds.x += dx;
1208 atomic.bounds.y += dy;
1209 }
1210 }
1211 if let Some(ref mut grid) = node.table_grid {
1212 grid.translate(dx, dy);
1213 }
1214
1215 let child_fixed_cb = fixed_cb_inside || node.style.establishes_fixed_containing_block();
1216 let child_abs_cb = abs_cb_inside
1217 || node.style.position != strata_style::types::Position::Static
1218 || child_fixed_cb;
1219
1220 for child in &mut node.children {
1221 stack.push((child, child_abs_cb, child_fixed_cb));
1222 }
1223 }
1224 }
1225
1226 pub fn layout_children(&mut self) {
1228 self.layout_children_guarded(LayoutDepthGuard::root());
1229 }
1230
1231 pub fn layout_children_guarded(&mut self, guard: LayoutDepthGuard) {
1233 self.layout_children_inner_guarded(guard, true);
1234 }
1235
1236 pub(crate) fn layout_children_inner_guarded(
1237 &mut self,
1238 guard: LayoutDepthGuard,
1239 resolve_positioned: bool,
1240 ) {
1241 if (self.children.is_empty() && self.inline_items.is_empty()) || guard.is_exhausted() {
1242 return;
1243 }
1244
1245 let content_w = self.geometry.content_box.width;
1246 let content_h = self.geometry.content_box.height;
1247 let preserved_geom = self.geometry;
1248
1249 if self.children_layout_clean {
1253 if let Some((prev_x, prev_y, prev_w, prev_h, prev_pos)) = self.last_preserved_box {
1254 if prev_pos == resolve_positioned
1255 && (prev_w - preserved_geom.border_box.width).abs() < 0.05
1256 && (prev_h - preserved_geom.border_box.height).abs() < 0.05
1257 && self.last_child_layout_content.is_some_and(|(cw, ch)| {
1258 (cw - content_w).abs() < 0.05 && (ch - content_h).abs() < 0.05
1259 })
1260 {
1261 let dx = preserved_geom.border_box.x - prev_x;
1262 let dy = preserved_geom.border_box.y - prev_y;
1263 if dx.abs() > 0.001 || dy.abs() > 0.001 {
1264 self.subtree_bounds.x += dx;
1265 self.subtree_bounds.y += dy;
1266 for line in &mut self.line_boxes {
1267 line.bounds.x += dx;
1268 line.bounds.y += dy;
1269 for frag in &mut line.text_fragments {
1270 frag.bounds.x += dx;
1271 frag.bounds.y += dy;
1272 frag.baseline_y += dy;
1273 }
1274 for at in &mut line.atomic_fragments {
1275 at.bounds.x += dx;
1276 at.bounds.y += dy;
1277 }
1278 }
1279 for child in &mut self.children {
1280 child.translate(dx, dy);
1281 }
1282 self.last_preserved_box = Some((
1283 preserved_geom.border_box.x,
1284 preserved_geom.border_box.y,
1285 prev_w,
1286 prev_h,
1287 prev_pos,
1288 ));
1289 }
1290 return;
1291 }
1292 }
1293 }
1294
1295 self.subtree_hit_flags &= !SUBTREE_META_VALID;
1296
1297 let saved_w = self.style.width;
1298 let saved_h = self.style.height;
1299 let saved_min_w = self.style.min_width;
1300 let saved_max_w = self.style.max_width;
1301 let saved_min_h = self.style.min_height;
1302 let saved_max_h = self.style.max_height;
1303
1304 let pin_w = preserved_geom.border_box.width > 0.0
1305 || matches!(saved_w, strata_style::types::Dimension::Percent(_));
1306 let pin_h = preserved_geom.border_box.height > 0.0
1307 || matches!(saved_h, strata_style::types::Dimension::Percent(_));
1308
1309 let container_avail_w = if pin_w {
1310 self.style.width = strata_style::types::Dimension::Px(preserved_geom.border_box.width);
1311 self.style.min_width = strata_style::types::Dimension::Auto;
1312 self.style.max_width = strata_style::types::Dimension::Auto;
1313 preserved_geom.border_box.width
1314 } else {
1315 preserved_geom.border_box.width + self.style.margin.left + self.style.margin.right
1316 };
1317
1318 let container_avail_h = if pin_h {
1319 let pinned_h = if saved_h == strata_style::types::Dimension::Auto {
1320 crate::box_model::clamp_dimension_with_node(
1321 preserved_geom.border_box.height,
1322 saved_min_h,
1323 saved_max_h,
1324 content_h.max(preserved_geom.border_box.height),
1325 self,
1326 )
1327 } else {
1328 preserved_geom.border_box.height
1329 };
1330 self.style.height = strata_style::types::Dimension::Px(pinned_h);
1331 self.style.min_height = strata_style::types::Dimension::Auto;
1332 self.style.max_height = strata_style::types::Dimension::Auto;
1333 pinned_h
1334 } else {
1335 preserved_geom.border_box.height + self.style.margin.top + self.style.margin.bottom
1336 };
1337
1338 match self.style.display {
1339 Display::Flex | Display::InlineFlex => {
1340 let definite_cross = if content_h > 0.0 && !pin_h {
1341 Some(content_h)
1342 } else {
1343 None
1344 };
1345 crate::flexbox::solve_flexbox_with_definite_cross_guarded(
1346 self,
1347 container_avail_w,
1348 container_avail_h,
1349 definite_cross,
1350 guard,
1351 );
1352 }
1353 Display::Grid | Display::InlineGrid => {
1354 crate::grid::solve_grid_guarded(self, container_avail_w, container_avail_h, guard);
1355 }
1356 Display::Table | Display::InlineTable => {
1357 crate::table::solve_table_guarded(
1358 self,
1359 container_avail_w,
1360 container_avail_h,
1361 guard,
1362 );
1363 }
1364 Display::Block
1365 | Display::ListItem
1366 | Display::Inline
1367 | Display::InlineBlock
1368 | Display::TableRowGroup
1369 | Display::TableHeaderGroup
1370 | Display::TableFooterGroup
1371 | Display::TableRow
1372 | Display::TableCell
1373 | Display::TableCaption
1374 | Display::TableColumnGroup
1375 | Display::TableColumn => {
1376 let block_h = crate::box_model::solve_block_children_with_exclusions_guarded(
1377 self, content_w, content_h, None, 0.0, guard,
1378 );
1379 if saved_h == strata_style::types::Dimension::Auto {
1380 self.geometry.border_box.height = block_h;
1381 }
1382 }
1383 Display::None => {}
1384 }
1385
1386 self.style.width = saved_w;
1387 self.style.height = saved_h;
1388 self.style.min_width = saved_min_w;
1389 self.style.max_width = saved_max_w;
1390 self.style.min_height = saved_min_h;
1391 self.style.max_height = saved_max_h;
1392
1393 let clamp_avail_h = preserved_geom.border_box.height.max(content_h);
1394 if self.style.height == strata_style::types::Dimension::Auto {
1395 self.geometry.border_box.height = crate::box_model::clamp_dimension_with_node(
1396 self.geometry.border_box.height,
1397 saved_min_h,
1398 saved_max_h,
1399 clamp_avail_h,
1400 self,
1401 );
1402 }
1403
1404 let clips_y = self.style.overflow_y != strata_style::types::Overflow::Visible;
1405 let final_h = if self.style.height == strata_style::types::Dimension::Auto && !clips_y {
1406 let unclipped = self
1407 .geometry
1408 .border_box
1409 .height
1410 .max(preserved_geom.border_box.height);
1411 crate::box_model::clamp_dimension_with_node(
1412 unclipped,
1413 saved_min_h,
1414 saved_max_h,
1415 clamp_avail_h,
1416 self,
1417 )
1418 } else if preserved_geom.border_box.height > 0.0 {
1419 if self.style.height == strata_style::types::Dimension::Auto {
1420 crate::box_model::clamp_dimension_with_node(
1421 preserved_geom.border_box.height,
1422 saved_min_h,
1423 saved_max_h,
1424 clamp_avail_h,
1425 self,
1426 )
1427 } else {
1428 preserved_geom.border_box.height
1429 }
1430 } else {
1431 self.geometry.border_box.height
1432 };
1433
1434 let clips_x = self.style.overflow_x != strata_style::types::Overflow::Visible;
1435 let final_w = if self.style.width == strata_style::types::Dimension::Auto && !clips_x {
1436 self.geometry
1437 .border_box
1438 .width
1439 .max(preserved_geom.border_box.width)
1440 } else if preserved_geom.border_box.width > 0.0 {
1441 preserved_geom.border_box.width
1442 } else {
1443 self.geometry.border_box.width
1444 };
1445
1446 self.geometry = LayoutGeometry::from_border_box(
1447 crate::geometry::Rect::new(
1448 preserved_geom.border_box.x,
1449 preserved_geom.border_box.y,
1450 final_w,
1451 final_h,
1452 ),
1453 self.style.padding,
1454 self.style.border_width,
1455 self.style.margin,
1456 );
1457
1458 if resolve_positioned && self.style.position != strata_style::types::Position::Static {
1459 crate::positioning::solve_positioning_guarded(self, content_w, content_h, guard);
1460 }
1461 self.geometry.snap_to_pixel();
1462 self.update_scroll_metrics();
1463 self.last_child_layout_content = Some((content_w, content_h));
1464 self.children_layout_clean = true;
1465 self.last_preserved_box = Some((
1466 self.geometry.border_box.x,
1467 self.geometry.border_box.y,
1468 self.geometry.border_box.width,
1469 self.geometry.border_box.height,
1470 resolve_positioned,
1471 ));
1472 self.layout_cache.is_valid = false;
1473 }
1474
1475 pub fn compute_layout(&mut self, available_width: f32, available_height: f32) {
1477 let session_root = crate::intrinsic::begin_layout_session();
1478 let _guard = crate::prof::LayoutGuard::new();
1479 let guard = LayoutDepthGuard::root();
1480 self.compute_layout_guarded(available_width, available_height, None, 0.0, guard);
1481 crate::intrinsic::end_layout_session(session_root);
1482 self.refresh_subtree_hit_metadata();
1483 }
1484
1485 pub fn compute_layout_with_exclusions(
1487 &mut self,
1488 available_width: f32,
1489 available_height: f32,
1490 exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1491 bfc_offset_y: f32,
1492 ) {
1493 let guard = LayoutDepthGuard::root();
1494 self.compute_layout_guarded(
1495 available_width,
1496 available_height,
1497 exclusions,
1498 bfc_offset_y,
1499 guard,
1500 );
1501 self.refresh_subtree_hit_metadata();
1502 }
1503
1504 pub fn refresh_subtree_hit_metadata(&mut self) {
1508 if !Self::node_needs_hit_metadata_refresh(self, None, true) {
1509 return;
1510 }
1511 if matches!(self.style.display, strata_style::types::Display::None)
1512 || self.children.is_empty()
1513 {
1514 Self::finalize_node_hit_metadata(self, None, true);
1515 return;
1516 }
1517
1518 struct MetaFrame {
1519 node: LayoutNode,
1520 parent_display: Option<strata_style::types::Display>,
1521 remaining_rev: Vec<LayoutNode>,
1522 processed: Vec<LayoutNode>,
1523 }
1524
1525 let root_display = Some(self.style.display);
1526 let mut root_remaining = std::mem::take(&mut self.children);
1527 root_remaining.reverse();
1528 let mut root_processed = Vec::with_capacity(root_remaining.len());
1529 let mut stack: Vec<MetaFrame> = Vec::new();
1530
1531 loop {
1532 if let Some(top) = stack.last_mut() {
1533 if let Some(mut child) = top.remaining_rev.pop() {
1534 let parent_disp = Some(top.node.style.display);
1535 if !Self::node_needs_hit_metadata_refresh(&child, parent_disp, false) {
1536 top.processed.push(child);
1537 } else if matches!(child.style.display, strata_style::types::Display::None)
1538 || child.children.is_empty()
1539 {
1540 Self::finalize_node_hit_metadata(&mut child, parent_disp, false);
1541 top.processed.push(child);
1542 } else {
1543 let mut sub = std::mem::take(&mut child.children);
1544 sub.reverse();
1545 let cap = sub.len();
1546 stack.push(MetaFrame {
1547 node: child,
1548 parent_display: parent_disp,
1549 remaining_rev: sub,
1550 processed: Vec::with_capacity(cap),
1551 });
1552 }
1553 } else {
1554 let mut frame = stack.pop().unwrap();
1555 frame.node.children = frame.processed;
1556 Self::finalize_node_hit_metadata(&mut frame.node, frame.parent_display, false);
1557 if let Some(parent) = stack.last_mut() {
1558 parent.processed.push(frame.node);
1559 } else {
1560 root_processed.push(frame.node);
1561 }
1562 }
1563 } else if let Some(mut child) = root_remaining.pop() {
1564 if !Self::node_needs_hit_metadata_refresh(&child, root_display, false) {
1565 root_processed.push(child);
1566 } else if matches!(child.style.display, strata_style::types::Display::None)
1567 || child.children.is_empty()
1568 {
1569 Self::finalize_node_hit_metadata(&mut child, root_display, false);
1570 root_processed.push(child);
1571 } else {
1572 let mut sub = std::mem::take(&mut child.children);
1573 sub.reverse();
1574 let cap = sub.len();
1575 stack.push(MetaFrame {
1576 node: child,
1577 parent_display: root_display,
1578 remaining_rev: sub,
1579 processed: Vec::with_capacity(cap),
1580 });
1581 }
1582 } else {
1583 break;
1584 }
1585 }
1586
1587 self.children = root_processed;
1588 Self::finalize_node_hit_metadata(self, None, true);
1589 }
1590
1591 #[inline]
1592 fn node_needs_hit_metadata_refresh(
1593 node: &LayoutNode,
1594 parent_display: Option<strata_style::types::Display>,
1595 is_root: bool,
1596 ) -> bool {
1597 let self_hoisted = !is_root
1598 && (node.style.position != strata_style::types::Position::Static
1599 || node.establishes_stacking_context_in(parent_display, false));
1600 !((node.subtree_hit_flags & SUBTREE_META_VALID) != 0
1601 && (!self_hoisted || (node.subtree_hit_flags & SUBTREE_HAS_HOISTED) != 0))
1602 }
1603
1604 #[inline]
1605 fn is_self_height_dependent(&self) -> bool {
1606 use strata_style::types::{Dimension, Position};
1607 matches!(self.style.height, Dimension::Percent(_))
1608 || matches!(self.style.min_height, Dimension::Percent(_))
1609 || matches!(self.style.max_height, Dimension::Percent(_))
1610 || matches!(self.style.flex_basis, Dimension::Percent(_))
1611 || (matches!(self.style.position, Position::Absolute | Position::Fixed)
1612 && (!matches!(self.style.insets.bottom, Dimension::Auto)
1613 || matches!(self.style.insets.top, Dimension::Percent(_))))
1614 }
1615
1616 fn finalize_node_hit_metadata(
1617 node: &mut LayoutNode,
1618 parent_display: Option<strata_style::types::Display>,
1619 is_root: bool,
1620 ) {
1621 if matches!(node.style.display, strata_style::types::Display::None) {
1622 node.subtree_hit_flags = SUBTREE_META_VALID;
1623 node.subtree_bounds = Rect::new(0.0, 0.0, 0.0, 0.0);
1624 return;
1625 }
1626
1627 let self_hoisted = !is_root
1628 && (node.style.position != strata_style::types::Position::Static
1629 || node.establishes_stacking_context_in(parent_display, false));
1630
1631 let mut flags = SUBTREE_META_VALID;
1632 if node.is_top_layer {
1633 flags |= SUBTREE_HAS_TOP_LAYER;
1634 }
1635 if node.style.has_transform() {
1636 flags |= SUBTREE_HAS_TRANSFORM;
1637 }
1638 if self_hoisted {
1639 flags |= SUBTREE_HAS_HOISTED;
1640 }
1641
1642 let own = node.geometry.border_box;
1643 let mut min_x = own.x;
1644 let mut min_y = own.y;
1645 let mut max_x = own.x + own.width.max(0.0);
1646 let mut max_y = own.y + own.height.max(0.0);
1647 let mut has_bounds = own.width > 0.0 || own.height > 0.0 || node.children.is_empty();
1648
1649 let union_rect = |r: Rect,
1650 min_x: &mut f32,
1651 min_y: &mut f32,
1652 max_x: &mut f32,
1653 max_y: &mut f32,
1654 has_bounds: &mut bool| {
1655 let rx1 = r.x + r.width.max(0.0);
1656 let ry1 = r.y + r.height.max(0.0);
1657 if *has_bounds {
1658 *min_x = min_x.min(r.x);
1659 *min_y = min_y.min(r.y);
1660 *max_x = max_x.max(rx1);
1661 *max_y = max_y.max(ry1);
1662 } else {
1663 *min_x = r.x;
1664 *min_y = r.y;
1665 *max_x = rx1;
1666 *max_y = ry1;
1667 *has_bounds = true;
1668 }
1669 };
1670
1671 for line in &node.line_boxes {
1672 if line.bounds.width > 0.0 || line.bounds.height > 0.0 {
1673 union_rect(
1674 line.bounds,
1675 &mut min_x,
1676 &mut min_y,
1677 &mut max_x,
1678 &mut max_y,
1679 &mut has_bounds,
1680 );
1681 }
1682 }
1683
1684 let self_display = Some(node.style.display);
1685 for child in &node.children {
1686 flags |= child.subtree_hit_flags & !SUBTREE_HAS_HEIGHT_DEP_DESCENDANT;
1687 if child.is_self_height_dependent()
1688 || (!matches!(child.style.height, strata_style::types::Dimension::Px(_))
1689 && (child.subtree_hit_flags & SUBTREE_HAS_HEIGHT_DEP_DESCENDANT) != 0)
1690 {
1691 flags |= SUBTREE_HAS_HEIGHT_DEP_DESCENDANT;
1692 }
1693 if matches!(child.style.display, strata_style::types::Display::None)
1694 || child.is_top_layer
1695 || child.style.position != strata_style::types::Position::Static
1696 || child.establishes_stacking_context_in(self_display, false)
1697 {
1698 continue;
1699 }
1700 let cb = child.subtree_bounds;
1701 if cb.width > 0.0
1702 || cb.height > 0.0
1703 || (child.children.is_empty() && (cb.x != 0.0 || cb.y != 0.0))
1704 {
1705 union_rect(
1706 cb,
1707 &mut min_x,
1708 &mut min_y,
1709 &mut max_x,
1710 &mut max_y,
1711 &mut has_bounds,
1712 );
1713 }
1714 }
1715
1716 if has_bounds {
1717 if node.style.overflow_x != strata_style::types::Overflow::Visible {
1718 let clip_x0 = own.x;
1719 let clip_x1 = own.x + own.width.max(0.0);
1720 min_x = min_x.max(clip_x0).min(clip_x1);
1721 max_x = max_x.min(clip_x1).max(min_x);
1722 }
1723 if node.style.overflow_y != strata_style::types::Overflow::Visible {
1724 let clip_y0 = own.y;
1725 let clip_y1 = own.y + own.height.max(0.0);
1726 min_y = min_y.max(clip_y0).min(clip_y1);
1727 max_y = max_y.min(clip_y1).max(min_y);
1728 }
1729 node.subtree_bounds = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y);
1730 } else {
1731 node.subtree_bounds = own;
1732 }
1733 node.subtree_hit_flags = flags;
1734 }
1735
1736 #[inline]
1737 pub(crate) fn is_height_independent_for_cache(&self) -> bool {
1738 self.style.height == strata_style::types::Dimension::Auto
1739 && self.style.flex_basis == strata_style::types::Dimension::Auto
1740 && self.style.flex_grow == 0.0
1741 && !matches!(
1742 self.style.min_height,
1743 strata_style::types::Dimension::Percent(_)
1744 )
1745 && !matches!(
1746 self.style.max_height,
1747 strata_style::types::Dimension::Percent(_)
1748 )
1749 && !(matches!(
1750 self.style.position,
1751 strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
1752 ) && (!matches!(
1753 self.style.insets.bottom,
1754 strata_style::types::Dimension::Auto
1755 ) || matches!(
1756 self.style.insets.top,
1757 strata_style::types::Dimension::Percent(_)
1758 )))
1759 && !self.has_height_dependent_descendant_fast()
1760 }
1761
1762 #[inline]
1765 pub(crate) fn lookup_measure_cache(
1766 &self,
1767 available_w: f32,
1768 available_h: f32,
1769 style_pin_hash: u64,
1770 ) -> Option<(f32, f32, f32)> {
1771 if !self.children_layout_clean {
1772 return None;
1773 }
1774 for slot in &self.measure_cache {
1775 if slot.is_valid
1776 && slot.style_pin_hash == style_pin_hash
1777 && (available_w - slot.available_w).abs() < 0.01
1778 && ((available_h - slot.available_h).abs() < 0.01
1779 || self.is_height_independent_for_cache())
1780 {
1781 return Some((slot.result_w, slot.result_h, slot.baseline_offset));
1782 }
1783 }
1784 None
1785 }
1786
1787 #[inline]
1789 #[allow(clippy::too_many_arguments)]
1790 pub(crate) fn store_measure_cache(
1791 &mut self,
1792 slot_idx: usize,
1793 available_w: f32,
1794 available_h: f32,
1795 style_pin_hash: u64,
1796 result_w: f32,
1797 result_h: f32,
1798 baseline_offset: f32,
1799 ) {
1800 self.measure_cache[slot_idx.min(1)] = MeasureCacheEntry {
1801 available_w,
1802 available_h,
1803 style_pin_hash,
1804 result_w,
1805 result_h,
1806 baseline_offset,
1807 is_valid: true,
1808 };
1809 }
1810
1811 #[cold]
1812 #[inline(never)]
1813 fn layout_overflow_fallback(
1814 &mut self,
1815 available_width: f32,
1816 available_height: f32,
1817 guard: LayoutDepthGuard,
1818 ) {
1819 record_layout_overflow(guard.current_depth(), guard.max_depth());
1820 let padding = self.style.padding;
1821 let border = self.style.border_width;
1822 let margin = self.style.margin;
1823
1824 let w = crate::box_model::resolve_dimension_with_node(
1825 self.style.width,
1826 available_width,
1827 self,
1828 )
1829 .unwrap_or(available_width)
1830 .max(0.0);
1831 let h = crate::box_model::resolve_dimension(self.style.height, available_height)
1832 .unwrap_or_else(|| {
1833 if self.text.is_some() {
1834 self.style.font_size * self.style.line_height
1835 } else {
1836 0.0
1837 }
1838 })
1839 .max(0.0);
1840
1841 self.geometry = LayoutGeometry::from_border_box(
1842 crate::geometry::Rect::new(
1843 self.geometry.border_box.x,
1844 self.geometry.border_box.y,
1845 w,
1846 h,
1847 ),
1848 padding,
1849 border,
1850 margin,
1851 );
1852 self.geometry.snap_to_pixel();
1853 self.layout_cache.is_valid = false;
1854 self.children_layout_clean = false;
1855 self.subtree_hit_flags &= !SUBTREE_META_VALID;
1856 }
1857
1858 #[inline(never)]
1859 fn translate_cached_subtree_hit(&mut self) {
1860 let dx = self.geometry.border_box.x - self.layout_cache.origin_x;
1861 let dy = self.geometry.border_box.y - self.layout_cache.origin_y;
1862 if dx.abs() > 0.001 || dy.abs() > 0.001 {
1863 self.geometry.padding_box.x += dx;
1864 self.geometry.padding_box.y += dy;
1865 self.geometry.content_box.x += dx;
1866 self.geometry.content_box.y += dy;
1867 self.geometry.margin_box.x += dx;
1868 self.geometry.margin_box.y += dy;
1869 self.subtree_bounds.x += dx;
1870 self.subtree_bounds.y += dy;
1871 if let Some(ref mut pb) = self.last_preserved_box {
1872 pb.0 += dx;
1873 pb.1 += dy;
1874 }
1875 if let Some(ref mut grid) = self.table_grid {
1876 grid.translate(dx, dy);
1877 }
1878 for line in &mut self.line_boxes {
1879 line.bounds.x += dx;
1880 line.bounds.y += dy;
1881 for frag in &mut line.text_fragments {
1882 frag.bounds.x += dx;
1883 frag.bounds.y += dy;
1884 frag.baseline_y += dy;
1885 }
1886 for at in &mut line.atomic_fragments {
1887 at.bounds.x += dx;
1888 at.bounds.y += dy;
1889 }
1890 }
1891 for child in &mut self.children {
1892 child.translate(dx, dy);
1893 }
1894 self.layout_cache.origin_x = self.geometry.border_box.x;
1895 self.layout_cache.origin_y = self.geometry.border_box.y;
1896 }
1897 self.applied_relative_offset = (0.0, 0.0);
1898 }
1899
1900 pub fn compute_layout_guarded(
1902 &mut self,
1903 available_width: f32,
1904 available_height: f32,
1905 exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1906 bfc_offset_y: f32,
1907 guard: LayoutDepthGuard,
1908 ) {
1909 let _guard = crate::prof::LayoutGuard::new();
1910 crate::prof::observe_width(self.children.len());
1911
1912 let available_width = if available_width.is_finite() && available_width >= 0.0 {
1913 available_width.min(1e7)
1914 } else {
1915 0.0
1916 };
1917 let available_height = if available_height.is_finite() && available_height >= 0.0 {
1918 available_height.min(1e7)
1919 } else {
1920 0.0
1921 };
1922
1923 if self.style.display == Display::None {
1924 self.geometry = LayoutGeometry::default();
1925 self.applied_relative_offset = (0.0, 0.0);
1926 self.layout_cache.is_valid = false;
1927 self.children_layout_clean = false;
1928 self.subtree_hit_flags &= !SUBTREE_META_VALID;
1929 return;
1930 }
1931
1932 if guard.is_exhausted() {
1933 self.layout_overflow_fallback(available_width, available_height, guard);
1934 return;
1935 }
1936
1937 let is_unconstrained_root = exclusions
1938 .as_ref()
1939 .is_none_or(|e| e.exclusions().is_empty());
1940 let style_pin_hash = layout_style_pin_hash(&self.style);
1941
1942 if is_unconstrained_root
1946 && self.layout_cache.is_valid
1947 && self.layout_cache.style_pin_hash == style_pin_hash
1948 && (available_width - self.layout_cache.available_w).abs() < 0.01
1949 && ((available_height - self.layout_cache.available_h).abs() < 0.01
1950 || self.is_height_independent_for_cache())
1951 {
1952 self.translate_cached_subtree_hit();
1953 return;
1954 }
1955
1956 self.applied_relative_offset = (0.0, 0.0);
1957 self.subtree_hit_flags &= !SUBTREE_META_VALID;
1958
1959 match self.style.display {
1961 Display::Flex | Display::InlineFlex => {
1962 crate::flexbox::solve_flexbox_guarded(
1963 self,
1964 available_width,
1965 available_height,
1966 guard,
1967 );
1968 }
1969 Display::Grid | Display::InlineGrid => {
1970 crate::grid::solve_grid_guarded(self, available_width, available_height, guard);
1971 }
1972 Display::Table | Display::InlineTable => {
1973 crate::table::solve_table_guarded(self, available_width, available_height, guard);
1974 }
1975 Display::Block
1976 | Display::ListItem
1977 | Display::Inline
1978 | Display::InlineBlock
1979 | Display::TableRowGroup
1980 | Display::TableHeaderGroup
1981 | Display::TableFooterGroup
1982 | Display::TableRow
1983 | Display::TableCell
1984 | Display::TableCaption
1985 | Display::TableColumnGroup
1986 | Display::TableColumn => {
1987 crate::box_model::solve_block_with_exclusions_guarded(
1988 self,
1989 available_width,
1990 available_height,
1991 exclusions,
1992 bfc_offset_y,
1993 guard,
1994 );
1995 }
1996 Display::None => unreachable!(),
1997 }
1998
1999 let needs_positioning_pass = guard.current_depth() == 0
2002 || self.style.position != strata_style::types::Position::Static
2003 || self.style.establishes_fixed_containing_block()
2004 || self
2005 .children
2006 .iter()
2007 .any(|c| c.style.position != strata_style::types::Position::Static);
2008 if needs_positioning_pass {
2009 crate::positioning::solve_positioning_guarded(
2010 self,
2011 available_width,
2012 available_height,
2013 guard,
2014 );
2015 }
2016
2017 self.geometry.snap_to_pixel();
2019 self.geometry.sanitize();
2020
2021 self.update_scroll_metrics();
2023
2024 if !self.children.is_empty() || !self.inline_items.is_empty() || self.text.is_some() {
2025 self.last_child_layout_content = Some((
2026 self.geometry.content_box.width,
2027 self.geometry.content_box.height,
2028 ));
2029 }
2030 self.children_layout_clean = true;
2031 self.last_preserved_box = None;
2032
2033 if is_unconstrained_root {
2035 self.layout_cache = LayoutCacheEntry {
2036 available_w: available_width,
2037 available_h: available_height,
2038 result_w: self.geometry.border_box.width,
2039 result_h: self.geometry.border_box.height,
2040 origin_x: self.geometry.border_box.x,
2041 origin_y: self.geometry.border_box.y,
2042 style_pin_hash,
2043 is_valid: true,
2044 };
2045 }
2046 }
2047
2048 #[inline]
2049 fn has_height_dependent_descendant_fast(&self) -> bool {
2050 if (self.subtree_hit_flags & SUBTREE_META_VALID) != 0 {
2051 return (self.subtree_hit_flags & SUBTREE_HAS_HEIGHT_DEP_DESCENDANT) != 0;
2052 }
2053 self.has_height_dependent_descendant()
2054 }
2055
2056 fn has_height_dependent_descendant(&self) -> bool {
2058 use strata_style::types::{Dimension, Position};
2059 let mut stack: Vec<&LayoutNode> = self.children.iter().collect();
2060 while let Some(node) = stack.pop() {
2061 if matches!(node.style.height, Dimension::Percent(_))
2062 || matches!(node.style.min_height, Dimension::Percent(_))
2063 || matches!(node.style.max_height, Dimension::Percent(_))
2064 || matches!(node.style.flex_basis, Dimension::Percent(_))
2065 {
2066 return true;
2067 }
2068 if matches!(node.style.position, Position::Absolute | Position::Fixed)
2069 && (!matches!(node.style.insets.bottom, Dimension::Auto)
2070 || matches!(node.style.insets.top, Dimension::Percent(_)))
2071 {
2072 return true;
2073 }
2074 if !matches!(node.style.height, Dimension::Px(_)) {
2075 for grand in &node.children {
2076 stack.push(grand);
2077 }
2078 }
2079 }
2080 false
2081 }
2082
2083 #[inline]
2086 pub fn invalidate_self_caches(&mut self) {
2087 self.layout_cache.is_valid = false;
2088 self.measure_cache[0].is_valid = false;
2089 self.measure_cache[1].is_valid = false;
2090 self.intrinsic_cache.clear();
2091 self.last_child_layout_content = None;
2092 self.children_layout_clean = false;
2093 self.last_preserved_box = None;
2094 self.subtree_hit_flags &= !SUBTREE_META_VALID;
2095 }
2096
2097 pub fn invalidate_cache(&mut self) {
2099 let mut stack: Vec<&mut LayoutNode> = vec![self];
2100 while let Some(node) = stack.pop() {
2101 node.invalidate_self_caches();
2102 for child in &mut node.children {
2103 stack.push(child);
2104 }
2105 }
2106 }
2107
2108 pub fn is_layout_boundary(&self) -> bool {
2117 if self.style.contain == strata_style::types::Containment::STRICT
2119 || self.style.contain == strata_style::types::Containment::CONTENT
2120 {
2121 return true;
2122 }
2123
2124 if self.style.contain.layout && self.style.contain.size {
2126 return true;
2127 }
2128
2129 if self.style.contain.layout && self.has_definite_dimensions() {
2131 return true;
2132 }
2133
2134 if self.style.content_visibility != strata_style::types::ContentVisibility::Visible
2136 && self.has_definite_dimensions()
2137 {
2138 return true;
2139 }
2140
2141 if matches!(
2143 self.style.position,
2144 strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
2145 ) && self.has_definite_dimensions()
2146 && self.style.overflow_x != strata_style::types::Overflow::Visible
2147 && self.style.overflow_y != strata_style::types::Overflow::Visible
2148 {
2149 return true;
2150 }
2151
2152 false
2153 }
2154
2155 #[inline]
2157 pub fn has_definite_dimensions(&self) -> bool {
2158 matches!(self.style.width, strata_style::types::Dimension::Px(_))
2159 && matches!(self.style.height, strata_style::types::Dimension::Px(_))
2160 }
2161
2162 pub fn find_layout_boundary_path<'a>(&self, path: &'a [usize]) -> Option<&'a [usize]> {
2165 let mut best_boundary_len = if self.is_layout_boundary() {
2166 Some(0)
2167 } else {
2168 None
2169 };
2170
2171 let mut curr = self;
2172 for (i, &child_idx) in path.iter().enumerate() {
2173 if child_idx >= curr.children.len() {
2174 break;
2175 }
2176 curr = &curr.children[child_idx];
2177 if curr.is_layout_boundary() {
2178 best_boundary_len = Some(i + 1);
2179 }
2180 }
2181
2182 best_boundary_len.map(|len| &path[..len])
2183 }
2184
2185 pub fn compute_subgrid_or_boundary_layout(&mut self, path: &[usize]) -> bool {
2192 let boundary_len = match self.find_layout_boundary_path(path) {
2193 Some(subpath) => subpath.len(),
2194 None => return false,
2195 };
2196
2197 if boundary_len == 0 {
2198 self.layout_children();
2200 return true;
2201 }
2202
2203 let mut curr = self;
2205 for &idx in &path[..boundary_len] {
2206 if idx >= curr.children.len() {
2207 return false;
2208 }
2209 curr = &mut curr.children[idx];
2210 }
2211
2212 curr.layout_children();
2214 true
2215 }
2216
2217 pub fn invalidate_layout_boundary(&mut self, path: &[usize]) -> bool {
2219 let boundary_len = match self.find_layout_boundary_path(path) {
2220 Some(subpath) => subpath.len(),
2221 None => {
2222 self.invalidate_cache();
2223 return false;
2224 }
2225 };
2226
2227 let mut curr = self;
2228 for &idx in &path[..boundary_len] {
2229 if idx >= curr.children.len() {
2230 return false;
2231 }
2232 curr = &mut curr.children[idx];
2233 }
2234
2235 curr.invalidate_cache();
2236 true
2237 }
2238
2239 pub fn find_path_by_entity_id(
2241 &self,
2242 target_id: strata_primitives::EntityId,
2243 ) -> Option<Vec<usize>> {
2244 if !target_id.is_valid() {
2245 return None;
2246 }
2247 if self.entity_id == target_id {
2248 return Some(Vec::new());
2249 }
2250 let mut path = Vec::new();
2251 let mut stack: Vec<(&LayoutNode, usize)> = vec![(self, 0)];
2252 while let Some((node, next_idx)) = stack.last_mut() {
2253 let idx = *next_idx;
2254 if idx < node.children.len() {
2255 *next_idx += 1;
2256 let child = &node.children[idx];
2257 path.push(idx);
2258 if child.entity_id == target_id {
2259 return Some(path);
2260 }
2261 if !child.children.is_empty() {
2262 stack.push((child, 0));
2263 } else {
2264 path.pop();
2265 }
2266 } else {
2267 stack.pop();
2268 if !stack.is_empty() {
2269 path.pop();
2270 }
2271 }
2272 }
2273 None
2274 }
2275
2276 pub fn invalidate_ancestors(&mut self, path: &[usize]) {
2278 self.invalidate_self_caches();
2279 let mut curr = self;
2280 for &idx in path {
2281 if idx >= curr.children.len() {
2282 break;
2283 }
2284 curr = &mut curr.children[idx];
2285 curr.invalidate_self_caches();
2286 }
2287 }
2288
2289 pub fn update_scroll_metrics(&mut self) {
2291 let origin_x = self.geometry.padding_box.x;
2292 let origin_y = self.geometry.padding_box.y;
2293 let mut max_extent_x = self.geometry.content_box.width;
2294 let mut max_extent_y = self.geometry.content_box.height;
2295
2296 for child in &self.children {
2297 if child.style.display == strata_style::types::Display::None
2298 || child.style.position == strata_style::types::Position::Fixed
2299 {
2300 continue;
2301 }
2302 let child_end_x = child.geometry.border_box.max_x() - origin_x;
2303 let child_end_y = child.geometry.border_box.max_y() - origin_y;
2304 if child_end_x.is_finite() && child_end_x > max_extent_x {
2305 max_extent_x = child_end_x;
2306 }
2307 if child_end_y.is_finite() && child_end_y > max_extent_y {
2308 max_extent_y = child_end_y;
2309 }
2310 }
2311
2312 for line in &self.line_boxes {
2313 let line_end_x = line.bounds.max_x() - origin_x;
2314 let line_end_y = line.bounds.max_y() - origin_y;
2315 if line_end_x.is_finite() && line_end_x > max_extent_x {
2316 max_extent_x = line_end_x;
2317 }
2318 if line_end_y.is_finite() && line_end_y > max_extent_y {
2319 max_extent_y = line_end_y;
2320 }
2321 }
2322
2323 self.geometry.scroll_bounds = crate::geometry::Size::new(max_extent_x, max_extent_y);
2324
2325 let has_scroll_x = match self.style.overflow_x {
2326 strata_style::types::Overflow::Scroll => true,
2327 strata_style::types::Overflow::Auto => max_extent_x > self.geometry.padding_box.width,
2328 _ => false,
2329 };
2330 let has_scroll_y = match self.style.overflow_y {
2331 strata_style::types::Overflow::Scroll => true,
2332 strata_style::types::Overflow::Auto => max_extent_y > self.geometry.padding_box.height,
2333 _ => false,
2334 };
2335 self.geometry.has_scroll = (has_scroll_x, has_scroll_y);
2336 self.geometry.scroll_offset = self
2337 .geometry
2338 .clamp_scroll_offset(self.geometry.scroll_offset);
2339 }
2340}
2341
2342#[inline(never)]
2343fn drop_layout_children_iterative(mut stack: Vec<LayoutNode>) {
2344 while let Some(mut node) = stack.pop() {
2345 if !node.children.is_empty() {
2346 let grandchildren = std::mem::take(&mut node.children);
2347 stack.extend(grandchildren);
2348 }
2349 }
2350}
2351
2352impl Drop for LayoutNode {
2353 fn drop(&mut self) {
2354 if self.children.is_empty() {
2355 return;
2356 }
2357 let stack = std::mem::take(&mut self.children);
2360 drop_layout_children_iterative(stack);
2361 }
2362}