Skip to main content

eternal_ui/
ui.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The element tree: mounting, styling, focus and event dispatch.
6
7use std::fmt;
8
9use eternal_styler::{
10    ComputedStyle, DeclarationBlock, ElementState, Error, OpaqueElement, Styler, Stylesheet,
11    opaque_element_from_index,
12};
13
14use crate::element::Element;
15use crate::event::{Event, Key, Modifiers};
16use crate::geometry::{Point, Rect, Size};
17use crate::layout::{Align, Justify};
18use crate::render::Fonts;
19use crate::shortcut::Shortcut;
20use crate::style::default_theme;
21use crate::widget::{EventCx, Handlers, Widget};
22use crate::widgets::{Container, parse_bool};
23
24/// A handle to a mounted element. Stays valid until the element is removed.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub struct NodeId(usize);
27
28pub(crate) struct Node<M> {
29    pub(crate) tag: &'static str,
30    pub(crate) widget: Box<dyn Widget<M>>,
31    pub(crate) id: Option<String>,
32    pub(crate) classes: Vec<String>,
33    pub(crate) attrs: Vec<(String, String)>,
34    pub(crate) custom_states: Vec<String>,
35    pub(crate) inline_style: Option<DeclarationBlock>,
36    pub(crate) handlers: Handlers<M>,
37    pub(crate) grow: f32,
38    pub(crate) align: Option<Align>,
39    pub(crate) disabled: bool,
40    pub(crate) shortcut: Option<Shortcut>,
41    /// The bits the framework manages: hover, active, focus.
42    pub(crate) state: ElementState,
43    pub(crate) parent: Option<NodeId>,
44    pub(crate) children: Vec<NodeId>,
45    pub(crate) style: ComputedStyle,
46    pub(crate) measured: Size,
47    pub(crate) rect: Rect,
48    pub(crate) content: Rect,
49}
50
51impl<M: 'static> Node<M> {
52    /// How a container aligns and justifies its children; defaults for
53    /// widgets that are not [`Container`]s.
54    pub(crate) fn container_alignment(&self) -> (Align, Justify) {
55        match self.widget.as_any().downcast_ref::<Container>() {
56            Some(container) => (container.align, container.justify),
57            None => (Align::Stretch, Justify::Start),
58        }
59    }
60}
61
62/// The element tree, the stylesheets that style it, and the focus.
63///
64/// `M` is the application's message type. Handlers produce messages, and
65/// [`handle`](Self::handle) returns them for the application to act on,
66/// which keeps every decision in explicit application code rather than in
67/// callbacks scattered through the tree.
68///
69/// A frame goes: feed events to [`handle`](Self::handle), act on the
70/// messages, [`layout`](Self::layout), [`paint`](Self::paint).
71pub struct Ui<M> {
72    nodes: Vec<Option<Node<M>>>,
73    free: Vec<usize>,
74    root: Option<NodeId>,
75    styler: Styler,
76    focus: Option<NodeId>,
77    hover: Option<NodeId>,
78    active: Option<NodeId>,
79    shortcuts: Vec<(Shortcut, Box<dyn FnMut() -> M>)>,
80    pub(crate) dirty: bool,
81    pub(crate) viewport: Size,
82}
83
84impl<M: 'static> Default for Ui<M> {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl<M: 'static> Ui<M> {
91    /// An empty tree styled by the [default theme](crate::default_theme).
92    pub fn new() -> Self {
93        let mut ui = Self::unstyled();
94        ui.styler.add_stylesheet(default_theme());
95        ui
96    }
97
98    /// An empty tree with no stylesheet at all.
99    pub fn unstyled() -> Self {
100        Self {
101            nodes: Vec::new(),
102            free: Vec::new(),
103            root: None,
104            styler: Styler::new(),
105            focus: None,
106            hover: None,
107            active: None,
108            shortcuts: Vec::new(),
109            dirty: true,
110            viewport: Size::ZERO,
111        }
112    }
113
114    // Stylesheets
115
116    /// Replaces every stylesheet with this one.
117    pub fn set_theme(&mut self, theme: Stylesheet) {
118        self.styler.clear_stylesheets();
119        self.styler.add_stylesheet(theme);
120        self.dirty = true;
121    }
122
123    /// Adds a stylesheet after the existing ones, so it wins ties.
124    pub fn add_stylesheet(&mut self, sheet: Stylesheet) {
125        self.styler.add_stylesheet(sheet);
126        self.dirty = true;
127    }
128
129    pub fn styler(&self) -> &Styler {
130        &self.styler
131    }
132
133    /// The style engine, for changing the root font size and the like.
134    pub fn styler_mut(&mut self) -> &mut Styler {
135        self.dirty = true;
136        &mut self.styler
137    }
138
139    // Mounting
140
141    /// Replaces the whole tree with `element`.
142    pub fn set_root(&mut self, element: Element<M>) -> NodeId {
143        self.clear();
144        let id = self.mount_element(None, element);
145        self.root = Some(id);
146        id
147    }
148
149    /// Appends `element` as the last child of `parent`.
150    pub fn mount(&mut self, parent: NodeId, element: Element<M>) -> NodeId {
151        let id = self.mount_element(Some(parent), element);
152        self.node_mut(parent).children.push(id);
153        id
154    }
155
156    fn mount_element(&mut self, parent: Option<NodeId>, element: Element<M>) -> NodeId {
157        let Element {
158            tag,
159            widget,
160            id: element_id,
161            classes,
162            attrs,
163            custom_states,
164            inline_style,
165            handlers,
166            children,
167            grow,
168            align,
169            disabled,
170            shortcut,
171        } = element;
172        let id = self.allocate(Node {
173            tag,
174            widget,
175            id: element_id,
176            classes,
177            attrs,
178            custom_states,
179            inline_style,
180            handlers,
181            grow,
182            align,
183            disabled,
184            shortcut,
185            state: ElementState::empty(),
186            parent,
187            children: Vec::new(),
188            style: ComputedStyle::initial(),
189            measured: Size::ZERO,
190            rect: Rect::ZERO,
191            content: Rect::ZERO,
192        });
193        for child in children {
194            let child_id = self.mount_element(Some(id), child);
195            self.node_mut(id).children.push(child_id);
196        }
197        self.dirty = true;
198        id
199    }
200
201    fn allocate(&mut self, node: Node<M>) -> NodeId {
202        match self.free.pop() {
203            Some(index) => {
204                self.nodes[index] = Some(node);
205                NodeId(index)
206            }
207            None => {
208                self.nodes.push(Some(node));
209                NodeId(self.nodes.len() - 1)
210            }
211        }
212    }
213
214    /// Removes an element and everything under it.
215    pub fn remove(&mut self, id: NodeId) {
216        if self.root == Some(id) {
217            self.clear();
218            return;
219        }
220        if let Some(parent) = self.node(id).parent {
221            self.node_mut(parent).children.retain(|&child| child != id);
222        }
223        self.free_subtree(id);
224        self.dirty = true;
225    }
226
227    /// Removes every element.
228    pub fn clear(&mut self) {
229        self.nodes.clear();
230        self.free.clear();
231        self.root = None;
232        self.focus = None;
233        self.hover = None;
234        self.active = None;
235        self.dirty = true;
236    }
237
238    fn free_subtree(&mut self, id: NodeId) {
239        if self.focus == Some(id) {
240            self.set_focus(None, false);
241        }
242        if self.hover == Some(id) {
243            self.hover = None;
244        }
245        if self.active == Some(id) {
246            self.active = None;
247        }
248        let children = std::mem::take(&mut self.node_mut(id).children);
249        for child in children {
250            self.free_subtree(child);
251        }
252        self.nodes[id.0] = None;
253        self.free.push(id.0);
254    }
255
256    // Looking around
257
258    pub fn root(&self) -> Option<NodeId> {
259        self.root
260    }
261
262    /// The element with this `id` attribute, if any.
263    pub fn find(&self, id: &str) -> Option<NodeId> {
264        self.preorder()
265            .into_iter()
266            .find(|&node| self.node(node).id.as_deref() == Some(id))
267    }
268
269    pub fn contains(&self, id: NodeId) -> bool {
270        self.nodes.get(id.0).is_some_and(Option::is_some)
271    }
272
273    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
274        self.node(id).parent
275    }
276
277    pub fn children(&self, id: NodeId) -> &[NodeId] {
278        &self.node(id).children
279    }
280
281    pub fn tag(&self, id: NodeId) -> &'static str {
282        self.node(id).tag
283    }
284
285    /// The element's border box, as of the last [`layout`](Self::layout).
286    pub fn rect(&self, id: NodeId) -> Rect {
287        self.node(id).rect
288    }
289
290    /// The element's content box, as of the last [`layout`](Self::layout).
291    pub fn content_rect(&self, id: NodeId) -> Rect {
292        self.node(id).content
293    }
294
295    /// The element's style, as of the last [`layout`](Self::layout).
296    pub fn style(&self, id: NodeId) -> &ComputedStyle {
297        &self.node(id).style
298    }
299
300    /// The element's full state: what the framework tracks, what the widget
301    /// owns, and `DISABLED` if it is disabled.
302    pub fn state(&self, id: NodeId) -> ElementState {
303        self.state_of(id)
304    }
305
306    /// The widget behind an element, if it is a `W`.
307    pub fn widget<W: Widget<M>>(&self, id: NodeId) -> Option<&W> {
308        self.node(id).widget.as_any().downcast_ref()
309    }
310
311    /// The widget behind an element, for changing it. Styles and layout are
312    /// recomputed afterwards.
313    pub fn widget_mut<W: Widget<M>>(&mut self, id: NodeId) -> Option<&mut W> {
314        self.dirty = true;
315        self.node_mut(id).widget.as_any_mut().downcast_mut()
316    }
317
318    /// The deepest element under `point`, as of the last layout.
319    pub fn hit_test(&self, point: Point) -> Option<NodeId> {
320        self.root.and_then(|root| self.hit(root, point))
321    }
322
323    fn hit(&self, id: NodeId, point: Point) -> Option<NodeId> {
324        let node = self.node(id);
325        if !node.rect.contains(point) {
326            return None;
327        }
328        node.children
329            .iter()
330            .rev()
331            .find_map(|&child| self.hit(child, point))
332            .or(Some(id))
333    }
334
335    /// Every element, parents before children, siblings in order.
336    pub fn preorder(&self) -> Vec<NodeId> {
337        let mut order = Vec::new();
338        let mut stack: Vec<NodeId> = self.root.into_iter().collect();
339        while let Some(id) = stack.pop() {
340            order.push(id);
341            stack.extend(self.node(id).children.iter().rev());
342        }
343        order
344    }
345
346    /// Whether something changed since the last [`layout`](Self::layout).
347    pub fn needs_layout(&self) -> bool {
348        self.dirty
349    }
350
351    pub fn viewport(&self) -> Size {
352        self.viewport
353    }
354
355    // Changing elements
356
357    pub fn has_class(&self, id: NodeId, class: &str) -> bool {
358        self.node(id).classes.iter().any(|c| c == class)
359    }
360
361    /// Adds or removes a class.
362    pub fn set_class(&mut self, id: NodeId, class: &str, on: bool) {
363        let node = self.node_mut(id);
364        let present = node.classes.iter().position(|c| c == class);
365        match (present, on) {
366            (None, true) => node.classes.push(class.to_owned()),
367            (Some(index), false) => {
368                node.classes.remove(index);
369            }
370            _ => return,
371        }
372        self.dirty = true;
373    }
374
375    pub fn is_disabled(&self, id: NodeId) -> bool {
376        self.node(id).disabled
377    }
378
379    /// A disabled element matches `:disabled`, gets no events and cannot
380    /// take focus.
381    pub fn set_disabled(&mut self, id: NodeId, disabled: bool) {
382        if self.focus == Some(id) && disabled {
383            self.set_focus(None, false);
384        }
385        self.node_mut(id).disabled = disabled;
386        self.dirty = true;
387    }
388
389    /// Sets or clears a custom state, matched by `:state(name)`.
390    pub fn set_state(&mut self, id: NodeId, name: &str, on: bool) {
391        let node = self.node_mut(id);
392        let present = node.custom_states.iter().position(|s| s == name);
393        match (present, on) {
394            (None, true) => node.custom_states.push(name.to_owned()),
395            (Some(index), false) => {
396                node.custom_states.remove(index);
397            }
398            _ => return,
399        }
400        self.dirty = true;
401    }
402
403    /// Sets an attribute at run time, the same ones [`Element::attr`] takes.
404    /// Returns `false` for an attribute the element does not accept or a
405    /// value it cannot parse, rather than panicking, since the value may
406    /// come from anywhere.
407    pub fn set_attr(&mut self, id: NodeId, name: &str, value: &str) -> bool {
408        let node = self.node_mut(id);
409        let accepted = match name {
410            "id" => {
411                node.id = Some(value.to_owned());
412                true
413            }
414            "class" => {
415                node.classes = value.split_whitespace().map(str::to_owned).collect();
416                true
417            }
418            "style" => match DeclarationBlock::parse(value) {
419                Ok(block) => {
420                    node.inline_style = Some(block);
421                    true
422                }
423                Err(_) => false,
424            },
425            "grow" => match value.trim().parse() {
426                Ok(grow) => {
427                    node.grow = grow;
428                    true
429                }
430                Err(_) => false,
431            },
432            "align" => match Align::parse(value) {
433                Some(align) => {
434                    node.align = Some(align);
435                    true
436                }
437                None => false,
438            },
439            "disabled" => {
440                let disabled = parse_bool(value);
441                self.set_disabled(id, disabled);
442                return true;
443            }
444            "shortcut" => match Shortcut::parse(value) {
445                Ok(shortcut) => {
446                    node.shortcut = Some(shortcut);
447                    true
448                }
449                Err(_) => false,
450            },
451            "state" => {
452                node.custom_states = value.split_whitespace().map(str::to_owned).collect();
453                true
454            }
455            _ => {
456                let accepted = node.widget.set_attribute(name, value);
457                if accepted {
458                    match node.attrs.iter_mut().find(|(n, _)| n == name) {
459                        Some(entry) => entry.1 = value.to_owned(),
460                        None => node.attrs.push((name.to_owned(), value.to_owned())),
461                    }
462                }
463                accepted
464            }
465        };
466        if accepted {
467            self.dirty = true;
468        }
469        accepted
470    }
471
472    /// Replaces the inline style.
473    pub fn set_inline_style(&mut self, id: NodeId, css: &str) -> Result<(), Error> {
474        let block = DeclarationBlock::parse(css)?;
475        self.node_mut(id).inline_style = Some(block);
476        self.dirty = true;
477        Ok(())
478    }
479
480    // Focus
481
482    pub fn focused(&self) -> Option<NodeId> {
483        self.focus
484    }
485
486    pub fn hovered(&self) -> Option<NodeId> {
487        self.hover
488    }
489
490    /// Moves keyboard focus to `id`, if it can take it. Focus moved this
491    /// way shows as `:focus-visible`, like focus moved with the keyboard.
492    pub fn focus(&mut self, id: NodeId) -> bool {
493        if !self.is_focusable(id) {
494            return false;
495        }
496        self.set_focus(Some(id), true);
497        true
498    }
499
500    pub fn blur(&mut self) {
501        self.set_focus(None, false);
502    }
503
504    fn is_focusable(&self, id: NodeId) -> bool {
505        let node = self.node(id);
506        node.widget.focusable() && !node.disabled
507    }
508
509    fn set_focus(&mut self, target: Option<NodeId>, visible: bool) {
510        if let Some(old) = self.focus.take() {
511            self.node_mut(old)
512                .state
513                .remove(ElementState::FOCUS | ElementState::FOCUS_VISIBLE);
514            let mut ancestor = self.node(old).parent;
515            while let Some(id) = ancestor {
516                self.node_mut(id).state.remove(ElementState::FOCUS_WITHIN);
517                ancestor = self.node(id).parent;
518            }
519        }
520        if let Some(new) = target {
521            let mut state = ElementState::FOCUS;
522            if visible {
523                state |= ElementState::FOCUS_VISIBLE;
524            }
525            self.node_mut(new).state.insert(state);
526            let mut ancestor = self.node(new).parent;
527            while let Some(id) = ancestor {
528                self.node_mut(id).state.insert(ElementState::FOCUS_WITHIN);
529                ancestor = self.node(id).parent;
530            }
531        }
532        self.focus = target;
533        self.dirty = true;
534    }
535
536    /// Moves focus to the next (or previous) focusable element in tree
537    /// order, wrapping around. What Tab and Shift+Tab do.
538    pub fn move_focus(&mut self, forward: bool) {
539        let focusable: Vec<NodeId> = self
540            .preorder()
541            .into_iter()
542            .filter(|&id| self.is_focusable(id))
543            .collect();
544        if focusable.is_empty() {
545            return;
546        }
547        let current = self
548            .focus
549            .and_then(|focus| focusable.iter().position(|&id| id == focus));
550        let next = match (current, forward) {
551            (Some(index), true) => (index + 1) % focusable.len(),
552            (Some(index), false) => (index + focusable.len() - 1) % focusable.len(),
553            (None, true) => 0,
554            (None, false) => focusable.len() - 1,
555        };
556        self.set_focus(Some(focusable[next]), true);
557    }
558
559    /// The nearest focusable element at or above `id`.
560    fn focusable_from(&self, id: NodeId) -> Option<NodeId> {
561        let mut current = Some(id);
562        while let Some(id) = current {
563            if self.is_focusable(id) {
564                return Some(id);
565            }
566            current = self.node(id).parent;
567        }
568        None
569    }
570
571    // Shortcuts
572
573    /// Binds a shortcut for the whole window. Global shortcuts are checked
574    /// before element shortcuts and before the focused element sees the
575    /// key.
576    pub fn bind(&mut self, shortcut: Shortcut, handler: impl FnMut() -> M + 'static) {
577        self.shortcuts.push((shortcut, Box::new(handler)));
578    }
579
580    pub fn unbind(&mut self, shortcut: Shortcut) {
581        self.shortcuts.retain(|(bound, _)| *bound != shortcut);
582    }
583
584    /// Every shortcut in effect: the global ones and those of elements
585    /// that are not disabled, with the element's id when it has one. For
586    /// help screens and menus.
587    pub fn shortcuts(&self) -> Vec<(Shortcut, Option<NodeId>)> {
588        let mut all: Vec<(Shortcut, Option<NodeId>)> = self
589            .shortcuts
590            .iter()
591            .map(|(shortcut, _)| (*shortcut, None))
592            .collect();
593        for id in self.preorder() {
594            let node = self.node(id);
595            if let Some(shortcut) = node.shortcut
596                && !node.disabled
597            {
598                all.push((shortcut, Some(id)));
599            }
600        }
601        all
602    }
603
604    fn run_shortcuts(&mut self, key: Key, modifiers: Modifiers, messages: &mut Vec<M>) -> bool {
605        for (shortcut, handler) in &mut self.shortcuts {
606            if shortcut.matches(key, modifiers) {
607                messages.push(handler());
608                return true;
609            }
610        }
611        let target = self.preorder().into_iter().find(|&id| {
612            let node = self.node(id);
613            !node.disabled && node.shortcut.is_some_and(|s| s.matches(key, modifiers))
614        });
615        if let Some(id) = target {
616            if let Some(handler) = &mut self.node_mut(id).handlers.click {
617                messages.push(handler());
618            }
619            return true;
620        }
621        false
622    }
623
624    // Events
625
626    /// Feeds one event through the tree and returns the messages it
627    /// produced.
628    ///
629    /// Pointer events go to the deepest element under the pointer and
630    /// bubble up until a widget handles them; while a button is held, they
631    /// go to the element it was pressed on. Key events go first to global
632    /// shortcuts, then to element shortcuts, then to the focused element,
633    /// and finally Tab and Shift+Tab move focus. Text goes to the focused
634    /// element.
635    ///
636    /// Hit-testing uses the last layout, so call [`layout`](Self::layout)
637    /// after changes before feeding more pointer events.
638    pub fn handle(&mut self, event: &Event, fonts: &dyn Fonts) -> Vec<M> {
639        let mut messages = Vec::new();
640        match event {
641            Event::PointerMove { position } => {
642                self.update_hover(Some(*position));
643                if let Some(target) = self.active.or_else(|| self.hit_test(*position)) {
644                    self.deliver(target, event, fonts, &mut messages);
645                }
646            }
647            Event::PointerDown { position, .. } => {
648                self.update_hover(Some(*position));
649                let target = self.hit_test(*position);
650                self.set_active(target);
651                match target {
652                    Some(target) => {
653                        let focus = self.focusable_from(target);
654                        self.set_focus(focus, false);
655                        self.deliver(target, event, fonts, &mut messages);
656                    }
657                    None => self.set_focus(None, false),
658                }
659            }
660            Event::PointerUp { position, .. } => {
661                if let Some(target) = self.active.or_else(|| self.hit_test(*position)) {
662                    self.deliver(target, event, fonts, &mut messages);
663                }
664                self.set_active(None);
665                self.update_hover(Some(*position));
666            }
667            Event::PointerLeave => self.update_hover(None),
668            Event::Wheel { position, .. } => {
669                if let Some(target) = self.hit_test(*position) {
670                    self.deliver(target, event, fonts, &mut messages);
671                }
672            }
673            Event::KeyDown { key, modifiers } => {
674                if self.run_shortcuts(*key, *modifiers, &mut messages) {
675                    return messages;
676                }
677                if let Some(focus) = self.focus
678                    && self.deliver(focus, event, fonts, &mut messages)
679                {
680                    return messages;
681                }
682                if *key == Key::Tab && (modifiers.is_empty() || *modifiers == Modifiers::SHIFT) {
683                    self.move_focus(!modifiers.contains(Modifiers::SHIFT));
684                }
685            }
686            Event::KeyUp { .. } | Event::Text(_) => {
687                if let Some(focus) = self.focus {
688                    self.deliver(focus, event, fonts, &mut messages);
689                }
690            }
691        }
692        messages
693    }
694
695    /// Offers `event` to `start` and then to each ancestor until one
696    /// handles it. Disabled elements are skipped.
697    fn deliver(
698        &mut self,
699        start: NodeId,
700        event: &Event,
701        fonts: &dyn Fonts,
702        messages: &mut Vec<M>,
703    ) -> bool {
704        let mut current = Some(start);
705        while let Some(id) = current {
706            let state = self.state_of(id);
707            let node = self.node_mut(id);
708            if !node.disabled {
709                let Node {
710                    widget,
711                    handlers,
712                    style,
713                    rect,
714                    content,
715                    ..
716                } = node;
717                let mut cx = EventCx {
718                    handlers,
719                    messages,
720                    fonts,
721                    focus_requested: false,
722                    changed: false,
723                    rect: *rect,
724                    content: *content,
725                    state,
726                    style,
727                };
728                let handled = widget.event(&mut cx, event);
729                let (focus_requested, changed) = (cx.focus_requested, cx.changed);
730                if changed {
731                    self.dirty = true;
732                }
733                if focus_requested && self.is_focusable(id) {
734                    self.set_focus(Some(id), false);
735                }
736                if handled {
737                    return true;
738                }
739            }
740            current = self.node(id).parent;
741        }
742        false
743    }
744
745    /// Marks the element under `position` and its ancestors as hovered,
746    /// and nothing else.
747    fn update_hover(&mut self, position: Option<Point>) {
748        let target = position.and_then(|p| self.hit_test(p));
749        if target == self.hover && !self.dirty {
750            return;
751        }
752        self.hover = target;
753        self.set_chain_state(target, ElementState::HOVER);
754    }
755
756    fn set_active(&mut self, target: Option<NodeId>) {
757        self.active = target;
758        self.set_chain_state(target, ElementState::ACTIVE);
759    }
760
761    /// Sets `flag` on `target` and its ancestors and clears it everywhere
762    /// else.
763    fn set_chain_state(&mut self, target: Option<NodeId>, flag: ElementState) {
764        let mut chain = Vec::new();
765        let mut current = target;
766        while let Some(id) = current {
767            chain.push(id);
768            current = self.node(id).parent;
769        }
770        for id in self.preorder() {
771            let node = self.node_mut(id);
772            let before = node.state;
773            node.state.set(flag, chain.contains(&id));
774            if node.state != before {
775                self.dirty = true;
776            }
777        }
778    }
779
780    // Styles
781
782    pub(crate) fn recompute_styles(&mut self) {
783        for id in self.preorder() {
784            let parent_style = self.node(id).parent.map(|p| self.node(p).style.clone());
785            let node_ref = NodeRef { ui: self, id };
786            let node = self.node(id);
787            let style = self.styler.compute_with_inline(
788                &node_ref,
789                parent_style.as_ref(),
790                node.inline_style.as_ref(),
791            );
792            self.node_mut(id).style = style;
793        }
794    }
795
796    pub(crate) fn state_of(&self, id: NodeId) -> ElementState {
797        let node = self.node(id);
798        let mut state = node.state | node.widget.state();
799        if node.disabled {
800            state |= ElementState::DISABLED;
801        }
802        state
803    }
804
805    pub(crate) fn node(&self, id: NodeId) -> &Node<M> {
806        self.nodes
807            .get(id.0)
808            .and_then(Option::as_ref)
809            .unwrap_or_else(|| panic!("{id:?} was removed"))
810    }
811
812    pub(crate) fn node_mut(&mut self, id: NodeId) -> &mut Node<M> {
813        self.nodes
814            .get_mut(id.0)
815            .and_then(Option::as_mut)
816            .unwrap_or_else(|| panic!("{id:?} was removed"))
817    }
818}
819
820impl<M: 'static> fmt::Debug for Ui<M> {
821    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822        fn write_node<M: 'static>(
823            ui: &Ui<M>,
824            id: NodeId,
825            depth: usize,
826            f: &mut fmt::Formatter<'_>,
827        ) -> fmt::Result {
828            let node = ui.node(id);
829            write!(f, "{:indent$}<{}", "", node.tag, indent = depth * 2)?;
830            if let Some(id) = &node.id {
831                write!(f, " id=\"{id}\"")?;
832            }
833            if !node.classes.is_empty() {
834                write!(f, " class=\"{}\"", node.classes.join(" "))?;
835            }
836            writeln!(f, "> {:?}", node.rect)?;
837            for &child in &node.children {
838                write_node(ui, child, depth + 1, f)?;
839            }
840            Ok(())
841        }
842        match self.root {
843            Some(root) => write_node(self, root, 0, f),
844            None => writeln!(f, "<empty>"),
845        }
846    }
847}
848
849/// What the style engine sees of an element.
850struct NodeRef<'a, M> {
851    ui: &'a Ui<M>,
852    id: NodeId,
853}
854
855impl<M> Clone for NodeRef<'_, M> {
856    fn clone(&self) -> Self {
857        Self {
858            ui: self.ui,
859            id: self.id,
860        }
861    }
862}
863
864impl<M> fmt::Debug for NodeRef<'_, M> {
865    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866        write!(f, "NodeRef({:?})", self.id)
867    }
868}
869
870impl<M: 'static> NodeRef<'_, M> {
871    fn node(&self) -> &Node<M> {
872        self.ui.node(self.id)
873    }
874
875    fn at(&self, id: NodeId) -> Self {
876        Self { ui: self.ui, id }
877    }
878
879    fn sibling(&self, offset: isize) -> Option<Self> {
880        let parent = self.node().parent?;
881        let siblings = &self.ui.node(parent).children;
882        let position = siblings.iter().position(|&id| id == self.id)?;
883        let target = position.checked_add_signed(offset)?;
884        siblings.get(target).map(|&id| self.at(id))
885    }
886}
887
888impl<M: 'static> eternal_styler::Element for NodeRef<'_, M> {
889    fn opaque(&self) -> OpaqueElement {
890        opaque_element_from_index(self.id.0)
891    }
892
893    fn parent(&self) -> Option<Self> {
894        self.node().parent.map(|id| self.at(id))
895    }
896
897    fn prev_sibling(&self) -> Option<Self> {
898        self.sibling(-1)
899    }
900
901    fn next_sibling(&self) -> Option<Self> {
902        self.sibling(1)
903    }
904
905    fn first_child(&self) -> Option<Self> {
906        self.node().children.first().map(|&id| self.at(id))
907    }
908
909    fn local_name(&self) -> &str {
910        self.node().tag
911    }
912
913    fn id(&self) -> Option<&str> {
914        self.node().id.as_deref()
915    }
916
917    fn classes(&self) -> impl Iterator<Item = &str> {
918        self.node().classes.iter().map(String::as_str)
919    }
920
921    fn attribute(&self, name: &str) -> Option<&str> {
922        let node = self.node();
923        if name == "disabled" {
924            return node.disabled.then_some("");
925        }
926        node.attrs
927            .iter()
928            .find(|(n, _)| n == name)
929            .map(|(_, v)| v.as_str())
930    }
931
932    fn state(&self) -> ElementState {
933        self.ui.state_of(self.id)
934    }
935
936    fn has_custom_state(&self, name: &str) -> bool {
937        self.node().custom_states.iter().any(|s| s == name)
938    }
939}