1use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6
7pub const EV_CLICK: u32 = 1;
9pub const EV_MOUSEDOWN: u32 = 2;
10pub const EV_MOUSEUP: u32 = 3;
11pub const EV_WHEEL: u32 = 4;
12pub const EV_KEYDOWN: u32 = 5;
13pub const EV_KEYUP: u32 = 6;
14pub const EV_FOCUS: u32 = 7;
15pub const EV_BLUR: u32 = 8;
16pub const EV_INPUT: u32 = 9;
17pub const EV_SCROLL: u32 = 10;
18pub const EV_COMPLETE: u32 = 11;
20pub const EV_LOOPCOMPLETE: u32 = 12;
21pub const EV_ENTERFRAME: u32 = 13;
22pub const EV_MOUSEMOVE: u32 = 14;
23pub const EV_MOUSEENTER: u32 = 15;
25pub const EV_MOUSELEAVE: u32 = 16;
26pub const EV_LOADSTART: u32 = 17;
27pub const EV_LOADEDMETADATA: u32 = 18;
28pub const EV_LOADEDDATA: u32 = 19;
29pub const EV_CANPLAY: u32 = 20;
30pub const EV_CANPLAYTHROUGH: u32 = 21;
31pub const EV_PLAY: u32 = 22;
32pub const EV_PLAYING: u32 = 23;
33pub const EV_PAUSE: u32 = 24;
34pub const EV_SEEKING: u32 = 25;
35pub const EV_SEEKED: u32 = 26;
36pub const EV_TIMEUPDATE: u32 = 27;
38pub const EV_DURATIONCHANGE: u32 = 28;
39pub const EV_RATECHANGE: u32 = 29;
40pub const EV_VOLUMECHANGE: u32 = 30;
41pub const EV_WAITING: u32 = 31;
42pub const EV_ENDED: u32 = 32;
43pub const EV_ERROR: u32 = 33;
45pub const EV_EMPTIED: u32 = 34;
46
47pub const EV_TRANSITIONEND: u32 = 35;
48pub const EV_ANIMATIONSTART: u32 = 36;
49pub const EV_ANIMATIONEND: u32 = 37;
50pub const EV_ANIMATIONCANCEL: u32 = 38;
51
52pub const EV_PASTE: u32 = 39;
53pub const EV_COPY: u32 = 40;
54pub const EV_CUT: u32 = 41;
55
56pub const EV_CONTEXTMENU: u32 = 42;
59pub const EV_LOAD: u32 = 43;
62pub const EV_POINTERCANCEL: u32 = 44;
64pub const EV_SELECTSTART: u32 = 45;
67pub const EV_SELECTIONCHANGE: u32 = 46;
68pub const EV_AUXCLICK: u32 = 47;
71pub const EV_BEFOREINPUT: u32 = 48;
73pub const EV_COMPOSITIONSTART: u32 = 49;
76pub const EV_COMPOSITIONUPDATE: u32 = 50;
77pub const EV_COMPOSITIONEND: u32 = 51;
78pub const EV_MESSAGE: u32 = 52;
81pub const EV_POINTERLOCKCHANGE: u32 = 53;
84pub const EV_POINTERLOCKERROR: u32 = 54;
85pub const EV_SURFACERESIZE: u32 = 55;
90pub const EV_SURFACEREADY: u32 = 56;
91pub const EV_SURFACELOST: u32 = 57;
92pub const EV_SURFACEDISPLAYCHANGE: u32 = 58;
93pub const EV_MOUSEOVER: u32 = 59;
96pub const EV_MOUSEOUT: u32 = 60;
97
98pub const EVENT_NAMES: &[(u32, &str)] = &[
100 (EV_CLICK, "click"),
101 (EV_MOUSEDOWN, "mousedown"),
102 (EV_MOUSEUP, "mouseup"),
103 (EV_WHEEL, "wheel"),
104 (EV_KEYDOWN, "keydown"),
105 (EV_KEYUP, "keyup"),
106 (EV_FOCUS, "focus"),
107 (EV_BLUR, "blur"),
108 (EV_INPUT, "input"),
109 (EV_SCROLL, "scroll"),
110 (EV_COMPLETE, "complete"),
111 (EV_LOOPCOMPLETE, "loopComplete"),
112 (EV_ENTERFRAME, "enterFrame"),
113 (EV_MOUSEMOVE, "mousemove"),
114 (EV_MOUSEENTER, "mouseenter"),
115 (EV_MOUSELEAVE, "mouseleave"),
116 (EV_LOADSTART, "loadstart"),
117 (EV_LOADEDMETADATA, "loadedmetadata"),
118 (EV_LOADEDDATA, "loadeddata"),
119 (EV_CANPLAY, "canplay"),
120 (EV_CANPLAYTHROUGH, "canplaythrough"),
121 (EV_PLAY, "play"),
122 (EV_PLAYING, "playing"),
123 (EV_PAUSE, "pause"),
124 (EV_SEEKING, "seeking"),
125 (EV_SEEKED, "seeked"),
126 (EV_TIMEUPDATE, "timeupdate"),
127 (EV_DURATIONCHANGE, "durationchange"),
128 (EV_RATECHANGE, "ratechange"),
129 (EV_VOLUMECHANGE, "volumechange"),
130 (EV_WAITING, "waiting"),
131 (EV_ENDED, "ended"),
132 (EV_ERROR, "error"),
133 (EV_EMPTIED, "emptied"),
134 (EV_TRANSITIONEND, "transitionend"),
135 (EV_ANIMATIONSTART, "animationstart"),
136 (EV_ANIMATIONEND, "animationend"),
137 (EV_ANIMATIONCANCEL, "animationcancel"),
138 (EV_PASTE, "paste"),
139 (EV_COPY, "copy"),
140 (EV_CUT, "cut"),
141 (EV_CONTEXTMENU, "contextmenu"),
142 (EV_LOAD, "load"),
143 (EV_POINTERCANCEL, "pointercancel"),
144 (EV_SELECTSTART, "selectstart"),
145 (EV_SELECTIONCHANGE, "selectionchange"),
146 (EV_AUXCLICK, "auxclick"),
147 (EV_BEFOREINPUT, "beforeinput"),
148 (EV_COMPOSITIONSTART, "compositionstart"),
149 (EV_COMPOSITIONUPDATE, "compositionupdate"),
150 (EV_COMPOSITIONEND, "compositionend"),
151 (EV_MESSAGE, "message"),
152 (EV_POINTERLOCKCHANGE, "pointerlockchange"),
153 (EV_POINTERLOCKERROR, "pointerlockerror"),
154 (EV_SURFACERESIZE, "surfaceresize"),
155 (EV_SURFACEREADY, "surfaceready"),
156 (EV_SURFACELOST, "surfacelost"),
157 (EV_SURFACEDISPLAYCHANGE, "surfacedisplaychange"),
158 (EV_MOUSEOVER, "mouseover"),
159 (EV_MOUSEOUT, "mouseout"),
160];
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum Kind {
164 Element,
165 Text,
166 Anchor,
167}
168
169pub struct Node {
170 pub kind: Kind,
171 pub tag: u32,
172 pub parent: u32,
173 pub children: Vec<u32>,
174 pub text: String,
176 pub style: Vec<(u32, String)>,
178 pub classes: Vec<String>,
179 pub class_attr: String,
181 pub props: Vec<(u32, String, u32)>,
185 pub scopes: Vec<String>,
187 pub listeners: u64,
188 pub(crate) inline_dirty: bool,
189 pub style_present: bool,
191 pub style_raw: Option<String>,
193 pub(crate) sub_rev: u64,
196 pub(crate) mark_gen: u32,
199 pub(crate) desc_gen: u32,
200 pub(crate) sel_flags: Cell<u8>,
202 pub(crate) inline: Option<std::rc::Rc<sk_css::InlineStyle>>,
203 pub computed: Option<sk_css::ComputedStates>,
204}
205
206pub(crate) mod sel {
212 pub const PREV_EDGE: u8 = 1;
213 pub const PREV_WALK: u8 = 2;
214 pub const NEXT_EDGE: u8 = 4;
215 pub const NEXT_WALK: u8 = 8;
216 pub const SIBLINGS: u8 = PREV_EDGE | PREV_WALK | NEXT_EDGE | NEXT_WALK;
217 pub const EMPTY: u8 = 16;
218 pub const HAS_SELF: u8 = 32;
219 pub const HAS_DESC: u8 = 64;
220 pub const HAS: u8 = HAS_SELF | HAS_DESC;
221 pub const HAS_NEXT: u8 = 128;
222}
223
224thread_local! {
225 static CASCADE_SUBJECT: Cell<u32> = const { Cell::new(0) };
226 static HAS_DEPTH: Cell<u32> = const { Cell::new(0) };
229 static READ_ON_OTHERS: RefCell<ReadOnOthers> = RefCell::new(ReadOnOthers::default());
230 static READ_CACHE: [Cell<(usize, usize, u32)>; 128] = [const { Cell::new((0, 0, 0)) }; 128];
233}
234
235#[derive(Default)]
241struct ReadOnOthers {
242 names: [HashMap<Box<str>, Readers>; 4],
243}
244
245#[derive(Default)]
246struct Readers {
247 tags: Vec<u32>,
248 all: bool,
249}
250
251const MAX_READER_TAGS: usize = 8;
253
254#[derive(Clone, Copy)]
255enum NameKind {
256 Class = 0,
257 Attr = 1,
258 Scope = 2,
259 Position = 3,
262}
263
264const POSITION: &str = "position";
265
266#[derive(Debug, PartialEq)]
267enum Reach {
268 Own,
269 Tags(Vec<u32>),
271 Subtree,
272}
273
274fn note_name_read(asked: u32, subject: u32, subject_tag: u32, name: &str, kind: NameKind) {
275 if subject == 0 || subject == asked {
276 return;
277 }
278 let key = (
279 name.as_ptr() as usize,
280 name.len() * 4 + kind as usize,
281 subject_tag,
282 );
283 let slot = ((key.0 >> 3) ^ key.2 as usize) & 127;
284 if READ_CACHE.with(|c| c[slot].get()) == key {
285 return;
286 }
287 READ_ON_OTHERS.with(|r| {
288 let mut r = r.borrow_mut();
289 let map = &mut r.names[kind as usize];
290 let readers = match map.get_mut(name) {
291 Some(readers) => readers,
292 None => map.entry(name.into()).or_default(),
293 };
294 if !readers.all && !readers.tags.contains(&subject_tag) {
295 readers.tags.push(subject_tag);
296 if readers.tags.len() > MAX_READER_TAGS {
297 readers.all = true;
298 readers.tags = Vec::new();
299 }
300 }
301 });
302 READ_CACHE.with(|c| c[slot].set(key));
303}
304
305fn reach_of<'a>(names: impl IntoIterator<Item = (&'a str, NameKind)>) -> Reach {
306 READ_ON_OTHERS.with(|r| {
307 let r = r.borrow();
308 let mut tags: Vec<u32> = Vec::new();
309 for (name, kind) in names {
310 let Some(readers) = r.names[kind as usize].get(name) else {
311 continue;
312 };
313 if readers.all {
314 return Reach::Subtree;
315 }
316 for &t in &readers.tags {
317 if !tags.contains(&t) {
318 tags.push(t);
319 }
320 }
321 }
322 match tags.len() {
323 0 => Reach::Own,
324 n if n > MAX_READER_TAGS => Reach::Subtree,
325 _ => Reach::Tags(tags),
326 }
327 })
328}
329
330#[derive(Default, Debug, Clone)]
331pub struct TreeMem {
332 pub slots: usize,
333 pub nodes: usize,
334 pub elements: usize,
335 pub texts: usize,
336 pub anchors: usize,
337 pub computed: usize,
338 pub slot_bytes: usize,
339 pub owned_bytes: usize,
340 pub computed_bytes: usize,
341 pub refinements: usize,
342 pub refinement_bytes: usize,
343 pub vars_maps: usize,
344 pub var_entries: usize,
345 pub vars_bytes: usize,
346 pub inlines: usize,
347 pub inline_bytes: usize,
348 pub names: usize,
349 pub total_bytes: usize,
350}
351
352#[derive(Default)]
353pub struct Tree {
354 nodes: Vec<Option<Node>>,
355 free: Vec<u32>,
356 freed: Vec<u32>,
357 pub root: u32,
358 dirty: bool,
359 restyle_gen: u32,
360 detached_marks: Vec<u32>,
363 has_anchors: Cell<bool>,
364 self_marks: Vec<u32>,
365 sibling_combinators: bool,
366 prop_writes: u32,
369 dirty_all: bool,
370 inline_dirty_nodes: Vec<u32>,
371 style_flushed: bool,
372 inline_container_units: bool,
375 style_nodes: std::collections::BTreeSet<u32>,
378 group_anchors: std::collections::HashSet<u32>,
382 group_hover_deps: HashMap<u32, Vec<u32>>,
385 group_focus_deps: HashMap<u32, Vec<u32>>,
387 names: Vec<String>,
388 name_ids: HashMap<String, u32>,
389}
390
391thread_local! {
392 static TREE: RefCell<Tree> = RefCell::new(Tree::new());
393 static DISPATCHER: Cell<u64> = const { Cell::new(0) };
394}
395
396pub fn with_tree<R>(f: impl FnOnce(&mut Tree) -> R) -> R {
399 TREE.with(|t| f(&mut t.borrow_mut()))
400}
401
402pub fn read_tree<R>(f: impl FnOnce(&Tree) -> R) -> R {
403 TREE.with(|t| f(&t.borrow()))
404}
405
406fn warn_css(msg: &str) {
408 let msg = crate::log::one_line(msg);
410 let fresh = CSS_WARNED.with(|w| w.borrow_mut().insert(msg.clone()));
411 if fresh {
412 eprintln!("{msg}");
413 crate::log::record("css", msg);
414 }
415}
416
417pub(crate) fn set_dispatcher(f: u64) {
418 DISPATCHER.with(|d| d.set(f));
419}
420
421pub(crate) fn dispatcher() -> u64 {
422 DISPATCHER.with(|d| d.get())
423}
424
425impl Tree {
426 fn new() -> Self {
427 Tree {
428 nodes: vec![None],
429 names: vec![String::new()],
432 name_ids: HashMap::from([(String::new(), 0)]),
433 restyle_gen: 1,
434 ..Default::default()
435 }
436 }
437
438 pub fn intern(&mut self, name: &str) -> u32 {
439 if let Some(&id) = self.name_ids.get(name) {
440 return id;
441 }
442 let id = self.names.len() as u32;
443 self.names.push(name.to_string());
444 self.name_ids.insert(name.to_string(), id);
445 id
446 }
447
448 pub fn name(&self, id: u32) -> &str {
449 self.names
450 .get(id as usize)
451 .map(String::as_str)
452 .unwrap_or("")
453 }
454
455 pub fn is_group_anchor(&self, id: u32) -> bool {
456 self.group_anchors.contains(&id)
457 }
458
459 pub(crate) fn touch_hover_styled(&mut self, id: u32) -> bool {
462 let own = self
463 .node(id)
464 .and_then(|n| n.computed.as_ref())
465 .is_some_and(|cs| cs.hover.is_some() || cs.control_state(1));
466 if own {
467 self.touch(id);
468 }
469 let deps = self.group_hover_deps.get(&id).cloned().unwrap_or_default();
470 for &dep in &deps {
471 self.touch(dep);
472 }
473 own || !deps.is_empty()
474 }
475
476 pub(crate) fn touch_focus_watchers(&mut self, old: u32, new: u32) {
479 if self.group_focus_deps.is_empty() {
480 return;
481 }
482 let mut deps = Vec::new();
483 for start in [old, new] {
484 let mut at = start;
485 for _ in 0..4096 {
486 let Some(n) = self.node(at) else { break };
487 if let Some(watchers) = self.group_focus_deps.get(&at) {
488 deps.extend_from_slice(watchers);
489 }
490 if n.parent == 0 || n.parent == at {
491 break;
492 }
493 at = n.parent;
494 }
495 }
496 for dep in deps {
497 self.touch(dep);
498 }
499 }
500
501 fn alloc(&mut self, node: Node) -> u32 {
502 if let Some(id) = self.free.pop() {
503 self.nodes[id as usize] = Some(node);
504 id
505 } else {
506 self.nodes.push(Some(node));
507 (self.nodes.len() - 1) as u32
508 }
509 }
510
511 pub fn node(&self, id: u32) -> Option<&Node> {
512 self.nodes.get(id as usize).and_then(Option::as_ref)
513 }
514
515 pub(crate) fn connected(&self, id: u32) -> bool {
517 let mut cursor = id;
518 for _ in 0..4096 {
520 if cursor == 0 {
521 return false;
522 }
523 if cursor == self.root {
524 return true;
525 }
526 match self.node(cursor) {
527 Some(n) => cursor = n.parent,
528 None => return false,
529 }
530 }
531 false
532 }
533
534 pub(crate) fn node_mut(&mut self, id: u32) -> Option<&mut Node> {
535 self.nodes.get_mut(id as usize).and_then(Option::as_mut)
536 }
537
538 fn fresh(&mut self, kind: Kind, tag: u32) -> u32 {
539 self.dirty = true;
540 let id = self.alloc(Node {
541 kind,
542 tag,
543 parent: 0,
544 children: Vec::new(),
545 text: String::new(),
546 style: Vec::new(),
547 classes: Vec::new(),
548 class_attr: String::new(),
549 props: Vec::new(),
550 scopes: Vec::new(),
551 listeners: 0,
552 inline_dirty: false,
553 style_present: false,
554 style_raw: None,
555 sub_rev: 0,
556 mark_gen: 0,
557 desc_gen: 0,
558 sel_flags: Cell::new(0),
559 inline: None,
560 computed: None,
561 });
562 self.mark_restyle(id);
563 id
564 }
565
566 pub fn create_element(&mut self, tag: u32) -> u32 {
567 let id = self.fresh(Kind::Element, tag);
568 if self.name(tag).eq_ignore_ascii_case("style") {
569 self.style_nodes.insert(id);
570 }
571 id
572 }
573
574 pub fn create_text(&mut self) -> u32 {
575 self.fresh(Kind::Text, 0)
576 }
577
578 pub fn create_anchor(&mut self) -> u32 {
579 self.fresh(Kind::Anchor, 0)
580 }
581
582 pub fn create_root(&mut self) -> u32 {
583 let tag = self.intern("root");
584 let id = self.fresh(Kind::Element, tag);
585 self.root = id;
586 id
587 }
588
589 pub fn set_text(&mut self, id: u32, text: String) {
590 if let Some(n) = self.node_mut(id) {
591 let flips = n.kind == Kind::Text && n.text.is_empty() != text.is_empty();
594 let mut parent = n.parent;
595 n.text = text;
596 self.dirty = true;
597 self.mark_restyle(id);
598 if flips {
599 while let Some(p) = self.node(parent).filter(|p| p.kind == Kind::Anchor) {
600 parent = p.parent;
601 }
602 if self
603 .node(parent)
604 .is_some_and(|p| p.sel_flags.get() & sel::EMPTY != 0)
605 {
606 self.mark_with_followers(parent);
607 }
608 self.touch_mutated(id, false);
609 return;
610 }
611 self.touch(id);
612 }
613 }
614
615 pub fn set_element_text(&mut self, id: u32, text: String) {
616 let children = match self.node_mut(id) {
617 Some(n) => std::mem::take(&mut n.children),
618 None => return,
619 };
620 for c in children {
621 self.free_subtree(c);
622 }
623 if let Some(n) = self.node_mut(id) {
624 n.text = text;
625 }
626 self.dirty = true;
627 if self
628 .node(id)
629 .is_some_and(|n| n.sel_flags.get() & sel::EMPTY != 0)
630 {
631 self.mark_with_followers(id);
632 } else {
633 self.mark_restyle(id);
634 }
635 self.touch_mutated(id, true);
636 }
637
638 pub fn insert(&mut self, child: u32, parent: u32, anchor: u32) {
641 if child == 0 || parent == 0 || child == anchor || self.node(parent).is_none() {
642 return;
643 }
644 let old_parent = self.node(child).map(|n| n.parent).unwrap_or(0);
645 if old_parent != 0 {
646 let was_bare = self.bare_if_asked(old_parent);
647 let at = self.detach(child);
648 self.child_list_changed(old_parent, at, false, was_bare);
649 }
650 let was_bare = self.bare_if_asked(parent);
651 let idx = {
654 let Some(p) = self.node_mut(parent) else {
655 return;
656 };
657 p.text.clear();
658 match p.children.iter().position(|&c| c == anchor) {
659 Some(i) => i,
660 None => p.children.len(),
661 }
662 };
663 if let Some(p) = self.node_mut(parent) {
664 p.children.insert(idx, child);
665 }
666 if let Some(c) = self.node_mut(child) {
667 c.parent = parent;
668 }
669 self.mark_restyle(child);
670 if self
671 .node(child)
672 .is_some_and(|c| c.desc_gen == self.restyle_gen)
673 {
674 self.flag_path(parent);
675 }
676 self.child_list_changed(parent, idx, true, was_bare);
677 self.dirty = true;
678 if old_parent != 0 {
680 self.touch_mutated(old_parent, true);
681 }
682 self.touch_mutated(child, false);
683 }
684
685 fn detach(&mut self, id: u32) -> usize {
686 let parent = self.node(id).map(|n| n.parent).unwrap_or(0);
687 let mut at = 0;
688 if parent != 0 {
689 if let Some(p) = self.node_mut(parent) {
690 if let Some(i) = p.children.iter().position(|&c| c == id) {
691 p.children.remove(i);
692 at = i;
693 }
694 }
695 if let Some(n) = self.node_mut(id) {
696 n.parent = 0;
697 }
698 }
699 at
700 }
701
702 pub fn remove(&mut self, id: u32) {
705 let parent = self.node(id).map(|n| n.parent).unwrap_or(0);
706 let was_bare = self.bare_if_asked(parent);
707 let at = self.detach(id);
708 self.free_subtree(id);
709 if parent != 0 {
710 self.child_list_changed(parent, at, false, was_bare);
711 }
712 self.dirty = true;
713 if parent != 0 {
714 self.touch_mutated(parent, true);
715 }
716 }
717
718 fn child_list_changed(&mut self, parent: u32, at: usize, inserted: bool, was_bare: bool) {
721 let Some(p) = self.node(parent) else { return };
722 let flags = p.sel_flags.get();
723 if flags & sel::EMPTY != 0 && self.is_bare(parent) != was_bare {
724 self.mark_with_followers(parent);
725 }
726 if flags & sel::SIBLINGS == 0 {
727 return;
728 }
729 let marks: Vec<u32> = {
730 let children = &self.node(parent).map_or(&[][..], |p| &p.children[..]);
731 let is_element = |c: &u32| self.node(*c).is_some_and(|n| n.kind == Kind::Element);
732 let after = if inserted { at + 1 } else { at };
733 let mut marks = Vec::new();
734 if flags & sel::PREV_WALK != 0 {
735 marks.extend(children.iter().skip(after).copied());
736 } else if flags & sel::PREV_EDGE != 0 {
737 marks.extend(children.iter().skip(after).find(|c| is_element(c)).copied());
738 }
739 if flags & sel::NEXT_WALK != 0 {
740 marks.extend(children.iter().take(at).copied());
741 } else if flags & sel::NEXT_EDGE != 0 {
742 marks.extend(
743 children
744 .iter()
745 .take(at)
746 .rev()
747 .find(|c| is_element(c))
748 .copied(),
749 );
750 }
751 marks
752 };
753 if marks.is_empty() {
754 return;
755 }
756 let reach = reach_of([(POSITION, NameKind::Position)]);
757 for c in marks {
758 self.mark_reach(c, &reach, false);
759 }
760 }
761
762 fn bare_if_asked(&self, id: u32) -> bool {
765 self.node(id)
766 .is_some_and(|n| n.sel_flags.get() & sel::EMPTY != 0)
767 && self.is_bare(id)
768 }
769
770 fn is_bare(&self, id: u32) -> bool {
771 let Some(n) = self.node(id) else { return true };
772 n.text.is_empty()
773 && n.children.iter().all(|&c| match self.node(c) {
774 Some(child) => match child.kind {
775 Kind::Element => false,
776 Kind::Text => child.text.is_empty(),
777 Kind::Anchor => self.is_bare(c),
778 },
779 None => true,
780 })
781 }
782
783 fn free_subtree(&mut self, id: u32) {
784 let Some(node) = self.nodes.get_mut(id as usize).and_then(Option::take) else {
785 return;
786 };
787 self.style_nodes.remove(&id);
788 for c in node.children {
789 self.free_subtree(c);
790 }
791 if self.root == id {
792 self.root = 0;
793 }
794 self.freed.push(id);
795 }
796
797 pub(crate) fn hidden_above(&self, id: u32) -> bool {
798 let mut cur = self.node(id).map_or(0, |n| n.parent);
799 while cur != 0 {
800 let Some(n) = self.node(cur) else {
801 return false;
802 };
803 if n.computed
804 .as_ref()
805 .is_some_and(|c| c.base.display == Some(gpui::Display::None))
806 {
807 return true;
808 }
809 cur = n.parent;
810 }
811 false
812 }
813
814 pub(crate) fn release_freed(&mut self) {
817 self.free.append(&mut self.freed);
818 }
819
820 pub fn set_style(&mut self, id: u32, key: u32, value: String) {
821 if let Some(n) = self.node_mut(id) {
822 if value.is_empty() {
823 n.style.retain(|(k, _)| *k != key);
824 } else if let Some(slot) = n.style.iter_mut().find(|(k, _)| *k == key) {
825 slot.1 = value;
826 } else {
827 n.style.push((key, value));
828 }
829 n.inline_dirty = true;
830 self.dirty = true;
831 self.inline_dirty_nodes.push(id);
832 self.mark_self(id);
833 self.touch(id);
834 }
835 }
836
837 pub fn set_prop(&mut self, id: u32, key: u32, value: Option<String>) {
838 let reach = reach_of([(self.name(key), NameKind::Attr)]);
839 self.prop_writes = self.prop_writes.wrapping_add(1);
840 let write = self.prop_writes;
841 if let Some(n) = self.node_mut(id) {
842 match value {
843 None => n.props.retain(|(k, _, _)| *k != key),
844 Some(v) => {
845 if let Some(slot) = n.props.iter_mut().find(|(k, _, _)| *k == key) {
846 slot.1 = v;
847 slot.2 = write;
848 } else {
849 n.props.push((key, v, write));
850 }
851 }
852 }
853 self.dirty = true;
854 self.mark_own_inputs(id, reach);
855 self.touch_mutated(id, false);
856 }
857 }
858
859 pub fn prop<'a>(&'a self, id: u32, name: &str) -> Option<&'a str> {
860 self.prop_write(id, name).map(|(v, _)| v)
861 }
862
863 pub fn prop_write<'a>(&'a self, id: u32, name: &str) -> Option<(&'a str, u32)> {
866 let key = *self.name_ids.get(name)?;
867 self.node(id)?
868 .props
869 .iter()
870 .find(|(k, _, _)| *k == key)
871 .map(|(_, v, write)| (v.as_str(), *write))
872 }
873
874 pub fn add_scope(&mut self, id: u32, scope: String) {
875 let reach = reach_of([(scope.as_str(), NameKind::Scope)]);
876 if let Some(n) = self.node_mut(id) {
877 if !n.scopes.contains(&scope) {
878 n.scopes.push(scope);
879 self.dirty = true;
880 self.mark_own_inputs(id, reach);
881 self.touch_mutated(id, false);
882 }
883 }
884 }
885
886 pub fn copy_scopes(&mut self, from: u32, to: u32) {
888 let scopes = self
889 .node(from)
890 .map(|n| n.scopes.clone())
891 .unwrap_or_default();
892 for scope in scopes {
893 self.add_scope(to, scope);
894 }
895 }
896
897 pub fn set_class(&mut self, id: u32, classes: &str) {
898 if let Some(n) = self.node_mut(id) {
899 if n.class_attr == classes {
900 return; }
902 let mut next: Vec<String> = Vec::new();
905 for c in classes.split_whitespace() {
906 if !next.iter().any(|x| x == c) {
907 next.push(c.to_string());
908 }
909 }
910 let reach = {
911 let gone = n.classes.iter().filter(|c| !next.contains(c));
912 let came = next.iter().filter(|c| !n.classes.contains(c));
913 let names = gone.chain(came).map(|c| (c.as_str(), NameKind::Class));
914 reach_of(std::iter::once(("class", NameKind::Attr)).chain(names))
915 };
916 n.classes = next;
917 n.class_attr = classes.to_string();
918 self.dirty = true;
919 self.mark_own_inputs(id, reach);
920 self.touch_mutated(id, false);
921 }
922 }
923
924 fn mark_own_inputs(&mut self, id: u32, reach: Reach) {
927 self.mark_reach(id, &reach, self.sibling_combinators);
928 }
929
930 fn mark_reach(&mut self, id: u32, reach: &Reach, later_siblings: bool) {
931 let tags = match reach {
932 Reach::Subtree if later_siblings => return self.mark_with_followers(id),
933 Reach::Subtree => return self.mark_restyle(id),
934 Reach::Own => return self.mark_self(id),
935 Reach::Tags(tags) => tags,
936 };
937 self.mark_self(id);
938 let mut stack: Vec<u32> = self
939 .node(id)
940 .map(|n| n.children.clone())
941 .unwrap_or_default();
942 if later_siblings {
943 if let Some(siblings) = self
944 .node(id)
945 .and_then(|n| self.node(n.parent))
946 .map(|p| &p.children)
947 {
948 if let Some(at) = siblings.iter().position(|&c| c == id) {
949 stack.extend_from_slice(&siblings[at + 1..]);
950 }
951 }
952 }
953 let mut hits: Vec<u32> = Vec::new();
954 while let Some(c) = stack.pop() {
955 let Some(n) = self.node(c) else { continue };
956 if n.kind == Kind::Element && tags.contains(&n.tag) {
957 hits.push(c);
958 continue;
959 }
960 stack.extend_from_slice(&n.children);
961 }
962 for c in hits {
963 self.mark_restyle(c);
964 }
965 }
966
967 fn mark_self(&mut self, id: u32) {
968 if self.dirty_all || id == 0 || self.node(id).is_none_or(|n| n.mark_gen == self.restyle_gen)
969 {
970 return;
971 }
972 self.self_marks.push(id);
973 }
974
975 pub fn set_listener(&mut self, id: u32, event: u32, on: bool) {
976 if let Some(n) = self.node_mut(id) {
977 if event >= u64::BITS {
980 return;
981 }
982 let bit = 1u64 << event;
983 if on {
984 n.listeners |= bit;
985 } else {
986 n.listeners &= !bit;
987 }
988 self.dirty = true;
989 self.touch(id);
990 }
991 }
992
993 pub fn is_dirty(&self) -> bool {
994 self.dirty || self.style_flushed
995 }
996
997 pub fn take_dirty(&mut self) -> bool {
998 let flushed = std::mem::take(&mut self.style_flushed);
1000 std::mem::take(&mut self.dirty) || flushed
1001 }
1002
1003 pub fn live_count(&self) -> u32 {
1005 self.nodes.iter().filter(|n| n.is_some()).count() as u32
1006 }
1007
1008 pub(crate) fn mem_estimate(&self) -> TreeMem {
1009 use std::collections::HashSet;
1010 use std::mem::size_of;
1011 let mut m = TreeMem {
1012 slots: self.nodes.len(),
1013 slot_bytes: self.nodes.capacity() * size_of::<Option<Node>>(),
1014 ..TreeMem::default()
1015 };
1016 let mut refinements: HashSet<*const gpui::StyleRefinement> = HashSet::new();
1017 let mut vars: HashSet<*const sk_css::Vars> = HashSet::new();
1018 let mut inlines: HashSet<*const sk_css::InlineStyle> = HashSet::new();
1019 let note_ref = |r: &std::rc::Rc<gpui::StyleRefinement>,
1020 set: &mut HashSet<*const gpui::StyleRefinement>| {
1021 set.insert(std::rc::Rc::as_ptr(r));
1022 };
1023 for n in self.nodes.iter().flatten() {
1024 m.nodes += 1;
1025 match n.kind {
1026 Kind::Element => m.elements += 1,
1027 Kind::Text => m.texts += 1,
1028 Kind::Anchor => m.anchors += 1,
1029 }
1030 let mut own = n.children.capacity() * 4 + n.text.capacity() + n.class_attr.capacity();
1031 own += n.style.capacity() * size_of::<(u32, String)>()
1032 + n.style.iter().map(|(_, v)| v.capacity()).sum::<usize>();
1033 own += n.classes.capacity() * size_of::<String>()
1034 + n.classes.iter().map(|c| c.capacity()).sum::<usize>();
1035 own += n.props.capacity() * size_of::<(u32, String, u32)>()
1036 + n.props.iter().map(|(_, v, _)| v.capacity()).sum::<usize>();
1037 own += n.scopes.capacity() * size_of::<String>()
1038 + n.scopes.iter().map(|s| s.capacity()).sum::<usize>();
1039 m.owned_bytes += own;
1040 if let Some(i) = &n.inline {
1041 inlines.insert(std::rc::Rc::as_ptr(i));
1042 }
1043 if let Some(cs) = &n.computed {
1044 m.computed += 1;
1045 note_ref(&cs.base, &mut refinements);
1046 for r in [
1047 &cs.hover,
1048 &cs.active,
1049 &cs.focus,
1050 &cs.focus_visible,
1051 &cs.focus_within,
1052 &cs.placeholder,
1053 &cs.selection,
1054 &cs.file_selector_button,
1055 ]
1056 .into_iter()
1057 .flatten()
1058 {
1059 note_ref(r, &mut refinements);
1060 }
1061 for (_, r) in [&cs.group_hover, &cs.group_active].into_iter().flatten() {
1062 note_ref(r, &mut refinements);
1063 }
1064 if let Some(g) = &cs.group_focus {
1065 for (_, r) in [&g.focus, &g.focus_visible, &g.focus_within]
1066 .into_iter()
1067 .flatten()
1068 {
1069 note_ref(r, &mut refinements);
1070 }
1071 }
1072 if vars.insert(std::rc::Rc::as_ptr(&cs.vars)) {
1073 m.var_entries += cs.vars.len();
1074 }
1075 }
1076 }
1077 m.computed_bytes = m.computed * size_of::<sk_css::ComputedStates>();
1078 m.refinements = refinements.len();
1079 m.refinement_bytes = refinements.len() * (size_of::<gpui::StyleRefinement>() + 16);
1080 m.vars_maps = vars.len();
1081 m.vars_bytes = vars.len() * (size_of::<sk_css::Vars>() + 16)
1083 + m.var_entries * 2 * size_of::<std::rc::Rc<str>>();
1084 m.inlines = inlines.len();
1085 m.inline_bytes = inlines.len() * (size_of::<sk_css::InlineStyle>() + 16);
1086 m.names = self.names.len();
1087 m.total_bytes = m.slot_bytes
1088 + m.owned_bytes
1089 + m.computed_bytes
1090 + m.refinement_bytes
1091 + m.vars_bytes
1092 + m.inline_bytes;
1093 m
1094 }
1095
1096 pub fn mark_restyle_subtree(&mut self, id: u32) {
1099 self.dirty = true;
1100 self.mark_restyle(id);
1101 }
1102
1103 pub fn mark_dirty(&mut self) {
1104 self.dirty = true;
1105 self.dirty_all = true;
1106 }
1107
1108 pub(crate) fn touch(&mut self, id: u32) {
1111 let mut cur = id;
1112 for _ in 0..4096 {
1114 let Some(n) = self.node_mut(cur) else { return };
1115 n.sub_rev = n.sub_rev.wrapping_add(1);
1116 match n.parent {
1117 0 => return,
1118 p => cur = p,
1119 }
1120 }
1121 }
1122
1123 pub(crate) fn touch_mutated(&mut self, id: u32, include_self: bool) {
1129 if !self.has_anchors.get() {
1130 self.touch(id);
1131 return;
1132 }
1133 let mut whole: Vec<u32> = Vec::new();
1134 let mut cur = id;
1135 let mut first = true;
1136 for _ in 0..4096 {
1137 let Some(n) = self.node_mut(cur) else { break };
1138 n.sub_rev = n.sub_rev.wrapping_add(1);
1139 let flags = n.sel_flags.get();
1140 let parent = n.parent;
1141 if include_self || !first {
1142 if flags & sel::HAS_DESC != 0 {
1143 whole.push(cur);
1144 } else if flags & sel::HAS_SELF != 0 {
1145 self.self_marks.push(cur);
1146 }
1147 }
1148 first = false;
1149 let earlier: Vec<u32> = match self.node(parent) {
1152 Some(p) if p.sel_flags.get() & sel::HAS_NEXT != 0 => p
1153 .children
1154 .iter()
1155 .take_while(|&&c| c != cur)
1156 .copied()
1157 .collect(),
1158 _ => Vec::new(),
1159 };
1160 for sibling in earlier {
1161 let flags = self.node(sibling).map_or(0, |n| n.sel_flags.get());
1162 if flags & sel::HAS_DESC != 0 {
1163 whole.push(sibling);
1164 } else if flags & sel::HAS_SELF != 0 {
1165 self.self_marks.push(sibling);
1166 }
1167 }
1168 match parent {
1169 0 => break,
1170 p => cur = p,
1171 }
1172 }
1173 for a in whole {
1174 self.mark_with_followers(a);
1175 }
1176 }
1177
1178 pub fn sub_rev(&self, id: u32) -> u64 {
1181 self.node(id).map(|n| n.sub_rev).unwrap_or(0)
1182 }
1183
1184 fn mark_restyle(&mut self, id: u32) {
1189 if self.dirty_all || id == 0 {
1190 return;
1191 }
1192 let gen = self.restyle_gen;
1193 match self.node_mut(id) {
1194 Some(n) if n.mark_gen != gen => n.mark_gen = gen,
1195 _ => return,
1196 }
1197 self.flag_path(id);
1198 }
1199
1200 fn mark_with_followers(&mut self, id: u32) {
1203 self.mark_restyle(id);
1204 if !self.sibling_combinators {
1205 return;
1206 }
1207 let later: Vec<u32> = self
1208 .node(id)
1209 .and_then(|n| self.node(n.parent))
1210 .map(|p| {
1211 p.children
1212 .iter()
1213 .skip_while(|&&c| c != id)
1214 .skip(1)
1215 .copied()
1216 .collect()
1217 })
1218 .unwrap_or_default();
1219 for s in later {
1220 self.mark_restyle(s);
1221 }
1222 }
1223
1224 fn flag_path(&mut self, id: u32) {
1227 let gen = self.restyle_gen;
1228 let root = self.root;
1229 let mut cur = id;
1230 for _ in 0..4096 {
1232 let Some(n) = self.node_mut(cur) else { return };
1233 if n.desc_gen == gen {
1234 return;
1235 }
1236 n.desc_gen = gen;
1237 match n.parent {
1238 0 => {
1239 if cur != root {
1240 self.detached_marks.push(cur);
1241 }
1242 return;
1243 }
1244 p => cur = p,
1245 }
1246 }
1247 }
1248
1249 pub(crate) fn invalidate_viewport_inline(&mut self) -> usize {
1254 self.invalidate_inline_where(has_viewport_unit)
1255 }
1256
1257 pub(crate) fn invalidate_rem_inline(&mut self) -> usize {
1258 self.invalidate_inline_where(has_rem_unit)
1259 }
1260
1261 fn invalidate_inline_where(&mut self, names_the_unit: fn(&str) -> bool) -> usize {
1262 let hits: Vec<u32> = self
1263 .nodes
1264 .iter()
1265 .enumerate()
1266 .filter_map(|(i, n)| {
1267 let n = n.as_ref()?;
1268 n.style
1269 .iter()
1270 .any(|(_, v)| names_the_unit(v))
1271 .then_some(i as u32)
1272 })
1273 .collect();
1274 for &id in &hits {
1275 if let Some(n) = self.node_mut(id) {
1276 n.inline_dirty = true;
1277 }
1278 self.inline_dirty_nodes.push(id);
1279 self.mark_restyle(id);
1280 self.touch(id);
1281 }
1282 if !hits.is_empty() {
1283 self.dirty = true;
1284 }
1285 hits.len()
1286 }
1287
1288 pub(crate) fn invalidate_font_inline(&mut self) -> usize {
1291 self.invalidate_inline_named(&["font", "font-family"])
1292 }
1293
1294 fn invalidate_inline_named(&mut self, names: &[&str]) -> usize {
1296 let keys: Vec<u32> = names
1297 .iter()
1298 .filter_map(|k| self.name_ids.get(*k).copied())
1299 .collect();
1300 if keys.is_empty() {
1301 return 0;
1302 }
1303 let hits: Vec<u32> = self
1304 .nodes
1305 .iter()
1306 .enumerate()
1307 .filter_map(|(i, n)| {
1308 let n = n.as_ref()?;
1309 n.style
1310 .iter()
1311 .any(|(k, _)| keys.contains(k))
1312 .then_some(i as u32)
1313 })
1314 .collect();
1315 for &id in &hits {
1316 if let Some(n) = self.node_mut(id) {
1317 n.inline_dirty = true;
1318 }
1319 self.inline_dirty_nodes.push(id);
1320 self.mark_restyle(id);
1321 self.touch(id);
1322 }
1323 if !hits.is_empty() {
1324 self.dirty = true;
1325 }
1326 hits.len()
1327 }
1328
1329 pub fn restyle(&mut self, engine: Option<&sk_css::Engine>, env: &sk_css::Env) {
1331 match engine {
1332 Some(e) => self.restyle_with(e, env),
1333 None => NO_SHEET.with(|e| self.restyle_with(e, env)),
1336 }
1337 }
1338
1339 fn restyle_roots(&mut self) -> Vec<u32> {
1343 let gen = self.restyle_gen;
1344 self.restyle_gen = self.restyle_gen.wrapping_add(1).max(1);
1345 let detached = std::mem::take(&mut self.detached_marks);
1346 if std::mem::take(&mut self.dirty_all) {
1347 let mut roots: Vec<u32> = Vec::new();
1348 if self.root != 0 && self.node(self.root).is_some() {
1349 roots.push(self.root);
1350 }
1351 roots.extend(
1352 (1..self.nodes.len() as u32)
1353 .filter(|&id| id != self.root)
1354 .filter(|&id| self.node(id).is_some_and(|n| n.parent == 0)),
1355 );
1356 return roots;
1357 }
1358
1359 let mut roots: Vec<u32> = Vec::new();
1360 let mut tops: Vec<u32> = Vec::new();
1363 for top in std::iter::once(self.root).chain(detached) {
1364 let Some(n) = self.node(top) else { continue };
1365 if n.desc_gen != gen || (top != self.root && n.parent != 0) || tops.contains(&top) {
1366 continue;
1367 }
1368 tops.push(top);
1369 }
1370 for top in tops {
1371 if self.collect_roots(top, gen, &mut roots, 0) {
1372 roots.push(top);
1373 }
1374 }
1375 roots
1376 }
1377
1378 fn collect_roots(&self, id: u32, gen: u32, roots: &mut Vec<u32>, depth: u32) -> bool {
1379 let Some(n) = self.node(id) else { return false };
1380 if n.mark_gen == gen || (n.kind == Kind::Element && n.computed.is_none()) || depth > 1024 {
1381 return true;
1382 }
1383 let start = roots.len();
1384 let element = n.kind == Kind::Element;
1385 for &c in &n.children {
1386 let Some(child) = self.node(c) else { continue };
1387 let whole = child.desc_gen == gen && self.collect_roots(c, gen, roots, depth + 1);
1388 if !whole {
1389 continue;
1390 }
1391 if !element {
1392 roots.truncate(start);
1395 return true;
1396 }
1397 roots.push(c);
1398 }
1399 false
1400 }
1401
1402 pub(crate) fn probe_root_font_size(
1406 &self,
1407 engine: Option<&sk_css::Engine>,
1408 env: &sk_css::Env,
1409 ) -> Option<f32> {
1410 let engine = engine?;
1411 let n = self.node(self.root)?;
1412 let parsed;
1413 let inline: Option<&sk_css::InlineStyle> = if n.inline_dirty {
1414 let body = n
1415 .style
1416 .iter()
1417 .map(|(k, v)| format!("{}: {}", self.name(*k), v))
1418 .collect::<Vec<_>>()
1419 .join("; ");
1420 parsed = (!body.is_empty())
1421 .then(|| sk_css::parse_inline_style(&body, &mut Vec::new()))
1422 .filter(|s| !s.is_empty());
1423 parsed.as_ref()
1424 } else {
1425 n.inline.as_deref()
1426 };
1427 let states = engine.compute_node_at(
1428 NodeRef {
1429 tree: self,
1430 id: self.root,
1431 },
1432 inline,
1433 &std::rc::Rc::new(sk_css::Vars::default()),
1434 None,
1435 ROOT_PARENT_FONT_SIZE,
1436 env,
1437 &mut Vec::new(),
1438 );
1439 match states.base.text.font_size? {
1440 gpui::AbsoluteLength::Pixels(p) => Some(f32::from(p)),
1441 gpui::AbsoluteLength::Rems(r) => Some(r.0 * sk_css::rem_basis()),
1444 }
1445 }
1446
1447 #[allow(clippy::type_complexity)]
1450 fn walk_inputs(
1451 &self,
1452 r: u32,
1453 env: &sk_css::Env,
1454 root_vars: &std::rc::Rc<sk_css::Vars>,
1455 ) -> (
1456 std::rc::Rc<sk_css::Vars>,
1457 bool,
1458 Inherited,
1459 sk_css::InheritedRadii,
1460 sk_css::Env,
1461 ) {
1462 let root_env = crate::windows::env_for_node(self, r, env);
1463 let mut cur = self.node(r).map_or(0, |n| n.parent);
1464 let mut parent_computed = None;
1465 for _ in 0..4096 {
1466 let Some(p) = self.node(cur) else { break };
1467 if let Some(c) = p.computed.as_ref() {
1468 parent_computed = Some(c);
1469 break;
1470 }
1471 if p.kind == Kind::Element {
1472 break;
1473 }
1474 cur = p.parent;
1475 }
1476 let inherited = parent_computed
1477 .map(|c| c.vars.clone())
1478 .unwrap_or_else(|| root_vars.clone());
1479 let inherited_inert =
1480 parent_computed.is_some_and(|c| c.extras.pointer_events_none == Some(true));
1481 let inherited_text = Inherited {
1484 color: parent_computed.and_then(|c| c.color),
1485 font_size: parent_computed.map_or(ROOT_PARENT_FONT_SIZE, |c| c.font_size),
1486 font: parent_computed
1487 .map(|c| c.computed_font.clone())
1488 .unwrap_or_default(),
1489 };
1490 let inherited_radii = parent_computed
1491 .map(|c| sk_css::InheritedRadii::of(&c.base))
1492 .unwrap_or_default();
1493 (
1494 inherited,
1495 inherited_inert,
1496 inherited_text,
1497 inherited_radii,
1498 root_env,
1499 )
1500 }
1501
1502 fn cascade_one(
1503 &self,
1504 engine: &sk_css::Engine,
1505 id: u32,
1506 (parent_vars, parent_inert, parent_text, parent_radii): (
1507 &std::rc::Rc<sk_css::Vars>,
1508 bool,
1509 Inherited,
1510 sk_css::InheritedRadii,
1511 ),
1512 env: &sk_css::Env,
1513 chain: &sk_css::container::Chain,
1514 diagnostics: &mut Vec<String>,
1515 ) -> (sk_css::ComputedStates, sk_css::InheritedRadii) {
1516 let n = self.node(id).expect("cascade_one on a live node");
1517 CASCADE_SUBJECT.with(|c| c.set(id));
1518 let mut states = sk_css::container::with_chain(chain, || {
1519 engine.compute_node_with_font(
1520 NodeRef { tree: self, id },
1521 n.inline.as_deref(),
1522 parent_vars,
1523 parent_text.color,
1524 parent_text.font_size,
1525 &parent_text.font,
1526 env,
1527 diagnostics,
1528 )
1529 });
1530 CASCADE_SUBJECT.with(|c| c.set(0));
1531 let inert = states.extras.pointer_events_none.unwrap_or(parent_inert);
1534 states.extras.pointer_events_none = Some(inert);
1535 let radii = sk_css::resolve_inherited_radii(&mut states, parent_radii);
1536 (states, radii)
1537 }
1538
1539 fn container_chain(&self, id: u32, active: bool) -> sk_css::container::Chain {
1542 if !active {
1543 return None;
1544 }
1545 let mut above = Vec::new();
1546 let mut cur = self.node(id).map_or(0, |n| n.parent);
1547 for _ in 0..4096 {
1548 let Some(n) = self.node(cur) else { break };
1549 if n.computed.is_some() {
1550 above.push(cur);
1551 }
1552 cur = n.parent;
1553 }
1554 let mut chain = None;
1555 for &a in above.iter().rev() {
1556 if let Some(cs) = self.node(a).and_then(|n| n.computed.as_ref()) {
1557 chain = sk_css::container::Container::link(
1558 a,
1559 &cs.extras,
1560 &cs.vars,
1561 cs.font_size,
1562 &chain,
1563 );
1564 }
1565 }
1566 chain
1567 }
1568
1569 fn containers_active(&self, engine: &sk_css::Engine) -> bool {
1570 engine.uses_containers() || self.inline_container_units
1571 }
1572
1573 fn settle_self_marks(
1577 &mut self,
1578 engine: &sk_css::Engine,
1579 env: &sk_css::Env,
1580 ) -> Vec<(u32, sk_css::ComputedStates)> {
1581 let mut marks = std::mem::take(&mut self.self_marks);
1582 if marks.is_empty() || self.dirty_all {
1583 return Vec::new();
1584 }
1585 marks.sort_unstable();
1586 marks.dedup();
1587 let root_vars = std::rc::Rc::new(sk_css::Vars::default());
1588 let mut diagnostics = Vec::new();
1589 let mut stored = Vec::new();
1590 let mut whole = Vec::new();
1591 let containers = self.containers_active(engine);
1592 for id in marks {
1593 let Some(n) = self.node(id) else { continue };
1594 if n.kind != Kind::Element || n.mark_gen == self.restyle_gen || n.computed.is_none() {
1595 continue;
1596 }
1597 let (vars, inert, text, radii, here_env) = self.walk_inputs(id, env, &root_vars);
1598 let (states, child_radii) = self.cascade_one(
1599 engine,
1600 id,
1601 (&vars, inert, text, radii),
1602 &here_env,
1603 &self.container_chain(id, containers),
1604 &mut diagnostics,
1605 );
1606 let Some(old) = n.computed.as_ref() else {
1607 continue;
1608 };
1609 if *old == states {
1610 continue;
1611 }
1612 let hands_down_the_same = old.vars == states.vars
1613 && old.color == states.color
1614 && old.font_size == states.font_size
1615 && old.computed_font == states.computed_font
1616 && old.extras.pointer_events_none == states.extras.pointer_events_none
1617 && old.extras.container_type == states.extras.container_type
1618 && old.extras.container_name == states.extras.container_name
1619 && sk_css::InheritedRadii::of(&old.base) == child_radii;
1620 if hands_down_the_same {
1621 stored.push((id, states));
1622 } else {
1623 whole.push(id);
1624 }
1625 }
1626 for id in whole {
1627 self.mark_restyle(id);
1628 }
1629 stored
1630 }
1631
1632 fn restyle_with(&mut self, engine: &sk_css::Engine, env: &sk_css::Env) {
1633 let _profile = sk_runtime::redjs::profiling::span("style", "Restyle DOM");
1634 thread_local! { static CACHE_ENGINE: Cell<usize> = const { Cell::new(0) }; }
1637 let addr = engine as *const sk_css::Engine as usize;
1638 if CACHE_ENGINE.with(|c| c.replace(addr)) != addr {
1639 forget_read_cache();
1640 note_parent_keys(engine);
1641 }
1642 let sheet_changed = REBIND_ANIMATIONS.with(|pending| pending.replace(false));
1643 self.sibling_combinators = engine.uses_sibling_combinators();
1644 let pass = crate::perf::Span::start();
1645 let phase = crate::perf::Span::start();
1646 let dirty_inline = std::mem::take(&mut self.inline_dirty_nodes);
1649 for id in dirty_inline {
1650 if !self.node(id).is_some_and(|n| n.inline_dirty) {
1651 continue; }
1653 let body = {
1654 let n = self.node(id).unwrap();
1655 n.style
1656 .iter()
1657 .map(|(k, v)| format!("{}: {}", self.name(*k), v))
1658 .collect::<Vec<_>>()
1659 .join("; ")
1660 };
1661 let mut diags = Vec::new();
1662 let parsed = if body.is_empty() {
1663 None
1664 } else {
1665 let style = sk_css::parse_inline_style(&body, &mut diags);
1666 (!style.is_empty()).then(|| std::rc::Rc::new(style))
1667 };
1668 for d in diags {
1669 warn_css(&format!("[css inline] {d}"));
1670 }
1671 self.inline_container_units |= parsed.is_some() && body.contains("cq");
1672 let n = self.node_mut(id).unwrap();
1673 n.inline = parsed;
1674 n.inline_dirty = false;
1675 }
1676
1677 let inline_ms = phase.ms();
1678 let phase = crate::perf::Span::start();
1679
1680 let mut diagnostics: Vec<String> = Vec::new();
1681 let full = self.dirty_all;
1682 let containers = self.containers_active(engine);
1683 if containers {
1684 crate::containers::install();
1685 }
1686 if full {
1687 crate::containers::forget_all();
1688 }
1689 let settled = self.settle_self_marks(engine, env);
1690 let roots = self.restyle_roots();
1691 let cascaded_anything = !roots.is_empty() || !settled.is_empty();
1692 let computed: Vec<(u32, sk_css::ComputedStates)> = {
1693 let this: &Tree = self;
1694 let root_vars = std::rc::Rc::new(sk_css::Vars::default());
1695 let mut out = Vec::new();
1696 let mut stack: Vec<(
1700 u32,
1701 std::rc::Rc<sk_css::Vars>,
1702 bool,
1703 Inherited,
1704 sk_css::InheritedRadii,
1705 sk_css::Env,
1706 sk_css::container::Chain,
1707 )> = Vec::new();
1708 let multiwindow = crate::windows::any_secondary();
1709 for r in roots {
1710 let (inherited, inherited_inert, inherited_text, inherited_radii, root_env) =
1713 this.walk_inputs(r, env, &root_vars);
1714 stack.push((
1715 r,
1716 inherited,
1717 inherited_inert,
1718 inherited_text,
1719 inherited_radii,
1720 root_env,
1721 this.container_chain(r, containers),
1722 ));
1723 while let Some((
1724 id,
1725 parent_vars,
1726 parent_inert,
1727 parent_text,
1728 parent_radii,
1729 here_env,
1730 chain,
1731 )) = stack.pop()
1732 {
1733 let Some(n) = this.node(id) else { continue };
1734 let (child_vars, child_inert, child_text, child_radii, child_chain) =
1735 if n.kind == Kind::Element {
1736 let (states, radii) = this.cascade_one(
1737 engine,
1738 id,
1739 (
1740 &parent_vars,
1741 parent_inert,
1742 parent_text.clone(),
1743 parent_radii,
1744 ),
1745 &here_env,
1746 &chain,
1747 &mut diagnostics,
1748 );
1749 let inert = states.extras.pointer_events_none == Some(true);
1750 let vars = states.vars.clone();
1751 let text = Inherited {
1752 color: states.color,
1753 font_size: states.font_size,
1754 font: states.computed_font.clone(),
1755 };
1756 let child_chain = if containers {
1757 sk_css::container::Container::link(
1758 id,
1759 &states.extras,
1760 &states.vars,
1761 states.font_size,
1762 &chain,
1763 )
1764 } else {
1765 None
1766 };
1767 out.push((id, states));
1768 (vars, inert, text, radii, child_chain)
1769 } else {
1770 (parent_vars, parent_inert, parent_text, parent_radii, chain)
1771 };
1772 for &c in n.children.iter().rev() {
1773 let child_env = if multiwindow {
1777 crate::windows::env_at_root(c, env).unwrap_or(here_env)
1778 } else {
1779 here_env
1780 };
1781 stack.push((
1782 c,
1783 child_vars.clone(),
1784 child_inert,
1785 child_text.clone(),
1786 child_radii,
1787 child_env,
1788 child_chain.clone(),
1789 ));
1790 }
1791 }
1792 }
1793 out
1794 };
1795 let computed = if settled.is_empty() {
1798 computed
1799 } else {
1800 let walked: std::collections::HashSet<u32> =
1801 computed.iter().map(|(id, _)| *id).collect();
1802 let mut computed = computed;
1803 computed.extend(settled.into_iter().filter(|(id, _)| !walked.contains(id)));
1804 computed
1805 };
1806 let cascade_ms = phase.ms();
1807 let cascaded = computed.len() as u64;
1808 let phase = crate::perf::Span::start();
1809 for d in diagnostics {
1810 warn_css(&format!("[css] {d}"));
1811 }
1812 let now = std::time::Instant::now();
1813 let has_keyframes = engine.has_keyframes();
1814 let keyframe_diagnostics = std::cell::RefCell::new(Vec::<String>::new());
1817 let mut restyled: Vec<u32> = Vec::new();
1818 let multiwindow = crate::windows::any_secondary();
1822 let mut display_flips: Vec<(u32, bool)> = Vec::new();
1823 ANIMATOR.with(|a| {
1824 let mut animator = a.borrow_mut();
1825 for (id, states) in computed {
1826 let node_env = if multiwindow && (has_keyframes || !states.animations.is_empty()) {
1827 crate::windows::env_for_node(self, id, env)
1828 } else {
1829 *env
1830 };
1831 let rebind = (sheet_changed || node_env != *env) && !states.animations.is_empty();
1834 let self_none = states.base.display == Some(gpui::Display::None);
1837 let animated = !states.animations.is_empty() || animator.has_animations(id);
1838 let hidden = animated && (self_none || self.hidden_above(id));
1839 let keywords = (animated
1840 || !states.transitions.is_empty()
1841 || animator.has_script_animations(id))
1842 && crate::inherit::interpolate_keywords(
1843 self,
1844 id,
1845 states.extras.interpolate_size,
1846 );
1847 animator.set_interpolate_keywords(id, keywords);
1848 if let Some(n) = self.node_mut(id) {
1849 let was_none = n
1850 .computed
1851 .as_ref()
1852 .map(|c| c.base.display == Some(gpui::Display::None));
1853 if was_none.is_some_and(|was| was != self_none) {
1854 display_flips.push((id, self_none));
1855 }
1856 if hidden {
1857 animator.cancel_animations(id, now);
1858 }
1859 if containers {
1860 crate::containers::note_committed(
1861 id,
1862 n.parent,
1863 n.computed.is_none(),
1864 &states,
1865 );
1866 }
1867 if n.computed.as_ref() != Some(&states) {
1868 let before = if containers && crate::containers::born_this_frame(id) {
1869 None
1870 } else {
1871 n.computed.as_ref()
1872 };
1873 animator.on_computed(id, before, &states, now);
1874 if !hidden
1878 && (has_keyframes
1879 || !states.animations.is_empty()
1880 || animator.has_animations(id))
1881 {
1882 animator.on_computed_animations(id, &states, now, &|name| {
1883 engine.keyframes_for(
1884 name,
1885 &states.vars,
1886 &node_env,
1887 &mut keyframe_diagnostics.borrow_mut(),
1888 )
1889 });
1890 }
1891 if states.hover_transitions() {
1894 let target = fold_hover_target(id, &states);
1895 if target.is_some() || animator.holds_state(id) {
1896 animator.on_state(id, &states, target.as_ref(), now);
1897 }
1898 }
1899 n.computed = Some(states);
1900 restyled.push(id);
1901 } else if rebind && !hidden {
1902 animator.on_computed_animations(id, &states, now, &|name| {
1903 engine.keyframes_for(
1904 name,
1905 &states.vars,
1906 &node_env,
1907 &mut keyframe_diagnostics.borrow_mut(),
1908 )
1909 });
1910 }
1911 }
1912 }
1913 for (id, none) in std::mem::take(&mut display_flips) {
1916 if !none && self.hidden_above(id) {
1917 continue; }
1919 let mut stack: Vec<u32> = self
1920 .node(id)
1921 .map(|n| n.children.clone())
1922 .unwrap_or_default();
1923 while let Some(c) = stack.pop() {
1924 let Some(node) = self.node(c) else { continue };
1925 if none {
1926 if animator.has_animations(c) {
1927 animator.cancel_animations(c, now);
1928 }
1929 } else {
1930 let Some(cs) = node.computed.as_ref() else {
1931 continue;
1932 };
1933 if cs.base.display == Some(gpui::Display::None) {
1934 continue; }
1936 if !cs.animations.is_empty() {
1937 let node_env = if multiwindow {
1938 crate::windows::env_for_node(self, c, env)
1939 } else {
1940 *env
1941 };
1942 animator.on_computed_animations(c, cs, now, &|name| {
1943 engine.keyframes_for(
1944 name,
1945 &cs.vars,
1946 &node_env,
1947 &mut keyframe_diagnostics.borrow_mut(),
1948 )
1949 });
1950 }
1951 }
1952 stack.extend(node.children.iter().copied());
1953 }
1954 }
1955 for d in animator.take_diagnostics() {
1956 warn_css(&format!("[css transition] {d}"));
1957 }
1958 });
1959 for d in keyframe_diagnostics.into_inner() {
1960 warn_css(&format!("[css] {d}"));
1961 }
1962 crate::perf::note_restyle_shape(full, restyled.len() as u64);
1963 for id in restyled {
1964 self.touch(id);
1965 }
1966 if !cascaded_anything {
1967 crate::perf::note_restyle(pass.ms(), inline_ms, cascade_ms, phase.ms(), cascaded);
1968 return;
1969 }
1970 self.group_anchors.clear();
1971 self.group_hover_deps.clear();
1972 self.group_focus_deps.clear();
1973 if engine.uses_group_states() {
1974 for (i, slot) in self.nodes.iter().enumerate() {
1975 let Some(slot) = slot else { continue };
1976 if let Some(cs) = &slot.computed {
1977 if let Some((key, _)) = &cs.group_hover {
1978 self.group_anchors.insert(*key as u32);
1979 self.group_hover_deps
1980 .entry(*key as u32)
1981 .or_default()
1982 .push(i as u32);
1983 }
1984 if let Some((key, _)) = &cs.group_active {
1985 self.group_anchors.insert(*key as u32);
1986 }
1987 for key in cs.group_focus.iter().flat_map(|g| g.anchors()) {
1988 self.group_focus_deps
1989 .entry(key as u32)
1990 .or_default()
1991 .push(i as u32);
1992 }
1993 }
1994 }
1995 }
1996 crate::perf::note_restyle(pass.ms(), inline_ms, cascade_ms, phase.ms(), cascaded);
1997 }
1998}
1999
2000thread_local! {
2001 static NO_SHEET: sk_css::Engine = sk_css::Engine::compile("");
2002 static RUNTIME_CSS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
2003 static CSS_WARNED: RefCell<std::collections::HashSet<String>> =
2004 RefCell::new(std::collections::HashSet::new());
2005 static ENGINE: RefCell<Option<sk_css::Engine>> = const { RefCell::new(None) };
2006 static REM_SETTLED: Cell<Option<(f32, f32)>> = const { Cell::new(None) };
2009 static SHEET_SOURCE: RefCell<String> = const { RefCell::new(String::new()) };
2010 static HEAD_SHEETS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
2013 static ANIMATOR: RefCell<sk_css::Animator> = RefCell::new(sk_css::Animator::new());
2014 static REBIND_ANIMATIONS: Cell<bool> = const { Cell::new(false) };
2015 static ENV: Cell<sk_css::Env> = Cell::new(sk_css::Env::default());
2019}
2020
2021pub fn set_env(env: sk_css::Env) -> bool {
2024 set_reduce_motion(env.reduce_motion);
2025 let primary = crate::windows::primary();
2026 let env = sk_css::Env {
2027 dynamic_range_high: crate::surface::dynamic_range_high(primary),
2028 ..env
2029 };
2030 crate::windows::set_env(primary, env);
2031 ENV.with(|e| {
2032 if e.get() == env {
2033 return false;
2034 }
2035 e.set(env);
2036 true
2037 })
2038}
2039
2040pub fn set_window_env(k: crate::windows::WinKey, env: sk_css::Env) -> bool {
2041 let env = sk_css::Env {
2042 dynamic_range_high: crate::surface::dynamic_range_high(k),
2043 ..env
2044 };
2045 if !crate::windows::set_env(k, env) {
2046 return false;
2047 }
2048 let root = crate::windows::root_of(k);
2049 if root != 0 {
2050 with_tree(|t| t.mark_restyle_subtree(root));
2051 }
2052 true
2053}
2054
2055pub fn env() -> sk_css::Env {
2056 ENV.with(|e| e.get())
2057}
2058
2059pub fn animation_overlay(
2060 id: u32,
2061 base: &gpui::StyleRefinement,
2062 now: std::time::Instant,
2063) -> Option<gpui::StyleRefinement> {
2064 ANIMATOR.with(|a| a.borrow().overlay(id, base, now))
2065}
2066
2067pub fn animated_extras(id: u32, now: std::time::Instant) -> Option<sk_css::Extras> {
2068 ANIMATOR.with(|animator| animator.borrow().animated_extras(id, now))
2069}
2070
2071thread_local! {
2072 static HOVERED: RefCell<std::collections::HashSet<u32>> =
2075 RefCell::new(std::collections::HashSet::new());
2076}
2077
2078pub fn note_hover(id: u32, hovered: bool) {
2083 let changed = HOVERED.with(|h| {
2084 let mut h = h.borrow_mut();
2085 if hovered {
2086 h.insert(id)
2087 } else {
2088 h.remove(&id)
2089 }
2090 });
2091 if !changed {
2092 return;
2093 }
2094 let now = std::time::Instant::now();
2095 retarget_state(id, now);
2096 let deps = read_tree(|t| t.group_hover_deps.get(&id).cloned());
2097 for dep in deps.into_iter().flatten() {
2098 retarget_state(dep, now);
2099 }
2100}
2101
2102pub fn is_hovered(id: u32) -> bool {
2104 HOVERED.with(|h| h.borrow().contains(&id))
2105}
2106
2107pub fn live_style(id: u32) -> Option<gpui::StyleRefinement> {
2110 use gpui::Refineable as _;
2111 let cs = read_tree(|t| t.node(id).and_then(|n| n.computed.clone()))?;
2112 let mut live = (*cs.base).clone();
2113 if let Some(overlay) = animation_overlay(id, &cs.base, std::time::Instant::now()) {
2114 live.refine(&overlay);
2115 }
2116 if let Some(group) = &cs.group_focus {
2117 read_tree(|t| {
2118 group.fold(&mut live, |key, state| {
2119 crate::live_state::focus_holds(t, key as u32, state)
2120 })
2121 });
2122 }
2123 if let Some(rung) = fold_hover_target(id, &cs) {
2124 match sk_css::strip_transitioned(&rung, &cs.transitions) {
2125 Some(stripped) => live.refine(&stripped),
2126 None => live.refine(&rung),
2127 }
2128 }
2129 Some(live)
2130}
2131
2132fn fold_hover_target(id: u32, cs: &sk_css::ComputedStates) -> Option<gpui::StyleRefinement> {
2133 HOVERED.with(|h| {
2134 let h = h.borrow();
2135 let own = h.contains(&id);
2136 let group = cs
2137 .group_hover
2138 .as_ref()
2139 .is_some_and(|(key, _)| h.contains(&(*key as u32)));
2140 cs.hovered(own, group)
2141 })
2142}
2143
2144fn retarget_state(id: u32, now: std::time::Instant) {
2145 let Some(cs) = read_tree(|t| t.node(id).and_then(|n| n.computed.clone())) else {
2146 return;
2147 };
2148 if !cs.hover_transitions() {
2149 return;
2150 }
2151 let target = fold_hover_target(id, &cs);
2152 ANIMATOR.with(|a| a.borrow_mut().on_state(id, &cs, target.as_ref(), now));
2153}
2154
2155pub fn animating() -> bool {
2157 let now = std::time::Instant::now();
2158 ANIMATOR.with(|a| {
2159 let a = a.borrow();
2160 a.any_active(now) || a.any_animation(now)
2161 })
2162}
2163
2164pub(crate) fn moving_paths(now: std::time::Instant, out: &mut std::collections::HashSet<u32>) {
2167 ANIMATOR.with(|a| {
2168 let a = a.borrow();
2169 read_tree(|t| {
2170 for id in a.moving_nodes(now) {
2171 let mut cur = id;
2172 while cur != 0 && out.insert(cur) {
2173 cur = t.node(cur).map_or(0, |n| n.parent);
2174 }
2175 }
2176 });
2177 });
2178}
2179
2180pub(crate) fn moving_nodes(now: std::time::Instant, out: &mut std::collections::HashSet<u32>) {
2183 ANIMATOR.with(|a| out.extend(a.borrow().moving_nodes(now)));
2184}
2185
2186pub fn advance_animations() -> bool {
2190 let now = std::time::Instant::now();
2191 ANIMATOR.with(|a| {
2192 let mut a = a.borrow_mut();
2193 a.tick(now);
2196 a.finish_settled(now)
2197 })
2198}
2199
2200pub fn take_anim_events() -> Vec<sk_css::AnimEvent> {
2201 ANIMATOR.with(|a| a.borrow_mut().take_events())
2202}
2203
2204thread_local! {
2205 static SCRIPT_DIRTY: Cell<bool> = const { Cell::new(false) };
2206 static TIMELINE_ORIGIN: Cell<Option<std::time::Instant>> = const { Cell::new(None) };
2207}
2208
2209fn ensure_timeline_origin(animator: &mut sk_css::Animator) {
2212 if TIMELINE_ORIGIN.with(|o| o.get()).is_some() {
2213 return;
2214 }
2215 let now = std::time::Instant::now();
2216 let ms = unsafe { sk_runtime::redjs::ffi::redjs_now() };
2217 let origin = now
2218 .checked_sub(std::time::Duration::from_secs_f64(ms.max(0.0) / 1000.0))
2219 .unwrap_or(now);
2220 TIMELINE_ORIGIN.with(|o| o.set(Some(origin)));
2221 animator.set_timeline_origin(origin);
2222}
2223
2224fn script_touched(node: Option<u32>) {
2225 if let Some(node) = node {
2226 with_tree(|t| t.touch(node));
2227 }
2228 SCRIPT_DIRTY.with(|d| d.set(true));
2229}
2230
2231pub(crate) fn script_anim_set(
2234 id: u32,
2235 node: u32,
2236 frames: &[sk_css::ScriptFrame],
2237 timing: sk_css::ScriptTiming,
2238) -> sk_css::ScriptKeyframeNotes {
2239 let (vars, keywords) = read_tree(|t| {
2240 let own = t.node(node).and_then(|n| n.computed.as_ref());
2241 (
2242 own.map(|c| c.vars.clone()),
2243 crate::inherit::interpolate_keywords(
2244 t,
2245 node,
2246 own.and_then(|c| c.extras.interpolate_size),
2247 ),
2248 )
2249 });
2250 let vars = vars.unwrap_or_default();
2251 let (keyframes, notes) = with_engine(|engine| {
2252 let compile = || sk_css::script_keyframes(frames, &vars, &env());
2253 match engine {
2254 Some(engine) => engine.with_functions(compile),
2255 None => compile(),
2256 }
2257 });
2258 let previous = ANIMATOR.with(|a| {
2259 let mut a = a.borrow_mut();
2260 ensure_timeline_origin(&mut a);
2261 a.set_interpolate_keywords(node, keywords);
2262 let previous = a.script_node(id);
2263 a.script_set(id, node, keyframes, timing);
2264 previous
2265 });
2266 if previous.is_some_and(|p| p != node) {
2268 script_touched(previous);
2269 }
2270 script_touched(Some(node));
2271 notes
2272}
2273
2274pub(crate) fn script_anim_clock(id: u32, clock: sk_css::ScriptClock) {
2275 let node = ANIMATOR.with(|a| a.borrow_mut().script_clock(id, clock));
2276 script_touched(node);
2277}
2278
2279pub(crate) fn script_anim_drop(id: u32) {
2280 let node = ANIMATOR.with(|a| a.borrow_mut().script_drop(id));
2281 script_touched(node);
2282}
2283
2284pub(crate) fn script_anim_values(id: u32) -> Option<Vec<(String, String)>> {
2285 let now = std::time::Instant::now();
2286 ANIMATOR.with(|a| {
2287 let a = a.borrow();
2288 let node = a.script_node(id)?;
2289 let base = read_tree(|t| {
2290 t.node(node)
2291 .and_then(|n| n.computed.as_ref().map(|c| c.base.clone()))
2292 })
2293 .unwrap_or_default();
2294 a.script_values(id, &base, now)
2295 })
2296}
2297
2298pub(crate) fn take_script_dirty() -> bool {
2303 SCRIPT_DIRTY.with(|d| d.replace(false))
2304}
2305
2306pub(crate) fn with_sheet<R>(f: impl FnOnce(&sk_css::Engine) -> R) -> R {
2308 ENGINE.with(|e| match e.borrow().as_ref() {
2309 Some(engine) => f(engine),
2310 None => NO_SHEET.with(|engine| f(engine)),
2311 })
2312}
2313
2314pub(crate) fn animate_detached(id: u32, states: &sk_css::ComputedStates, now: std::time::Instant) {
2317 let env = env();
2318 let diagnostics = std::cell::RefCell::new(Vec::new());
2319 with_sheet(|engine| {
2320 ANIMATOR.with(|a| {
2321 a.borrow_mut()
2322 .on_computed_animations(id, states, now, &|name| {
2323 engine.keyframes_for(name, &states.vars, &env, &mut diagnostics.borrow_mut())
2324 });
2325 });
2326 });
2327 for d in diagnostics.into_inner() {
2328 warn_css(&format!("[css] {d}"));
2329 }
2330}
2331
2332pub(crate) fn animations_finished(id: u32, now: std::time::Instant) -> bool {
2333 ANIMATOR.with(|a| a.borrow().animations_finished(id, now))
2334}
2335
2336pub(crate) fn cancel_detached(id: u32) {
2337 let now = std::time::Instant::now();
2338 ANIMATOR.with(|a| a.borrow_mut().cancel_animations(id, now));
2339}
2340
2341pub fn animator_gc() {
2342 ANIMATOR.with(|a| {
2343 a.borrow_mut()
2344 .gc(&|id| crate::view_transition::is_pseudo(id) || read_tree(|t| t.node(id).is_some()));
2345 });
2346 HOVERED.with(|h| {
2349 let mut h = h.borrow_mut();
2350 if !h.is_empty() {
2351 read_tree(|t| h.retain(|&id| t.node(id).is_some()));
2352 }
2353 });
2354}
2355
2356pub fn set_reduce_motion(on: bool) {
2357 ANIMATOR.with(|a| a.borrow_mut().set_reduce_motion(on));
2358}
2359
2360fn sheet_sources() -> Vec<String> {
2365 let mut out = vec![SHEET_SOURCE.with(|s| s.borrow().clone())];
2366 HEAD_SHEETS.with(|h| out.extend(h.borrow().iter().cloned()));
2367 RUNTIME_CSS.with(|r| out.extend(r.borrow().iter().cloned()));
2368 out
2369}
2370
2371fn sync_runtime_sheets() {
2372 let next = with_tree(|t| {
2373 let mut placed: Vec<((bool, u32, Vec<usize>), u32)> = Vec::new();
2374 for &id in t.style_nodes.iter() {
2375 let mut ancestor = id;
2379 let mut path = Vec::new();
2380 let mut top = None;
2381 for _ in 0..4096 {
2382 if ancestor == t.root || crate::windows::window_of_root(ancestor).is_some() {
2383 top = Some(ancestor);
2384 break;
2385 }
2386 let Some(node) = t.node(ancestor) else { break };
2387 let Some(parent) = t.node(node.parent) else {
2388 break;
2389 };
2390 path.push(
2391 parent
2392 .children
2393 .iter()
2394 .position(|&c| c == ancestor)
2395 .unwrap_or(usize::MAX),
2396 );
2397 ancestor = node.parent;
2398 }
2399 let Some(top) = top else { continue };
2400 path.reverse();
2401 placed.push(((top != t.root, top, path), id));
2402 }
2403 placed.sort();
2404 let mut sheets = Vec::new();
2405 for (_, id) in placed {
2406 fn walk(t: &Tree, id: u32, out: &mut String) {
2407 let Some(n) = t.node(id) else { return };
2408 out.push_str(&n.text);
2409 for &c in &n.children {
2410 walk(t, c, out);
2411 }
2412 }
2413 let mut out = String::new();
2414 walk(t, id, &mut out);
2415 sheets.push(out);
2416 }
2417 sheets
2418 });
2419 if RUNTIME_CSS.with(|r| *r.borrow() == next) {
2420 return;
2421 }
2422 RUNTIME_CSS.with(|r| *r.borrow_mut() = next);
2423 recompile_sheet(
2426 crate::perf::FullReason::StyleElement,
2427 "a <style> element in the tree changed — recompiling the stylesheet",
2428 );
2429}
2430
2431#[cfg(test)]
2432pub(crate) fn set_stylesheet(css: String) {
2433 set_stylesheet_with_head(css, Vec::new());
2434}
2435
2436pub fn set_stylesheet_with_head(css: String, head: Vec<String>) -> bool {
2440 let same = ENGINE.with(|e| e.borrow().is_some())
2441 && SHEET_SOURCE.with(|s| *s.borrow() == css)
2442 && HEAD_SHEETS.with(|h| *h.borrow() == head);
2443 if same {
2444 return false;
2445 }
2446 let fresh = SHEET_SOURCE.with(|s| *s.borrow() != css);
2449 if fresh {
2450 CSS_WARNED.with(|w| w.borrow_mut().clear());
2451 }
2452 let before = crate::perf::live_bytes();
2453 SHEET_SOURCE.with(|s| *s.borrow_mut() = css);
2454 HEAD_SHEETS.with(|h| *h.borrow_mut() = head);
2455 let span = crate::perf::Span::start();
2456 let took = std::time::Instant::now();
2457 let sources = sheet_sources();
2458 let engine = compile(&sources);
2459 crate::perf::note_recompile(span.ms());
2460 set_engine(engine);
2461 let len = sources.iter().map(String::len).sum();
2462 drop(sources);
2463 crate::perf::note_sheet_compile(
2464 took.elapsed().as_secs_f32() * 1000.0,
2465 len,
2466 before,
2467 crate::perf::live_bytes(),
2468 );
2469 true
2470}
2471
2472fn compile(sources: &[String]) -> sk_css::Engine {
2475 crate::fonts::note_sheet(&sources.join("\n"));
2476 let sheets: Vec<&str> = sources.iter().map(String::as_str).collect();
2477 sk_css::Engine::compile_sheets(&sheets)
2478}
2479
2480pub(crate) fn recompile_for_fonts() {
2483 recompile_sheet(
2484 crate::perf::FullReason::Fonts,
2485 "web fonts were registered — recompiling the stylesheet",
2486 );
2487 with_tree(|t| {
2488 t.invalidate_font_inline();
2489 t.mark_dirty();
2490 });
2491}
2492
2493pub fn effects_changed() {
2498 recompile_sheet(
2499 crate::perf::FullReason::Stylesheet,
2500 "the app's `--shading` effects were rebuilt — recompiling the stylesheet",
2501 );
2502 with_tree(|t| {
2503 t.invalidate_inline_named(&["--shading"]);
2504 t.mark_dirty();
2505 });
2506}
2507
2508pub(crate) fn set_engine(engine: sk_css::Engine) {
2509 REBIND_ANIMATIONS.with(|pending| pending.set(true));
2512 for d in &engine.diagnostics {
2513 warn_css(&format!("[css] {d}"));
2514 }
2515 note_parent_keys(&engine);
2516 ENGINE.with(|c| *c.borrow_mut() = Some(engine));
2517 forget_read_cache();
2520}
2521
2522fn forget_read_cache() {
2523 READ_CACHE.with(|c| c.iter().for_each(|s| s.set((0, 0, 0))));
2524}
2525
2526fn note_parent_keys(engine: &sk_css::Engine) {
2530 READ_ON_OTHERS.with(|r| {
2531 let mut r = r.borrow_mut();
2532 let map = &mut r.names[NameKind::Class as usize];
2533 for name in engine.classes_keyed_on_the_parent() {
2534 let readers = match map.get_mut(name) {
2535 Some(readers) => readers,
2536 None => map.entry(name.into()).or_default(),
2537 };
2538 readers.all = true;
2539 readers.tags = Vec::new();
2540 }
2541 });
2542}
2543
2544pub(crate) fn with_engine<R>(f: impl FnOnce(Option<&sk_css::Engine>) -> R) -> R {
2545 ENGINE.with(|e| f(e.borrow().as_ref()))
2546}
2547
2548pub fn restyle_all() {
2552 let pending = read_tree(|t| t.dirty);
2553 sync_runtime_sheets();
2554 let env = env();
2555 let basis_moved = sk_css::set_viewport_basis(env.viewport_width, env.viewport_height);
2561 if basis_moved && sk_css::uses_viewport_units() {
2562 rebase_viewport(env.viewport_width, env.viewport_height);
2563 }
2564 if basis_moved {
2566 with_tree(|t| t.invalidate_viewport_inline());
2567 }
2568 if sk_css::uses_viewport_units() && crate::windows::any_secondary() {
2569 crate::render::warn_compat(
2570 "multiwindow-viewport-units",
2571 "A-M05: this stylesheet uses `vw`/`vh`/`rem`, which Skathi flattens to px when \
2572 the sheet is COMPILED — so those lengths resolve against the PRIMARY window's \
2573 viewport in every window, including pop-outs. `@media` conditions, `env()` and \
2574 `prefers-color-scheme` are already per-window.",
2575 );
2576 }
2577 let probe = || {
2585 ENGINE.with(|eng| {
2586 let eng = eng.borrow();
2587 read_tree(|t| t.probe_root_font_size(eng.as_ref(), &env))
2588 })
2589 };
2590 let mut earlier: Option<(f32, f32)> = None;
2591 for _ in 0..REM_BASIS_PASSES {
2592 let Some(root_font_size) = probe() else {
2593 break;
2594 };
2595 let basis = sk_css::rem_basis();
2596 if REM_SETTLED.with(Cell::get) == Some((basis, root_font_size)) {
2597 break;
2598 }
2599 let at_initial = earlier.and_then(|(b0, p0)| {
2600 let moved = (root_font_size - p0).abs() > 1e-3 && (basis - b0).abs() > 1e-3;
2601 moved.then(|| p0 + (root_font_size - p0) / (basis - b0) * (ROOT_PARENT_FONT_SIZE - b0))
2602 });
2603 earlier = Some((basis, root_font_size));
2604 let next = at_initial.unwrap_or(root_font_size);
2605 let moved = sk_css::set_rem_basis(next);
2606 if moved {
2607 with_tree(|t| t.invalidate_rem_inline());
2608 }
2609 let recompiled = moved
2610 && recompile_sheet(crate::perf::FullReason::RemBasis, &format!(
2611 "rem basis is now {next}px (the root element's font-size) — recompiling \n the stylesheet"
2612 ));
2613 if at_initial.is_some() {
2614 let settled = if recompiled {
2615 probe()
2616 } else {
2617 Some(root_font_size)
2618 };
2619 REM_SETTLED.with(|c| c.set(settled.map(|size| (sk_css::rem_basis(), size))));
2620 break;
2621 }
2622 REM_SETTLED.with(|c| c.set(None));
2623 if !recompiled {
2624 break;
2625 }
2626 }
2627 with_tree(|t| t.dirty = pending);
2630 ENGINE.with(|eng| {
2631 let eng = eng.borrow();
2632 with_tree(|t| t.restyle(eng.as_ref(), &env));
2633 });
2634}
2635
2636fn has_viewport_unit(value: &str) -> bool {
2637 const UNITS: [&str; 24] = [
2638 "vw", "vh", "vi", "vb", "vmin", "vmax", "svw", "svh", "svi", "svb", "svmin", "svmax",
2639 "lvw", "lvh", "lvi", "lvb", "lvmin", "lvmax", "dvw", "dvh", "dvi", "dvb", "dvmin", "dvmax",
2640 ];
2641 has_unit(value, &UNITS)
2642}
2643
2644fn has_rem_unit(value: &str) -> bool {
2645 has_unit(value, &["rem"])
2646}
2647
2648fn has_unit(value: &str, units: &[&str]) -> bool {
2649 let b = value.as_bytes();
2650 let mut i = 0;
2651 while i < b.len() {
2652 if b[i].is_ascii_digit() || (b[i] == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) {
2653 while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
2654 i += 1;
2655 }
2656 let start = i;
2657 while i < b.len() && b[i].is_ascii_alphabetic() {
2658 i += 1;
2659 }
2660 let unit = value[start..i].to_ascii_lowercase();
2661 if units.contains(&unit.as_str()) {
2662 return true;
2663 }
2664 } else if b[i].is_ascii_alphabetic()
2665 || b[i] == b'_'
2666 || (b[i] == b'-'
2667 && b.get(i + 1)
2668 .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'-' || *c == b'_'))
2669 {
2670 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'-' || b[i] == b'_') {
2672 i += 1;
2673 }
2674 } else {
2675 i += 1;
2676 }
2677 }
2678 false
2679}
2680
2681pub fn flush_pending_style() {
2686 let pending = with_tree(|t| {
2687 if !t.dirty {
2688 return false;
2689 }
2690 t.dirty = false;
2691 t.style_flushed = true;
2692 true
2693 });
2694 if pending {
2695 crate::perf::note_style_flush();
2696 restyle_all();
2697 crate::render::gc_node_state();
2698 animator_gc();
2699 }
2700}
2701
2702fn recompile_sheet(reason: crate::perf::FullReason, why: &str) -> bool {
2703 crate::log::record("dev", format!("[css] {why}"));
2706 let sources = sheet_sources();
2707 if sources.iter().all(|s| s.trim().is_empty()) {
2708 return false;
2709 }
2710 let before = crate::perf::live_bytes();
2711 let span = crate::perf::Span::start();
2712 let took = std::time::Instant::now();
2713 let engine = compile(&sources);
2714 crate::perf::note_recompile(span.ms());
2715 crate::perf::note_full(reason);
2716 set_engine(engine);
2717 let len = sources.iter().map(String::len).sum();
2718 drop(sources);
2719 crate::perf::note_sheet_compile(
2720 took.elapsed().as_secs_f32() * 1000.0,
2721 len,
2722 before,
2723 crate::perf::live_bytes(),
2724 );
2725 with_tree(|t| t.mark_dirty());
2726 true
2727}
2728
2729fn rebase_viewport(width: f32, height: f32) {
2733 let took = std::time::Instant::now();
2734 let rebased = ENGINE.with(|e| e.borrow_mut().as_mut().is_some_and(|e| e.rebase_viewport()));
2735 if !rebased {
2736 recompile_sheet(crate::perf::FullReason::ViewportBasis, &format!(
2737 "viewport basis is now {width}x{height}px — recompiling the stylesheet (it uses vh/vw units)"
2738 ));
2739 return;
2740 }
2741 crate::log::record("dev", format!(
2742 "[css] viewport basis is now {width}x{height}px — re-resolved the stylesheet's vh/vw rules ({:.1} ms)",
2743 took.elapsed().as_secs_f32() * 1000.0
2744 ));
2745 crate::perf::note_full(crate::perf::FullReason::ViewportBasis);
2746 with_tree(|t| t.mark_dirty());
2747}
2748
2749const REM_BASIS_PASSES: usize = 3;
2752
2753const ROOT_PARENT_FONT_SIZE: f32 = 16.0;
2754
2755#[derive(Clone, Debug, PartialEq)]
2756struct Inherited {
2757 color: Option<gpui::Hsla>,
2758 font_size: f32,
2759 font: gpui::Font,
2760}
2761
2762#[derive(Clone, Copy)]
2763pub struct NodeRef<'t> {
2764 pub tree: &'t Tree,
2765 pub id: u32,
2766}
2767
2768impl<'t> NodeRef<'t> {
2769 fn node(&self) -> &'t Node {
2770 self.tree
2771 .node(self.id)
2772 .expect("NodeRef points at a live node")
2773 }
2774
2775 fn element_sibling(&self, forward: bool) -> Option<NodeRef<'t>> {
2776 let parent = self.node().parent;
2777 if parent == 0 {
2778 return None;
2779 }
2780 let siblings = &self.tree.node(parent)?.children;
2781 let pos = siblings.iter().position(|&c| c == self.id)?;
2782 let range: Box<dyn Iterator<Item = u32>> = if forward {
2783 Box::new(siblings[pos + 1..].iter().copied())
2784 } else {
2785 Box::new(siblings[..pos].iter().rev().copied())
2786 };
2787 for id in range {
2788 if self.tree.node(id).is_some_and(|n| n.kind == Kind::Element) {
2789 return Some(NodeRef {
2790 tree: self.tree,
2791 id,
2792 });
2793 }
2794 }
2795 None
2796 }
2797
2798 fn note_sibling_question(&self, edge: u8, walk: u8) {
2799 let subject = CASCADE_SUBJECT.with(Cell::get);
2800 if subject == 0 {
2801 return;
2802 }
2803 let parent = self.node().parent;
2804 if let Some(p) = self.tree.node(parent) {
2805 let flag = if self.id == subject { edge } else { walk };
2806 p.sel_flags.set(p.sel_flags.get() | flag);
2807 }
2808 if self.id != subject {
2809 if let Some(s) = self.tree.node(subject) {
2810 if s.parent != parent {
2811 note_name_read(self.id, subject, s.tag, POSITION, NameKind::Position);
2812 }
2813 }
2814 }
2815 }
2816
2817 fn note_read(&self, name: &str, kind: NameKind) {
2818 let subject = CASCADE_SUBJECT.with(Cell::get);
2819 if subject == 0 || subject == self.id {
2820 return;
2821 }
2822 let tag = self.tree.node(subject).map_or(0, |n| n.tag);
2823 note_name_read(self.id, subject, tag, name, kind);
2824 }
2825
2826 fn note_content_question(&self, flag: u8) {
2832 let subject = CASCADE_SUBJECT.with(Cell::get);
2833 if subject == 0 {
2834 return;
2835 }
2836 let flag = match flag {
2837 sel::HAS if self.id == subject => sel::HAS_SELF,
2838 sel::HAS => sel::HAS_DESC,
2839 other => other,
2840 };
2841 let n = self.node();
2842 n.sel_flags.set(n.sel_flags.get() | flag);
2843 if flag & sel::HAS != 0 {
2844 self.tree.has_anchors.set(true);
2845 }
2846 }
2847}
2848
2849impl<'t> sk_css::MatchDom for NodeRef<'t> {
2850 fn key(&self) -> u64 {
2851 self.id as u64
2852 }
2853 fn parent(&self) -> Option<Self> {
2854 let p = self.node().parent;
2855 (p != 0).then(|| NodeRef {
2856 tree: self.tree,
2857 id: p,
2858 })
2859 }
2860 fn prev_sibling(&self) -> Option<Self> {
2861 self.note_sibling_question(sel::PREV_EDGE, sel::PREV_WALK);
2862 self.element_sibling(false)
2863 }
2864 fn next_sibling(&self) -> Option<Self> {
2865 self.note_sibling_question(sel::NEXT_EDGE, sel::NEXT_WALK);
2866 self.element_sibling(true)
2867 }
2868 fn note_following_sibling_anchor(&self) {
2871 if CASCADE_SUBJECT.with(Cell::get) == 0 {
2872 return;
2873 }
2874 self.note_content_question(sel::HAS);
2875 if let Some(p) = self.tree.node(self.node().parent) {
2876 p.sel_flags.set(p.sel_flags.get() | sel::HAS_NEXT);
2877 }
2878 }
2879 fn each_child(&self, f: &mut dyn FnMut(Self)) {
2880 fn walk<'t>(tree: &'t Tree, id: u32, f: &mut dyn FnMut(NodeRef<'t>)) {
2881 let Some(node) = tree.node(id) else { return };
2882 for &child in &node.children {
2883 match tree.node(child).map(|n| n.kind) {
2884 Some(Kind::Element) => f(NodeRef { tree, id: child }),
2885 Some(_) => walk(tree, child, f),
2886 None => {}
2887 }
2888 }
2889 }
2890 struct Restore(u32);
2891 impl Drop for Restore {
2892 fn drop(&mut self) {
2893 HAS_DEPTH.with(|d| d.set(self.0));
2894 }
2895 }
2896 let depth = HAS_DEPTH.with(|d| d.replace(d.get() + 1));
2897 let _restore = Restore(depth);
2898 if depth == 0 {
2899 self.note_content_question(sel::HAS);
2900 }
2901 walk(self.tree, self.id, f);
2902 }
2903 fn has_tag(&self, name: &str) -> bool {
2904 self.tree.name(self.node().tag) == name
2907 }
2908 fn tag_eq(&self, other: &Self) -> bool {
2909 self.node().tag == other.node().tag
2910 }
2911 fn has_class(&self, name: &str) -> bool {
2912 self.note_read(name, NameKind::Class);
2913 self.node().classes.iter().any(|c| c == name)
2914 }
2915 fn tag_name(&self) -> &str {
2916 self.tree.name(self.node().tag)
2917 }
2918 fn each_class(&self, f: &mut dyn FnMut(&str)) {
2919 for c in &self.node().classes {
2920 f(c);
2921 }
2922 }
2923 fn has_scope(&self, name: &str) -> bool {
2924 self.note_read(name, NameKind::Scope);
2925 self.node().scopes.iter().any(|s| s == name)
2926 }
2927 fn attr(&self, name: &str) -> Option<&str> {
2929 self.note_read(name, NameKind::Attr);
2930 if name == "class" {
2932 let raw = self.node().class_attr.as_str();
2933 return (!raw.is_empty()).then_some(raw);
2934 }
2935 let key = *self.tree.name_ids.get(name)?;
2936 self.node()
2937 .props
2938 .iter()
2939 .find(|(k, _, _)| *k == key)
2940 .map(|(_, v, _)| v.as_str())
2941 }
2942 fn is_empty(&self) -> bool {
2947 self.note_content_question(sel::EMPTY);
2948 self.tree.is_bare(self.id)
2949 }
2950 fn is_root(&self) -> bool {
2951 self.node().parent == 0
2952 }
2953}
2954
2955#[cfg(test)]
2956mod tests {
2957 use super::*;
2958
2959 #[test]
2960 fn a_mutation_bumps_the_subtree_revision_of_every_ancestor_and_of_nothing_else() {
2961 let (root, left, leaf, right) = with_tree(|t| {
2962 let root = t.create_root();
2963 let div = t.intern("div");
2964 let left = t.create_element(div);
2965 let leaf = t.create_element(div);
2966 let right = t.create_element(div);
2967 t.insert(left, root, 0);
2968 t.insert(leaf, left, 0);
2969 t.insert(right, root, 0);
2970 (root, left, leaf, right)
2971 });
2972 let before = read_tree(|t| {
2973 (
2974 t.sub_rev(root),
2975 t.sub_rev(left),
2976 t.sub_rev(leaf),
2977 t.sub_rev(right),
2978 )
2979 });
2980
2981 with_tree(|t| t.set_class(leaf, "hot"));
2982
2983 let after = read_tree(|t| {
2984 (
2985 t.sub_rev(root),
2986 t.sub_rev(left),
2987 t.sub_rev(leaf),
2988 t.sub_rev(right),
2989 )
2990 });
2991 assert!(after.0 > before.0, "the root is an ancestor of the change");
2992 assert!(after.1 > before.1, "so is the parent");
2993 assert!(after.2 > before.2, "and the node itself");
2994 assert_eq!(after.3, before.3, "the sibling subtree did not move");
2995 }
2996
2997 #[test]
2998 fn removing_a_child_bumps_the_parent() {
2999 let (parent, child) = with_tree(|t| {
3000 let root = t.create_root();
3001 let div = t.intern("div");
3002 let parent = t.create_element(div);
3003 let child = t.create_element(div);
3004 t.insert(parent, root, 0);
3005 t.insert(child, parent, 0);
3006 (parent, child)
3007 });
3008 let before = read_tree(|t| t.sub_rev(parent));
3009 with_tree(|t| t.remove(child));
3010 assert!(read_tree(|t| t.sub_rev(parent)) > before);
3011 }
3012
3013 #[test]
3014 fn the_cascade_touches_every_node_whose_fold_moved() {
3015 set_stylesheet(".on .leaf { opacity: 0.5 }".into());
3016 let (wrap, leaf, bystander) = with_tree(|t| {
3017 let root = t.create_root();
3018 let div = t.intern("div");
3019 let wrap = t.create_element(div);
3020 let leaf = t.create_element(div);
3021 let bystander = t.create_element(div);
3022 t.set_class(leaf, "leaf");
3023 t.insert(wrap, root, 0);
3024 t.insert(leaf, wrap, 0);
3025 t.insert(bystander, root, 0);
3026 (wrap, leaf, bystander)
3027 });
3028 restyle_all();
3029 let before = read_tree(|t| (t.sub_rev(leaf), t.sub_rev(bystander)));
3030
3031 with_tree(|t| t.set_class(wrap, "on"));
3032 restyle_all();
3033
3034 let after = read_tree(|t| (t.sub_rev(leaf), t.sub_rev(bystander)));
3035 assert_eq!(
3036 read_tree(|t| t
3037 .node(leaf)
3038 .and_then(|n| n.computed.as_ref())
3039 .and_then(|c| c.base.opacity)),
3040 Some(0.5),
3041 "the descendant combinator reached the leaf",
3042 );
3043 assert!(
3044 after.0 > before.0,
3045 "…so the leaf's subtree revision moved with it"
3046 );
3047 assert_eq!(after.1, before.1, "the bystander's fold did not move");
3048 }
3049
3050 #[test]
3054 fn a_runtime_style_element_reaches_the_cascade_and_recompiles_when_its_text_moves() {
3055 let opacity = |id: u32| {
3056 read_tree(|t| {
3057 t.node(id)
3058 .and_then(|n| n.computed.as_ref())
3059 .and_then(|c| c.base.opacity)
3060 })
3061 };
3062
3063 set_stylesheet(".probe { opacity: 0.25 }".into());
3064 let (probe, sheet) = with_tree(|t| {
3065 let root = t.create_root();
3066 let div = t.intern("div");
3067 let probe = t.create_element(div);
3068 t.set_class(probe, "probe");
3069 t.insert(probe, root, 0);
3070 let style_tag = t.intern("style");
3071 let sheet = t.create_element(style_tag);
3072 t.insert(sheet, root, 1);
3073 (probe, sheet)
3074 });
3075 restyle_all();
3076 assert_eq!(
3077 opacity(probe),
3078 Some(0.25),
3079 "the build's sheet, with an empty <style>"
3080 );
3081
3082 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.5 }".into()));
3084 restyle_all();
3085 assert_eq!(
3086 opacity(probe),
3087 Some(0.5),
3088 "a runtime <style> installs its rules"
3089 );
3090
3091 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.75 }".into()));
3092 restyle_all();
3093 assert_eq!(opacity(probe), Some(0.75), "changed text re-installs");
3094
3095 restyle_all();
3096 assert_eq!(
3097 opacity(probe),
3098 Some(0.75),
3099 "an unchanged sheet is not recompiled away"
3100 );
3101
3102 with_tree(|t| t.set_element_text(sheet, String::new()));
3103 restyle_all();
3104 assert_eq!(
3105 opacity(probe),
3106 Some(0.25),
3107 "removing the rules restores the build's sheet"
3108 );
3109 }
3110
3111 #[test]
3112 fn runtime_sheets_are_in_document_order() {
3113 set_stylesheet(String::new());
3114 with_tree(|t| {
3115 let root = t.create_root();
3116 let style = t.intern("style");
3117 let older = t.create_element(style);
3118 t.set_element_text(older, ".a { opacity: 0.5 }".into());
3119 t.insert(older, root, 0);
3120 let newer = t.create_element(style);
3121 t.set_element_text(newer, ".b { opacity: 0.5 }".into());
3122 t.insert(newer, root, older);
3123 });
3124 restyle_all();
3125 let sheets = RUNTIME_CSS.with(|r| r.borrow().clone());
3126 assert_eq!(
3127 sheets,
3128 vec![
3129 ".b { opacity: 0.5 }".to_string(),
3130 ".a { opacity: 0.5 }".to_string()
3131 ]
3132 );
3133 }
3134
3135 fn runtime_sheet_probe() -> (u32, u32, u32, u32) {
3136 set_stylesheet(".probe { opacity: 0.25 }".into());
3137 with_tree(|t| {
3138 let root = t.create_root();
3139 let div = t.intern("div");
3140 let probe = t.create_element(div);
3141 t.set_class(probe, "probe");
3142 t.insert(probe, root, 0);
3143 let detached = t.create_anchor();
3144 let style = t.intern("style");
3145 let sheet = t.create_element(style);
3146 t.set_element_text(sheet, ".probe { opacity: 0.75 }".into());
3147 t.insert(sheet, detached, 0);
3148 (root, probe, detached, sheet)
3149 })
3150 }
3151
3152 fn runtime_sheet_opacity(node: u32) -> Option<f32> {
3153 read_tree(|t| {
3154 t.node(node)
3155 .unwrap()
3156 .computed
3157 .as_ref()
3158 .unwrap()
3159 .base
3160 .opacity
3161 })
3162 }
3163
3164 #[test]
3165 fn detached_fragment_styles_are_inert_until_connected_and_stop_on_detach() {
3166 let (root, probe, fragment, sheet) = runtime_sheet_probe();
3167 restyle_all();
3168 assert_eq!(
3169 runtime_sheet_opacity(probe),
3170 Some(0.25),
3171 "closed Select fragments install no rules"
3172 );
3173
3174 with_tree(|t| t.insert(fragment, root, 0));
3175 restyle_all();
3176 assert_eq!(
3177 runtime_sheet_opacity(probe),
3178 Some(0.75),
3179 "connecting the fragment activates its style"
3180 );
3181
3182 with_tree(|t| {
3183 let other_fragment = t.create_anchor();
3184 t.insert(fragment, other_fragment, 0);
3185 });
3186 restyle_all();
3187 assert_eq!(
3188 runtime_sheet_opacity(probe),
3189 Some(0.25),
3190 "detaching removes its rules without freeing the style"
3191 );
3192
3193 with_tree(|t| t.set_element_text(sheet, ".probe { opacity: 0.9 }".into()));
3194 restyle_all();
3195 assert_eq!(
3196 runtime_sheet_opacity(probe),
3197 Some(0.25),
3198 "editing detached CSS remains inert"
3199 );
3200 }
3201
3202 #[test]
3203 fn runtime_styles_in_a_painted_secondary_root_remain_connected() {
3204 let (_, probe, secondary_root, _) = runtime_sheet_probe();
3205 restyle_all();
3206 assert_eq!(runtime_sheet_opacity(probe), Some(0.25));
3207
3208 crate::windows::set_painted_root(9001, secondary_root);
3209 restyle_all();
3210 assert_eq!(
3211 runtime_sheet_opacity(probe),
3212 Some(0.75),
3213 "SkWindow styles share the live document cascade"
3214 );
3215
3216 crate::windows::set_painted_root(9001, 0);
3217 restyle_all();
3218 assert_eq!(
3219 runtime_sheet_opacity(probe),
3220 Some(0.25),
3221 "unpainting a detached root deactivates its style"
3222 );
3223 crate::windows::forget(9001);
3224 }
3225
3226 #[test]
3227 fn empty_ignores_vue_anchors_and_empty_text() {
3228 let opacity = |id: u32| {
3229 read_tree(|t| {
3230 t.node(id)
3231 .and_then(|n| n.computed.as_ref())
3232 .and_then(|c| c.base.opacity)
3233 })
3234 };
3235 set_stylesheet(".box:empty { opacity: 0.5 }".into());
3236 let (bare, anchored, texted, text) = with_tree(|t| {
3237 let root = t.create_root();
3238 let div = t.intern("div");
3239 let mut boxed = || {
3240 let b = t.create_element(div);
3241 t.set_class(b, "box");
3242 t.insert(b, root, 0);
3243 b
3244 };
3245 let (bare, anchored, texted) = (boxed(), boxed(), boxed());
3246 for _ in 0..2 {
3247 let a = t.create_anchor();
3248 t.insert(a, anchored, 0);
3249 }
3250 let start = t.create_text();
3251 t.insert(start, anchored, 0);
3252 let text = t.create_text();
3253 t.insert(text, texted, 0);
3254 (bare, anchored, texted, text)
3255 });
3256 restyle_all();
3257 assert_eq!(opacity(bare), Some(0.5), "no children");
3258 assert_eq!(
3259 opacity(anchored),
3260 Some(0.5),
3261 "anchors and an empty text node only"
3262 );
3263 assert_eq!(opacity(texted), Some(0.5), "a text node with no data");
3264
3265 with_tree(|t| t.set_text(text, " ".into()));
3266 restyle_all();
3267 assert_eq!(opacity(texted), None, "text with data, whitespace included");
3268 with_tree(|t| t.set_text(text, String::new()));
3269 restyle_all();
3270 assert_eq!(opacity(texted), Some(0.5), "and empty again");
3271
3272 with_tree(|t| {
3273 let span = t.intern("span");
3274 let child = t.create_element(span);
3275 t.insert(child, anchored, 0);
3276 });
3277 restyle_all();
3278 assert_eq!(opacity(anchored), None, "an element child");
3279 }
3280
3281 #[test]
3282 fn a_viewport_unit_is_a_dimension_token_not_a_substring() {
3283 for yes in [
3284 "100vw",
3285 "100svh",
3286 "calc(100vh - 2rem)",
3287 "-5vh",
3288 "-.5vmin",
3289 "85DVH",
3290 "min(50vw, 40rem)",
3291 "1.5lvmax",
3292 ] {
3293 assert!(has_viewport_unit(yes), "{yes:?}");
3294 }
3295 for no in [
3296 "10px",
3297 "var(--x9vw)",
3298 "abc12vh",
3299 "2rem",
3300 "",
3301 "50%",
3302 "url(a1vw.png)",
3303 "100v",
3304 "3vws",
3305 ] {
3306 assert!(!has_viewport_unit(no), "{no:?}");
3307 }
3308 }
3309
3310 #[test]
3311 fn inline_viewport_units_and_var_composed_ones_follow_the_viewport() {
3312 fn px(l: Option<gpui::Length>) -> Option<f32> {
3313 match l? {
3314 gpui::Length::Definite(gpui::DefiniteLength::Absolute(
3315 gpui::AbsoluteLength::Pixels(p),
3316 )) => Some(f32::from(p)),
3317 _ => None,
3318 }
3319 }
3320 let size = |id: u32| {
3321 read_tree(|t| {
3322 let cs = t.node(id)?.computed.as_ref()?;
3323 Some((px(cs.base.size.width), px(cs.base.size.height)))
3324 })
3325 };
3326 let resize = |w: f32, h: f32| {
3327 if set_env(sk_css::Env {
3328 viewport_width: w,
3329 viewport_height: h,
3330 ..sk_css::Env::default()
3331 }) {
3332 with_tree(|t| t.mark_dirty());
3333 }
3334 restyle_all();
3335 };
3336 resize(1652.0, 633.0);
3337 let (shell, child, plain) = with_tree(|t| {
3338 let root = t.create_root();
3339 let div = t.intern("div");
3340 let (width, height, var) = (t.intern("width"), t.intern("height"), t.intern("--w"));
3341 let shell = t.create_element(div);
3342 t.insert(shell, root, 0);
3343 t.set_style(shell, width, "100svw".into());
3344 t.set_style(shell, height, "100svh".into());
3345 let parent = t.create_element(div);
3346 t.insert(parent, root, 1);
3347 t.set_style(parent, var, "50vw".into());
3348 let child = t.create_element(div);
3349 t.insert(child, parent, 0);
3350 t.set_style(child, width, "var(--w)".into());
3351 let plain = t.create_element(div);
3352 t.insert(plain, root, 2);
3353 t.set_style(plain, width, "40px".into());
3354 (shell, child, plain)
3355 });
3356 restyle_all();
3357 assert_eq!(size(shell), Some((Some(1652.0), Some(633.0))));
3358 assert_eq!(size(child).and_then(|s| s.0), Some(826.0));
3359
3360 resize(1700.0, 800.0);
3361 assert_eq!(
3362 size(shell),
3363 Some((Some(1700.0), Some(800.0))),
3364 "the inline svw/svh re-resolved"
3365 );
3366 assert_eq!(
3367 size(child).and_then(|s| s.0),
3368 Some(850.0),
3369 "and the var()-composed vw with it"
3370 );
3371 assert_eq!(size(plain).and_then(|s| s.0), Some(40.0));
3372
3373 assert!(sk_css::set_viewport_basis(1000.0, 500.0));
3375 let marked = with_tree(|t| t.invalidate_viewport_inline());
3376 assert_eq!(
3377 marked, 2,
3378 "the shell and the --w parent; never the px-only node"
3379 );
3380 ENGINE.with(|eng| with_tree(|t| t.restyle(eng.borrow().as_ref(), &env())));
3381 assert_eq!(size(shell), Some((Some(1000.0), Some(500.0))));
3382 assert_eq!(size(child).and_then(|s| s.0), Some(500.0));
3383 }
3384
3385 #[test]
3386 fn sheet_viewport_units_follow_the_viewport() {
3387 let width = |id: u32| {
3388 read_tree(|t| match t.node(id)?.computed.as_ref()?.base.size.width? {
3389 gpui::Length::Definite(gpui::DefiniteLength::Absolute(
3390 gpui::AbsoluteLength::Pixels(p),
3391 )) => Some(f32::from(p)),
3392 _ => None,
3393 })
3394 };
3395 let resize = |w: f32, h: f32| {
3396 if set_env(sk_css::Env {
3397 viewport_width: w,
3398 viewport_height: h,
3399 ..sk_css::Env::default()
3400 }) {
3401 with_tree(|t| t.mark_dirty());
3402 }
3403 restyle_all();
3404 };
3405 resize(1000.0, 800.0);
3406 assert!(set_stylesheet_with_head(
3407 ".box, .wide { width: 50vw } .wide { min-height: 10vh }".into(),
3408 vec![]
3409 ));
3410 let (bx, wide) = with_tree(|t| {
3411 let root = t.create_root();
3412 let div = t.intern("div");
3413 let bx = t.create_element(div);
3414 t.insert(bx, root, 0);
3415 t.set_class(bx, "box");
3416 let wide = t.create_element(div);
3417 t.insert(wide, root, 1);
3418 t.set_class(wide, "wide");
3419 t.mark_dirty();
3420 (bx, wide)
3421 });
3422 restyle_all();
3423 assert_eq!((width(bx), width(wide)), (Some(500.0), Some(500.0)));
3424 resize(1200.0, 800.0);
3425 assert_eq!(
3426 (width(bx), width(wide)),
3427 (Some(600.0), Some(600.0)),
3428 "rebased"
3429 );
3430
3431 assert!(set_stylesheet_with_head(
3432 ".box, .wide { width: 50vw } @keyframes k { from { height: 10vh } }".into(),
3433 vec![]
3434 ));
3435 with_tree(|t| t.mark_dirty());
3436 restyle_all();
3437 resize(800.0, 800.0);
3438 assert_eq!(
3439 (width(bx), width(wide)),
3440 (Some(400.0), Some(400.0)),
3441 "recompiled"
3442 );
3443 sk_css::set_viewport_basis(
3444 sk_css::INITIAL_VIEWPORT_BASIS.0,
3445 sk_css::INITIAL_VIEWPORT_BASIS.1,
3446 );
3447 }
3448
3449 #[test]
3450 fn an_unchanged_sheet_resent_compiles_nothing() {
3451 assert!(set_stylesheet_with_head(
3452 ".a { opacity: 0.5 }".into(),
3453 vec![".b {}".into()]
3454 ));
3455 assert!(!set_stylesheet_with_head(
3456 ".a { opacity: 0.5 }".into(),
3457 vec![".b {}".into()]
3458 ));
3459 assert!(set_stylesheet_with_head(
3460 ".a { opacity: 0.5 }".into(),
3461 vec![".b {}".into(), ".c {}".into()]
3462 ));
3463 assert!(set_stylesheet_with_head(
3464 ".a { opacity: 0.6 }".into(),
3465 vec![".b {}".into(), ".c {}".into()]
3466 ));
3467 assert_eq!(
3468 sheet_sources(),
3469 vec![
3470 ".a { opacity: 0.6 }".to_string(),
3471 ".b {}".into(),
3472 ".c {}".into()
3473 ],
3474 "the build's sheet, then each head text on its own"
3475 );
3476 }
3477
3478 fn flush_motion_styles() {
3479 with_tree(|t| t.mark_dirty());
3480 restyle_all();
3481 }
3482
3483 fn motion_probe(sheet: &str) -> (u32, std::time::Instant) {
3484 set_stylesheet(sheet.into());
3485 let node = with_tree(|t| {
3486 let root = t.create_root();
3487 let div = t.intern("div");
3488 let node = t.create_element(div);
3489 t.set_class(node, "motion");
3490 t.insert(node, root, 0);
3491 node
3492 });
3493 flush_motion_styles();
3494 let start = std::time::Instant::now();
3495 ANIMATOR.with(|a| a.borrow_mut().tick(start));
3496 let _ = take_anim_events();
3497 (node, start)
3498 }
3499
3500 fn motion_opacity_at(node: u32, at: std::time::Instant) -> Option<f32> {
3501 let base = read_tree(|t| {
3502 t.node(node)
3503 .unwrap()
3504 .computed
3505 .as_ref()
3506 .unwrap()
3507 .base
3508 .clone()
3509 });
3510 animation_overlay(node, &base, at).and_then(|style| style.opacity)
3511 }
3512
3513 #[test]
3514 fn late_stylesheet_and_font_recompile_preserve_a_running_animation_clock() {
3515 let sheet = "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3516 .motion { animation: enter 500ms linear }";
3517 let (node, start) = motion_probe(sheet);
3518 let at = start + std::time::Duration::from_millis(200);
3519 assert!((motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5);
3520
3521 assert!(set_stylesheet_with_head(
3522 sheet.into(),
3523 vec![".late-panel { color: red }".into()]
3524 ));
3525 flush_motion_styles();
3526 assert!(
3527 (motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5,
3528 "unrelated CSS must retain the elapsed clock, not drop/restart the run"
3529 );
3530
3531 recompile_for_fonts();
3532 flush_motion_styles();
3533 assert!(
3534 (motion_opacity_at(node, at).unwrap() - 0.4).abs() < 1e-5,
3535 "registering a font must not erase the running animation"
3536 );
3537 }
3538
3539 #[test]
3540 fn changed_keyframes_rebind_at_the_existing_clock_and_deleted_keyframes_cancel() {
3541 let sheet = "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3542 .motion { animation: enter 500ms linear }";
3543 let (node, start) = motion_probe(sheet);
3544 let at = start + std::time::Duration::from_millis(200);
3545 set_stylesheet(sheet.replace("opacity: 1", "opacity: 0.5"));
3546 flush_motion_styles();
3547 assert!(
3548 (motion_opacity_at(node, at).unwrap() - 0.2).abs() < 1e-5,
3549 "same-name definition changes sample new frames on the existing timeline"
3550 );
3551
3552 set_stylesheet(".motion { animation: enter 500ms linear }".into());
3553 flush_motion_styles();
3554 assert!(
3555 motion_opacity_at(node, at).is_none(),
3556 "deleted frames must not keep painting"
3557 );
3558 let events = take_anim_events();
3559 assert_eq!(
3560 events
3561 .iter()
3562 .filter(|event| event.node == node
3563 && event.kind == sk_css::AnimEventKind::AnimationCancel)
3564 .count(),
3565 1
3566 );
3567 }
3568
3569 #[test]
3570 fn removing_the_animation_and_last_keyframes_cancels_the_old_run() {
3571 let (node, start) = motion_probe(
3572 "@keyframes enter { from { opacity: 0 } to { opacity: 1 } } \
3573 .motion { animation: enter 500ms linear }",
3574 );
3575 set_stylesheet(".motion { opacity: 1 }".into());
3576 flush_motion_styles();
3577 assert!(motion_opacity_at(node, start).is_none());
3578 assert!(take_anim_events().iter().any(
3579 |event| event.node == node && event.kind == sk_css::AnimEventKind::AnimationCancel
3580 ));
3581 }
3582
3583 #[test]
3584 fn unrelated_stylesheet_preserves_a_running_transition_clock() {
3585 let sheet = ".motion { opacity: 0; transition: opacity 500ms linear } \
3586 .motion.open { opacity: 1 }";
3587 let (node, _) = motion_probe(sheet);
3588 with_tree(|t| t.set_class(node, "motion open"));
3589 flush_motion_styles();
3590 let start = std::time::Instant::now();
3591 let at = start + std::time::Duration::from_millis(200);
3592 let before = motion_opacity_at(node, at).unwrap();
3593 assert!(before > 0.39 && before < 0.42, "{before}");
3594 assert!(set_stylesheet_with_head(
3595 sheet.into(),
3596 vec![".late-panel { color: red }".into()]
3597 ));
3598 flush_motion_styles();
3599 assert!(
3600 (motion_opacity_at(node, at).unwrap() - before).abs() < 1e-5,
3601 "a late sheet must not snap or restart an unrelated transition"
3602 );
3603 }
3604
3605 #[test]
3608 fn a_rem_recompile_at_boot_starts_no_transition() {
3609 set_stylesheet(".card { padding: 1.5rem; transition: all 300ms }".into());
3610 let card = with_tree(|t| {
3611 let root = t.create_root();
3612 let font_size = t.intern("font-size");
3615 t.set_style(root, font_size, "14px".into());
3616 let div = t.intern("div");
3617 let card = t.create_element(div);
3618 t.set_class(card, "card");
3619 t.insert(card, root, 0);
3620 card
3621 });
3622
3623 let probed = ENGINE.with(|eng| {
3624 let eng = eng.borrow();
3625 read_tree(|t| t.probe_root_font_size(eng.as_ref(), &env()))
3626 });
3627 assert_eq!(
3628 probed,
3629 Some(14.0),
3630 "the root's own inline font-size, without a cascade"
3631 );
3632 assert!(
3633 read_tree(|t| t.node(t.root).is_some_and(|n| n.computed.is_none())),
3634 "probing the basis must not commit a computed style"
3635 );
3636
3637 restyle_all();
3638 assert_eq!(
3639 sk_css::rem_basis(),
3640 14.0,
3641 "the sheet was recompiled against the root"
3642 );
3643
3644 let padding = read_tree(|t| {
3645 t.node(card)
3646 .and_then(|n| n.computed.as_ref())
3647 .and_then(|c| c.base.padding.top)
3648 });
3649 assert_eq!(
3650 padding,
3651 Some(gpui::DefiniteLength::Absolute(
3652 gpui::AbsoluteLength::Pixels(gpui::px(21.0))
3653 )),
3654 "the ONE committed cascade ran under the settled basis"
3655 );
3656
3657 let base = read_tree(|t| {
3658 t.node(card)
3659 .and_then(|n| n.computed.as_ref())
3660 .map(|c| c.base.clone())
3661 })
3662 .expect("the card is cascaded");
3663 assert!(
3664 animation_overlay(card, &base, std::time::Instant::now()).is_none(),
3665 "a basis recompile is not a style change, so no transition runs across it"
3666 );
3667 }
3668
3669 #[test]
3670 fn several_style_elements_concatenate_in_document_order() {
3671 let opacity = |id: u32| {
3672 read_tree(|t| {
3673 t.node(id)
3674 .and_then(|n| n.computed.as_ref())
3675 .and_then(|c| c.base.opacity)
3676 })
3677 };
3678 set_stylesheet(String::new());
3679 let probe = with_tree(|t| {
3680 let root = t.create_root();
3681 let div = t.intern("div");
3682 let probe = t.create_element(div);
3683 t.set_class(probe, "probe");
3684 t.insert(probe, root, 0);
3685 let style_tag = t.intern("style");
3686 for css in [".probe { opacity: 0.1 }", ".probe { opacity: 0.9 }"] {
3687 let sheet = t.create_element(style_tag);
3688 t.set_element_text(sheet, css.into());
3689 t.insert(sheet, root, 0);
3690 }
3691 probe
3692 });
3693 restyle_all();
3694 assert_eq!(
3695 opacity(probe),
3696 Some(0.9),
3697 "the later sheet wins at equal specificity"
3698 );
3699 }
3700
3701 fn cascaded_comb(n: usize) -> (u32, Vec<u32>, Vec<u32>) {
3702 let ids = with_tree(|t| {
3703 let root = t.create_root();
3704 let div = t.intern("div");
3705 let mut kids = Vec::new();
3706 let mut grandkids = Vec::new();
3707 for _ in 0..n {
3708 let kid = t.create_element(div);
3709 let grandkid = t.create_element(div);
3710 t.insert(grandkid, kid, 0);
3711 t.insert(kid, root, 0);
3712 kids.push(kid);
3713 grandkids.push(grandkid);
3714 }
3715 (root, kids, grandkids)
3716 });
3717 restyle_all();
3718 ids
3719 }
3720
3721 fn roots_of() -> Vec<u32> {
3722 let mut roots = with_tree(|t| t.restyle_roots());
3723 roots.sort_unstable();
3724 roots
3725 }
3726
3727 #[test]
3728 fn hundreds_of_separate_marks_stay_a_scoped_pass() {
3729 let (_, _, grandkids) = cascaded_comb(300);
3730 with_tree(|t| {
3731 for &g in &grandkids {
3732 t.mark_restyle_subtree(g);
3733 }
3734 });
3735 let mut want = grandkids.clone();
3736 want.sort_unstable();
3737 assert_eq!(roots_of(), want);
3738 assert!(roots_of().is_empty());
3739 }
3740
3741 #[test]
3742 fn a_mark_under_a_marked_ancestor_is_not_walked_twice() {
3743 let (_, kids, grandkids) = cascaded_comb(3);
3744 with_tree(|t| {
3745 t.mark_restyle_subtree(grandkids[1]);
3746 t.mark_restyle_subtree(kids[1]);
3747 });
3748 assert_eq!(roots_of(), vec![kids[1]]);
3749 }
3750
3751 #[test]
3752 fn marks_in_a_parentless_container_are_found_and_follow_a_move() {
3753 let (_, kids, _) = cascaded_comb(2);
3754 let (cache, kept) = with_tree(|t| {
3755 let div = t.intern("div");
3756 let cache = t.create_element(div);
3757 let kept = t.create_element(div);
3758 t.insert(kept, cache, 0);
3759 (cache, kept)
3760 });
3761 restyle_all();
3762 with_tree(|t| t.mark_restyle_subtree(kept));
3763 assert_eq!(roots_of(), vec![kept]);
3764
3765 with_tree(|t| {
3766 t.mark_restyle_subtree(kept);
3767 t.insert(kept, kids[0], 0);
3768 });
3769 assert_eq!(roots_of(), vec![kept]);
3770 let _ = cache;
3771 }
3772
3773 #[test]
3774 fn an_append_walks_the_new_child_and_not_its_siblings() {
3775 let (root, kids, _) = cascaded_comb(50);
3776 let added = with_tree(|t| {
3777 let div = t.intern("div");
3778 let added = t.create_element(div);
3779 t.insert(added, root, 0);
3780 added
3781 });
3782 assert_eq!(roots_of(), vec![added]);
3783 let _ = kids;
3784 }
3785
3786 #[test]
3789 fn a_root_has_anchor_is_rechecked_not_walked() {
3790 let sheet = "body:has([data-x]) { opacity: 0.5 }";
3791 set_engine(sk_css::Engine::compile(sheet));
3792 let (root, _, grandkids) = cascaded_comb(3);
3793 assert!(
3794 read_tree(|t| t.node(root).unwrap().sel_flags.get() & sel::HAS_SELF != 0),
3795 "the root asked `:has()` of itself"
3796 );
3797 let engine = sk_css::Engine::compile(sheet);
3798 let env = env();
3799
3800 let settled_ids = |engine: &sk_css::Engine| {
3801 with_tree(|t| t.settle_self_marks(engine, &env))
3802 .into_iter()
3803 .map(|(id, _)| id)
3804 .collect::<Vec<_>>()
3805 };
3806
3807 with_tree(|t| t.set_class(grandkids[1], "x"));
3808 assert!(settled_ids(&engine).is_empty());
3809 assert!(roots_of().is_empty(), "no walk at all");
3810
3811 let x = with_tree(|t| t.intern("data-x"));
3812 with_tree(|t| t.set_prop(grandkids[0], x, Some(String::new())));
3813 assert_eq!(settled_ids(&engine), vec![root]);
3814 assert!(roots_of().is_empty(), "no walk at all");
3815 }
3816
3817 #[test]
3818 fn a_following_sibling_has_anchor_is_rechecked_when_that_sibling_changes() {
3819 let sheet = "div:has(+ [data-x]) { opacity: 0.5 }";
3820 set_engine(sk_css::Engine::compile(sheet));
3821 let (root, kids, _) = cascaded_comb(2);
3822 assert!(
3823 read_tree(|t| t.node(root).unwrap().sel_flags.get() & sel::HAS_NEXT != 0),
3824 "a child asked `:has(+ …)`"
3825 );
3826 let engine = sk_css::Engine::compile(sheet);
3827 let env = env();
3828 let x = with_tree(|t| t.intern("data-x"));
3829 with_tree(|t| t.set_prop(kids[1], x, Some(String::new())));
3830 let settled: Vec<u32> = with_tree(|t| t.settle_self_marks(&engine, &env))
3831 .into_iter()
3832 .map(|(id, _)| id)
3833 .collect();
3834 assert!(
3835 settled.contains(&kids[0]),
3836 "the earlier sibling's answer moved: {settled:?}"
3837 );
3838 }
3839
3840 #[test]
3841 fn a_text_node_filling_up_rechecks_the_has_anchor_that_reads_empty() {
3842 let sheet = ".card:has(span:empty) { opacity: 0.5 }";
3843 set_engine(sk_css::Engine::compile(sheet));
3844 let (card, text) = with_tree(|t| {
3845 let root = t.create_root();
3846 let (div, span) = (t.intern("div"), t.intern("span"));
3847 let card = t.create_element(div);
3848 t.set_class(card, "card");
3849 let badge = t.create_element(span);
3850 let text = t.create_text();
3851 t.insert(text, badge, 0);
3852 t.insert(badge, card, 0);
3853 t.insert(card, root, 0);
3854 (card, text)
3855 });
3856 restyle_all();
3857 let engine = sk_css::Engine::compile(sheet);
3858 let env = env();
3859 with_tree(|t| t.set_text(text, "3".into()));
3860 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3861 let card_now = settled
3862 .iter()
3863 .find(|(id, _)| *id == card)
3864 .map(|(_, s)| s.base.opacity);
3865 assert_eq!(
3866 card_now,
3867 Some(None),
3868 "the badge has text now: {:?}",
3869 settled.iter().map(|s| s.0).collect::<Vec<_>>()
3870 );
3871 }
3872
3873 #[test]
3874 fn a_prop_set_again_after_a_removal_has_a_new_write_count() {
3875 let (id, value) = with_tree(|t| {
3876 t.create_root();
3877 let input = t.intern("input");
3878 let id = t.create_element(input);
3879 (id, t.intern("value"))
3880 });
3881 let write = |v: Option<&str>| {
3882 with_tree(|t| t.set_prop(id, value, v.map(str::to_string)));
3883 read_tree(|t| t.prop_write(id, "value").map(|(_, write)| write))
3884 };
3885 let first = write(Some("a")).unwrap();
3886 assert_ne!(
3887 write(Some("a")).unwrap(),
3888 first,
3889 "the same string again is still a write"
3890 );
3891 assert_eq!(write(None), None);
3892 assert_ne!(write(Some("a")).unwrap(), first);
3893 }
3894
3895 #[test]
3896 fn a_class_read_only_by_its_own_element_restyles_that_element_alone() {
3897 let sheet = ".hot { opacity: 0.5 } .on .leaf { opacity: 0.25 }";
3898 set_engine(sk_css::Engine::compile(sheet));
3899 let (root, kids, grandkids) = with_tree(|t| {
3900 let root = t.create_root();
3901 let div = t.intern("div");
3902 let kid = t.create_element(div);
3903 let leaf = t.create_element(div);
3904 t.set_class(leaf, "leaf");
3905 t.insert(leaf, kid, 0);
3906 t.insert(kid, root, 0);
3907 (root, vec![kid], vec![leaf])
3908 });
3909 restyle_all();
3910 let engine = sk_css::Engine::compile(sheet);
3911 let env = env();
3912
3913 with_tree(|t| t.set_class(kids[0], "hot"));
3914 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3915 assert_eq!(settled.len(), 1);
3916 assert_eq!(settled[0].0, kids[0]);
3917 assert_eq!(settled[0].1.base.opacity, Some(0.5));
3918 assert!(roots_of().is_empty(), "the subtree is not walked");
3919
3920 with_tree(|t| t.set_class(kids[0], "hot on"));
3921 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3922 assert_eq!(
3923 settled.iter().map(|s| s.0).collect::<Vec<_>>(),
3924 vec![kids[0]]
3925 );
3926 assert_eq!(roots_of(), vec![grandkids[0]]);
3927 let _ = root;
3928 }
3929
3930 #[test]
3931 fn a_moved_sibling_is_restyled_alone_with_the_elements_that_read_its_place() {
3932 let sheet = ".row:nth-child(2) { opacity: 0.5 } .row:first-child .cell { opacity: 0.25 }";
3933 set_engine(sk_css::Engine::compile(sheet));
3934 let (list, rows, cells) = with_tree(|t| {
3935 let root = t.create_root();
3936 let div = t.intern("div");
3937 let span = t.intern("span");
3938 let list = t.create_element(div);
3939 let (mut rows, mut cells) = (Vec::new(), Vec::new());
3940 for _ in 0..3 {
3941 let row = t.create_element(div);
3942 t.set_class(row, "row");
3943 let other = t.create_element(div);
3944 let cell = t.create_element(span);
3945 t.set_class(cell, "cell");
3946 t.insert(other, row, 0);
3947 t.insert(cell, row, 0);
3948 t.insert(row, list, 0);
3949 rows.push(row);
3950 cells.push(cell);
3951 }
3952 t.insert(list, root, 0);
3953 (list, rows, cells)
3954 });
3955 restyle_all();
3956 let opacity = |id: u32| {
3957 read_tree(|t| {
3958 t.node(id)
3959 .and_then(|n| n.computed.as_ref())
3960 .and_then(|c| c.base.opacity)
3961 })
3962 };
3963 assert_eq!(
3964 (opacity(rows[1]), opacity(cells[0])),
3965 (Some(0.5), Some(0.25))
3966 );
3967
3968 let engine = sk_css::Engine::compile(sheet);
3969 let env = env();
3970 let added = with_tree(|t| {
3971 let div = t.intern("div");
3972 let added = t.create_element(div);
3973 t.set_class(added, "row");
3974 t.insert(added, list, rows[0]);
3975 added
3976 });
3977 let settled = with_tree(|t| t.settle_self_marks(&engine, &env));
3978 assert_eq!(
3979 settled.iter().map(|s| s.0).collect::<Vec<_>>(),
3980 vec![rows[0], rows[1]]
3981 );
3982 let mut want = vec![added, cells[0], cells[1], cells[2]];
3983 want.sort_unstable();
3984 assert_eq!(
3985 roots_of(),
3986 want,
3987 "the new row and the cells, none of the rows' other children"
3988 );
3989
3990 with_tree(|t| t.remove(added));
3991 restyle_all();
3992 with_tree(|t| {
3993 let div = t.intern("div");
3994 let added = t.create_element(div);
3995 t.set_class(added, "row");
3996 t.insert(added, list, rows[0]);
3997 });
3998 restyle_all();
3999 assert_eq!(
4000 [rows[0], rows[1], cells[0], cells[1]].map(opacity),
4001 [Some(0.5), None, None, None],
4002 "the old first row is the second now, and no cell is under the first row"
4003 );
4004 }
4005
4006 #[test]
4007 fn a_name_read_by_a_few_tags_walks_only_those_elements() {
4008 let sheet = "[class*=\"submit\"] button { opacity: 0.5 }";
4009 set_engine(sk_css::Engine::compile(sheet));
4010 let (panel, buttons) = with_tree(|t| {
4011 let root = t.create_root();
4012 let div = t.intern("div");
4013 let button = t.intern("button");
4014 let panel = t.create_element(div);
4015 let mut buttons = Vec::new();
4016 for _ in 0..3 {
4017 let row = t.create_element(div);
4018 let b = t.create_element(button);
4019 let label = t.create_element(div);
4020 t.insert(label, b, 0);
4021 t.insert(b, row, 0);
4022 t.insert(row, panel, 0);
4023 buttons.push(b);
4024 }
4025 t.insert(panel, root, 0);
4026 (panel, buttons)
4027 });
4028 restyle_all();
4029 let opacity = |id: u32| {
4030 read_tree(|t| {
4031 t.node(id)
4032 .and_then(|n| n.computed.as_ref())
4033 .and_then(|c| c.base.opacity)
4034 })
4035 };
4036 assert_eq!(opacity(buttons[0]), None);
4037
4038 let engine = sk_css::Engine::compile(sheet);
4039 let env = env();
4040 with_tree(|t| t.set_class(panel, "submit-row"));
4041 assert!(
4042 with_tree(|t| t.settle_self_marks(&engine, &env)).is_empty(),
4043 "the panel's own style did not move"
4044 );
4045 let mut want = buttons.clone();
4046 want.sort_unstable();
4047 assert_eq!(
4048 roots_of(),
4049 want,
4050 "the buttons, and none of the divs around them"
4051 );
4052
4053 with_tree(|t| t.set_class(panel, "submit-row wide"));
4054 restyle_all();
4055 assert!(buttons.iter().all(|&b| opacity(b) == Some(0.5)));
4056 with_tree(|t| t.set_class(panel, "wide"));
4057 restyle_all();
4058 assert!(buttons.iter().all(|&b| opacity(b).is_none()));
4059 }
4060
4061 #[test]
4062 fn an_insert_marks_the_siblings_the_cascade_said_it_read() {
4063 let (root, kids, _) = cascaded_comb(5);
4064 let take_self_marks = || {
4065 with_tree(|t| {
4066 let mut marks = std::mem::take(&mut t.self_marks);
4067 marks.sort_unstable();
4068 marks.dedup();
4069 marks
4070 })
4071 };
4072 with_tree(|t| t.node(root).unwrap().sel_flags.set(sel::NEXT_EDGE));
4073 let added = with_tree(|t| {
4074 let div = t.intern("div");
4075 let added = t.create_element(div);
4076 t.insert(added, root, 0);
4077 added
4078 });
4079 assert_eq!(take_self_marks(), vec![kids[4]], "the old last child");
4080 assert_eq!(roots_of(), vec![added], "and the new one");
4081
4082 with_tree(|t| t.node(root).unwrap().sel_flags.set(sel::PREV_WALK));
4083 let middle = with_tree(|t| {
4084 let div = t.intern("div");
4085 let middle = t.create_element(div);
4086 t.insert(middle, root, kids[3]);
4087 middle
4088 });
4089 let mut want = vec![kids[3], kids[4], added];
4090 want.sort_unstable();
4091 assert_eq!(take_self_marks(), want);
4092 assert_eq!(roots_of(), vec![middle]);
4093 }
4094
4095 #[test]
4096 fn a_root_under_an_anchor_is_promoted_to_the_anchor() {
4097 let (anchor, inner) = with_tree(|t| {
4098 let root = t.create_root();
4099 let div = t.intern("div");
4100 let anchor = t.create_anchor();
4101 let a = t.create_element(div);
4102 let b = t.create_element(div);
4103 t.insert(a, anchor, 0);
4104 t.insert(b, anchor, 0);
4105 t.insert(anchor, root, 0);
4106 (anchor, b)
4107 });
4108 restyle_all();
4109 with_tree(|t| t.mark_restyle_subtree(inner));
4110 assert_eq!(roots_of(), vec![anchor]);
4111 }
4112
4113 #[test]
4114 fn a_sibling_combinator_reaches_later_siblings_where_they_read() {
4115 let sheet = ".a + .b { opacity: 0.5 }";
4116 set_engine(sk_css::Engine::compile(sheet));
4117 let (root, kids, grandkids) = cascaded_comb(5);
4118 let opacity = |id: u32| {
4119 read_tree(|t| {
4120 t.node(id)
4121 .and_then(|n| n.computed.as_ref())
4122 .and_then(|c| c.base.opacity)
4123 })
4124 };
4125 with_tree(|t| kids.iter().for_each(|&k| t.set_class(k, "b")));
4126 restyle_all();
4127 let order: Vec<u32> = read_tree(|t| t.node(root).unwrap().children.clone());
4128 let (first, second, third) = (order[0], order[1], order[2]);
4129
4130 with_tree(|t| t.set_class(first, "a b"));
4131 let mut want: Vec<u32> = order[1..].to_vec();
4132 want.push(grandkids[kids.iter().position(|&k| k == first).unwrap()]);
4133 want.sort_unstable();
4134 assert_eq!(roots_of(), want, "the divs after it, and the one under it");
4135
4136 let added = with_tree(|t| {
4137 let div = t.intern("div");
4138 let added = t.create_element(div);
4139 t.insert(added, root, third);
4140 added
4141 });
4142 assert_eq!(roots_of(), vec![added], "only the new node is walked");
4143 let mut marked = with_tree(|t| std::mem::take(&mut t.self_marks));
4144 marked.sort_unstable();
4145 marked.dedup();
4146 assert_eq!(
4147 marked,
4148 vec![first, third],
4149 "the class change, and the one whose `+` steps across"
4150 );
4151
4152 with_tree(|t| t.set_class(first, "b"));
4153 restyle_all();
4154 assert_eq!(opacity(second), None);
4155 with_tree(|t| t.set_class(first, "a b"));
4156 restyle_all();
4157 assert_eq!(opacity(second), Some(0.5), ".a + .b");
4158 with_tree(|t| t.set_class(first, "b"));
4159 restyle_all();
4160 assert_eq!(opacity(second), None);
4161 }
4162
4163 #[test]
4164 fn an_uncascaded_element_on_the_trail_is_a_walk_root() {
4165 let (_, kids, _) = cascaded_comb(2);
4166 let fresh = with_tree(|t| {
4167 let div = t.intern("div");
4168 let fresh = t.create_element(div);
4169 let inner = t.create_element(div);
4170 t.insert(inner, fresh, 0);
4171 t.node_mut(fresh).unwrap().parent = kids[0];
4174 t.node_mut(fresh).unwrap().mark_gen = 0;
4175 t.node_mut(kids[0]).unwrap().children.push(fresh);
4176 t.flag_path(kids[0]);
4177 fresh
4178 });
4179 assert_eq!(roots_of(), vec![fresh]);
4180 }
4181
4182 fn font_size_of(id: u32) -> f32 {
4183 read_tree(|t| {
4184 t.node(id)
4185 .and_then(|n| n.computed.as_ref())
4186 .map(|c| c.font_size)
4187 })
4188 .expect("cascaded")
4189 }
4190
4191 fn padding_top_of(id: u32) -> Option<gpui::DefiniteLength> {
4192 read_tree(|t| {
4193 t.node(id)
4194 .and_then(|n| n.computed.as_ref())
4195 .and_then(|c| c.base.padding.top)
4196 })
4197 }
4198
4199 fn px_len(v: f32) -> Option<gpui::DefiniteLength> {
4200 Some(gpui::px(v).into())
4201 }
4202
4203 #[test]
4206 fn a_root_font_size_in_rem_settles_on_the_initial_size() {
4207 set_stylesheet(":root { font-size: 0.875rem } .w { width: 2rem }".into());
4208 let w = with_tree(|t| {
4209 let root = t.create_root();
4210 let div = t.intern("div");
4211 let w = t.create_element(div);
4212 t.set_class(w, "w");
4213 let height = t.intern("height");
4214 t.set_style(w, height, "2rem".to_string());
4215 t.insert(w, root, 0);
4216 w
4217 });
4218 for pass in 0..4 {
4219 with_tree(|t| t.take_dirty());
4220 restyle_all();
4221 assert_eq!(sk_css::rem_basis(), 14.0, "pass {pass}");
4222 assert!(
4223 !read_tree(|t| t.dirty),
4224 "pass {pass} left a restyle pending"
4225 );
4226 let computed = read_tree(|t| {
4227 t.node(w)
4228 .and_then(|n| n.computed.as_ref())
4229 .map(|c| c.base.clone())
4230 })
4231 .expect("cascaded");
4232 let rem2 = Some(gpui::Length::Definite(gpui::px(28.0).into()));
4233 assert_eq!(computed.size.width, rem2, "the sheet's 2rem, pass {pass}");
4234 assert_eq!(computed.size.height, rem2, "the inline 2rem, pass {pass}");
4235 }
4236 }
4237
4238 #[test]
4239 fn em_follows_the_computed_font_size_down_the_walk() {
4240 set_stylesheet(
4241 ":root { font-size: 62.5% } \
4242 .a { font-size: 2em } \
4243 .b { font-size: 75%; padding: .5em } \
4244 .c { margin-top: 1em; width: 2rem; line-height: 1.5em } \
4245 .n { line-height: 1.5 }"
4246 .into(),
4247 );
4248 let (root, a, b, c, n) = with_tree(|t| {
4249 let root = t.create_root();
4250 let div = t.intern("div");
4251 let mut make = |class: &str, parent: u32| {
4252 let e = t.create_element(div);
4253 t.set_class(e, class);
4254 t.insert(e, parent, 0);
4255 e
4256 };
4257 let a = make("a", root);
4258 let b = make("b", a);
4259 let c = make("c", b);
4260 let n = make("n", c);
4261 (root, a, b, c, n)
4262 });
4263 restyle_all();
4264 assert_eq!(
4265 sk_css::rem_basis(),
4266 10.0,
4267 "the root's 62.5% of 16px is the rem basis"
4268 );
4269 assert_eq!(
4270 [root, a, b, c, n].map(font_size_of),
4271 [10.0, 20.0, 15.0, 15.0, 15.0],
4272 "each size of its parent's, and inherited as px"
4273 );
4274 assert_eq!(padding_top_of(b), px_len(7.5), "`.5em` of its own 15px");
4275 let computed = read_tree(|t| {
4276 t.node(c)
4277 .and_then(|n| n.computed.as_ref())
4278 .map(|c| c.base.clone())
4279 })
4280 .expect("cascaded");
4281 assert_eq!(
4282 computed.margin.top,
4283 Some(gpui::Length::Definite(gpui::px(15.0).into()))
4284 );
4285 assert_eq!(
4286 computed.size.width,
4287 Some(gpui::Length::Definite(gpui::px(20.0).into())),
4288 "2rem"
4289 );
4290 assert_eq!(
4291 computed.text.line_height,
4292 px_len(22.5),
4293 "an em line-height is px"
4294 );
4295 let number = read_tree(|t| {
4296 t.node(n)
4297 .and_then(|n| n.computed.as_ref())
4298 .and_then(|c| c.base.text.line_height)
4299 });
4300 assert_eq!(
4301 number,
4302 Some(gpui::relative(1.5)),
4303 "a number line-height stays a number"
4304 );
4305 let reported = crate::dom::computed_style(c).unwrap_or_default();
4306 assert!(
4307 reported.lines().any(|l| l == "font-size=15px"),
4308 "getComputedStyle: {reported}"
4309 );
4310 }
4311
4312 #[test]
4313 fn a_new_parent_font_size_reaches_the_em_below_it() {
4314 set_stylesheet(".big { font-size: 20px } .leaf { padding: 1em }".into());
4315 let (big, plain, leaves) = with_tree(|t| {
4316 let root = t.create_root();
4317 let div = t.intern("div");
4318 let big = t.create_element(div);
4319 t.set_class(big, "big");
4320 t.insert(big, root, 0);
4321 let plain = t.create_element(div);
4322 t.insert(plain, root, 1);
4323 let mut leaves = Vec::new();
4324 for parent in [big, plain] {
4325 let leaf = t.create_element(div);
4326 t.set_class(leaf, "leaf");
4327 t.insert(leaf, parent, 0);
4328 leaves.push(leaf);
4329 }
4330 (big, plain, leaves)
4331 });
4332 restyle_all();
4333 assert_eq!(
4334 leaves
4335 .iter()
4336 .map(|&l| padding_top_of(l))
4337 .collect::<Vec<_>>(),
4338 vec![px_len(20.0), px_len(16.0)]
4339 );
4340
4341 with_tree(|t| {
4342 t.set_class(plain, "big");
4343 t.set_class(big, "");
4344 });
4345 restyle_all();
4346 assert_eq!(
4347 leaves
4348 .iter()
4349 .map(|&l| padding_top_of(l))
4350 .collect::<Vec<_>>(),
4351 vec![px_len(16.0), px_len(20.0)]
4352 );
4353 assert_eq!(font_size_of(leaves[1]), 20.0);
4354 }
4355 #[test]
4356 fn character_width_follows_inherited_face_and_restyles_descendants() {
4357 sk_css::set_font_source(|| vec!["SK Metric Narrow".into(), "SK Metric Wide".into()]);
4358 sk_css::set_font_metric_source(|font, size| {
4359 Some(sk_css::FontRelativeMetrics {
4360 zero_advance: size
4361 * if font.family.as_ref() == "SK Metric Wide" {
4362 0.8
4363 } else {
4364 0.6
4365 },
4366 x_height: size * 0.4,
4367 })
4368 });
4369 struct Reset;
4370 impl Drop for Reset {
4371 fn drop(&mut self) {
4372 sk_css::set_font_metric_source(|_, _| None);
4373 }
4374 }
4375 let _reset = Reset;
4376 set_stylesheet(".narrow {font-family:'SK Metric Narrow';font-size:10px} .wide {font-family:'SK Metric Wide';font-size:10px} .leaf{width:1ch}".into());
4377 let (parent, leaves) = with_tree(|tree| {
4378 let root = tree.create_root();
4379 let tag = tree.intern("div");
4380 let mut parents = Vec::new();
4381 let mut leaves = Vec::new();
4382 for class in ["narrow", "wide"] {
4383 let parent = tree.create_element(tag);
4384 tree.set_class(parent, class);
4385 tree.insert(parent, root, 0);
4386 parents.push(parent);
4387 let leaf = tree.create_element(tag);
4388 tree.set_class(leaf, "leaf");
4389 tree.insert(leaf, parent, 0);
4390 leaves.push(leaf);
4391 }
4392 (parents[0], leaves)
4393 });
4394 let widths = || {
4395 read_tree(|tree| {
4396 leaves
4397 .iter()
4398 .map(|&id| {
4399 tree.node(id)
4400 .and_then(|node| node.computed.as_ref())
4401 .and_then(|computed| computed.base.size.width)
4402 })
4403 .collect::<Vec<_>>()
4404 })
4405 };
4406 restyle_all();
4407 assert_eq!(
4408 widths(),
4409 vec![Some(gpui::px(6.0).into()), Some(gpui::px(8.0).into())]
4410 );
4411 with_tree(|tree| tree.set_class(parent, "wide"));
4412 restyle_all();
4413 assert_eq!(
4414 widths(),
4415 vec![Some(gpui::px(8.0).into()), Some(gpui::px(8.0).into())]
4416 );
4417 }
4418}