1
//! Engine-side support for `<transient-window>`: find the open ones after a
2
//! layout, and describe each as something a backend can turn into a surface.
3
//!
4
//! The node type and its config live in `azul_core::transient`. This module is
5
//! the bridge between "a node in the parent's DOM says `open=true`" and "the
6
//! backend has a window to create" — it does the part that is the same on
7
//! every platform, so the per-backend code only has to answer "given this
8
//! anchor rect and this gravity, make a surface".
9
//!
10
//! A transient window is NOT laid out in its parent (see
11
//! `layout_tree::get_display_type`, which returns `display: none` for the node
12
//! in its parent's flow). Its subtree is laid out separately, as a root, with
13
//! its own `DomId` — the same treatment a `VirtualView` child gets — and that
14
//! is what [`collect_open_transient_windows`] sets up.
15

            
16
use alloc::vec::Vec;
17

            
18
use azul_core::{
19
    dom::{DomId, NodeType},
20
    geom::{LogicalRect, LogicalSize, OptionLogicalSize},
21
    id::NodeId,
22
    refany::OptionRefAny,
23
    styled_dom::StyledDom,
24
    transient::{
25
        TransientAnchor, TransientDismiss, TransientDock, TransientTearoff, TransientWindowConfig,
26
    },
27
};
28

            
29
/// Everything a backend needs to materialise one open transient window.
30
///
31
/// Placement is an ANCHOR RECT plus an EDGE, never a screen position. Wayland
32
/// cannot be given coordinates (the compositor hides them) and `xdg_positioner`
33
/// takes exactly this shape; the other backends compute a position from it in
34
/// one shared place ([`TransientPlacement::resolve`]) so they cannot disagree.
35
#[derive(Debug, Copy, Clone, PartialEq)]
36
pub struct TransientPlacement {
37
    /// The `<transient-window>` node in the PARENT dom.
38
    pub node: NodeId,
39
    /// The anchor: the transient node's parent element, in parent-window
40
    /// logical coordinates. What the popup opens FROM.
41
    pub anchor_rect: LogicalRect,
42
    /// Which edge of the anchor it opens from.
43
    pub anchor: TransientAnchor,
44
    /// What closes it.
45
    pub dismiss: TransientDismiss,
46
    /// The requested size, or `None` for content-sized. The backend lays the
47
    /// subtree out with `available = size` when given, and with an unbounded
48
    /// available size otherwise, then uses the content's extent.
49
    pub size: OptionLogicalSize,
50
    /// Whether the user may tear it off into a free toplevel, and whether
51
    /// drop zones take part.
52
    pub tearoff: TransientTearoff,
53
    /// The app's `torn` attribute: a request, applied when it CHANGES (the
54
    /// manager keeps the user's own tear-offs in between).
55
    pub torn: bool,
56
    /// The popup window's background material (a clip mask on the node
57
    /// implies `Transparent`, see `collect_open_transient_windows`).
58
    pub material: azul_core::window::WindowBackgroundMaterial,
59
    /// Popup at the anchor, or inline content of it (`dock="inline"`).
60
    pub dock: TransientDock,
61
}
62

            
63
impl TransientPlacement {
64
    /// Where the popup's top-left goes, in the PARENT's logical coordinates,
65
    /// for a popup of `size` opening from this anchor.
66
    ///
67
    /// Shared by every backend that needs a coordinate (X11, Windows, macOS,
68
    /// headless) so the arithmetic lives once. Wayland does NOT call this — it
69
    /// hands `anchor_rect` + `anchor` to `xdg_positioner` and lets the
70
    /// compositor place it, which is the only way to get it right there.
71
    ///
72
    /// `cursor` is used only for [`TransientAnchor::Cursor`]; pass the current
73
    /// pointer position, or `None` to fall back to the anchor's corner.
74
    #[must_use]
75
15
    pub fn resolve(
76
15
        &self,
77
15
        size: LogicalSize,
78
15
        cursor: Option<azul_core::geom::LogicalPosition>,
79
15
    ) -> azul_core::geom::LogicalPosition {
80
        use azul_core::geom::LogicalPosition;
81
15
        let a = self.anchor_rect;
82
15
        match self.anchor {
83
9
            TransientAnchor::Bottom => LogicalPosition::new(a.origin.x, a.origin.y + a.size.height),
84
2
            TransientAnchor::Top => LogicalPosition::new(a.origin.x, a.origin.y - size.height),
85
1
            TransientAnchor::Left => LogicalPosition::new(a.origin.x - size.width, a.origin.y),
86
1
            TransientAnchor::Right => LogicalPosition::new(a.origin.x + a.size.width, a.origin.y),
87
2
            TransientAnchor::Cursor => cursor.unwrap_or(a.origin),
88
        }
89
15
    }
90

            
91
    /// [`Self::resolve`], then keep the popup inside `bounds` — a rect in the
92
    /// PARENT's coordinate space, normally the monitor's work area (a popup is
93
    /// its own OS window and may hang out of the parent, but not off the
94
    /// screen; a short parent window must not force its picker to flip).
95
    /// A popup that would run off the bottom flips to open upward when there
96
    /// is room above (and vice versa; left/right the same), and whatever
97
    /// still overflows is slid back in. Menus have done this edge-flip +
98
    /// clamp since forever.
99
    #[must_use]
100
5
    pub fn resolve_within(
101
5
        &self,
102
5
        size: LogicalSize,
103
5
        cursor: Option<azul_core::geom::LogicalPosition>,
104
5
        bounds: LogicalRect,
105
5
    ) -> azul_core::geom::LogicalPosition {
106
5
        let a = self.anchor_rect;
107
5
        let (min_x, min_y) = (bounds.origin.x, bounds.origin.y);
108
5
        let (max_x, max_y) = (bounds.max_x(), bounds.max_y());
109
5
        let mut pos = self.resolve(size, cursor);
110
4
        match self.anchor {
111
            TransientAnchor::Bottom
112
4
                if pos.y + size.height > max_y && a.origin.y - size.height >= min_y =>
113
1
            {
114
1
                pos.y = a.origin.y - size.height;
115
1
            }
116
            TransientAnchor::Top
117
1
                if pos.y < min_y && a.origin.y + a.size.height + size.height <= max_y =>
118
1
            {
119
1
                pos.y = a.origin.y + a.size.height;
120
1
            }
121
            TransientAnchor::Right
122
                if pos.x + size.width > max_x && a.origin.x - size.width >= min_x =>
123
            {
124
                pos.x = a.origin.x - size.width;
125
            }
126
            TransientAnchor::Left
127
                if pos.x < min_x && a.origin.x + a.size.width + size.width <= max_x =>
128
            {
129
                pos.x = a.origin.x + a.size.width;
130
            }
131
3
            _ => {}
132
        }
133
5
        pos.x = pos.x.min(max_x - size.width).max(min_x);
134
5
        pos.y = pos.y.min(max_y - size.height).max(min_y);
135
5
        pos
136
5
    }
137
}
138

            
139
/// Every `<transient-window>` in `styled_dom` whose config says `open`, with
140
/// the anchor rect of its parent element taken from `positions` (the
141
/// parent-window layout result, indexed by `NodeId`).
142
///
143
/// Closed transient windows are not returned — there is nothing to do for
144
/// them, and the caller must not have to filter. A transient window with no
145
/// parent (the root itself) is skipped: there is nothing to anchor to.
146
///
147
/// `rect_of` is how the caller supplies "where did node N land in the parent's
148
/// layout"; it is a closure rather than a map so a `DomLayoutResult` and a test
149
/// fixture can both drive it without converting.
150
///
151
/// `anchor_overrides` are `(transient node, zone node)` pairs for windows the
152
/// user docked onto a drop zone: such a window anchors to the ZONE's rect,
153
/// not its parent's. A zone that is no longer laid out falls back to the
154
/// parent, so the window never anchors to nothing.
155
#[must_use]
156
3
pub fn collect_open_transient_windows(
157
3
    styled_dom: &StyledDom,
158
3
    forced_open: &[NodeId],
159
3
    anchor_overrides: &[(NodeId, NodeId)],
160
3
    mut rect_of: impl FnMut(NodeId) -> Option<LogicalRect>,
161
3
) -> Vec<TransientPlacement> {
162
3
    let nodes = styled_dom.node_data.as_container();
163
3
    let hierarchy = styled_dom.node_hierarchy.as_container();
164
3
    let mut out = Vec::new();
165

            
166
15
    for node in nodes.linear_iter() {
167
15
        let Some(nd) = nodes.get(node) else { continue };
168
15
        let NodeType::TransientWindow(cfg) = nd.get_node_type() else {
169
9
            continue;
170
        };
171
        // The attribute, or a callback's `set_transient_window_open(true)`
172
        // held by the manager — a widget can open its own popup without the
173
        // app carrying a flag for it.
174
6
        if !cfg.open && !forced_open.contains(&node) {
175
2
            continue;
176
4
        }
177
4
        let Some(parent) = hierarchy
178
4
            .get(node)
179
4
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
180
        else {
181
            continue; // a root transient window has nothing to anchor to
182
        };
183
4
        let zone_rect = anchor_overrides
184
4
            .iter()
185
4
            .find(|(n, _)| *n == node)
186
4
            .and_then(|(_, zone)| rect_of(*zone));
187
4
        let Some(anchor_rect) = zone_rect.or_else(|| rect_of(parent)) else {
188
            continue; // the parent was not laid out (display:none ancestor)
189
        };
190
4
        let mut placement = placement_for(node, anchor_rect, cfg);
191
        // A clip mask on the node is the window's shape: that needs alpha.
192
4
        if nd.get_svg_data().is_some()
193
            && placement.material == azul_core::window::WindowBackgroundMaterial::Opaque
194
        {
195
            placement.material = azul_core::window::WindowBackgroundMaterial::Transparent;
196
4
        }
197
4
        out.push(placement);
198
    }
199
3
    out
200
3
}
201

            
202
/// Build the placement for one open node. Split out so the pure mapping from
203
/// config to placement is testable without a `StyledDom`.
204
#[must_use]
205
4
pub const fn placement_for(
206
4
    node: NodeId,
207
4
    anchor_rect: LogicalRect,
208
4
    cfg: &TransientWindowConfig,
209
4
) -> TransientPlacement {
210
4
    TransientPlacement {
211
4
        node,
212
4
        anchor_rect,
213
4
        anchor: cfg.anchor,
214
4
        dismiss: cfg.dismiss,
215
4
        size: cfg.size,
216
4
        tearoff: cfg.tearoff,
217
4
        torn: cfg.torn,
218
4
        material: cfg.material,
219
4
        dock: cfg.dock,
220
4
    }
221
4
}
222

            
223
/// The selector naming a `tearoff="zone"` window's drop zones, from the
224
/// node's `tearoff-zone` attribute (XML: `tearoff="zone:<selector>"` sets it).
225
#[must_use]
226
pub fn tearoff_zone_selector(styled_dom: &StyledDom, node: NodeId) -> Option<String> {
227
    use azul_core::dom::AttributeType;
228
    let nodes = styled_dom.node_data.as_container();
229
    let nd = nodes.get(node)?;
230
    nd.attributes().as_ref().iter().find_map(|a| match a {
231
        AttributeType::Custom(kv) | AttributeType::Data(kv)
232
            if kv.attr_name.as_str() == "tearoff-zone" =>
233
        {
234
            Some(kv.value.as_str().to_owned())
235
        }
236
        _ => None,
237
    })
238
}
239

            
240
/// The nodes of `styled_dom` matching `selector` - the drop zones of a
241
/// `tearoff="zone:<selector>"` window. An unparsable selector matches nothing.
242
#[must_use]
243
pub fn nodes_matching_selector(styled_dom: &StyledDom, selector: &str) -> Vec<NodeId> {
244
    let Ok(path) = azul_css::parser2::parse_css_path(selector) else {
245
        return Vec::new();
246
    };
247
    let hierarchy = styled_dom.node_hierarchy.as_container();
248
    let nodes = styled_dom.node_data.as_container();
249
    let cascade = styled_dom.cascade_info.as_container();
250
    (0..nodes.len())
251
        .map(NodeId::new)
252
        .filter(|n| {
253
            azul_core::style::matches_html_element(&path, *n, &hierarchy, &nodes, &cascade, None)
254
        })
255
        .collect()
256
}
257

            
258
/// What the end of a tear-off drag means. Decided from WHERE THE POINTER
259
/// IS, in the parent's coordinates - that is what the user aimed with.
260
#[derive(Debug, Clone, Copy, PartialEq)]
261
pub enum TearDrop {
262
    /// Released over the window's current anchor: it docks back (or stays).
263
    Dock,
264
    /// Released over a drop zone: it docks onto THAT node from now on.
265
    DockOnto(NodeId),
266
    /// Released anywhere else: a free toplevel at `origin` (the window's
267
    /// top-left in parent coordinates).
268
    TearOff(azul_core::geom::LogicalPosition),
269
}
270

            
271
/// Decide a drop. `zone_at` answers "which drop zone, if any, is under this
272
/// point" - the caller hit-tests its zone rects in the parent's layout.
273
#[must_use]
274
3
pub fn decide_drop(
275
3
    cursor: azul_core::geom::LogicalPosition,
276
3
    anchor_rect: LogicalRect,
277
3
    window_origin: azul_core::geom::LogicalPosition,
278
3
    zone_at: impl FnOnce(azul_core::geom::LogicalPosition) -> Option<NodeId>,
279
3
) -> TearDrop {
280
3
    if anchor_rect.contains(cursor) {
281
1
        return TearDrop::Dock;
282
2
    }
283
2
    if let Some(zone) = zone_at(cursor) {
284
1
        return TearDrop::DockOnto(zone);
285
1
    }
286
1
    TearDrop::TearOff(window_origin)
287
3
}
288

            
289
/// The `DomId` under which an open transient window's subtree is laid out.
290
///
291
/// Transient windows are children of the PARENT dom but laid out as roots of
292
/// their own, and the child-dom machinery (`VirtualView`, iframes) keys
293
/// everything by `DomId`. Allocating from a high base keeps these ids clear of
294
/// the ones `VirtualView` hands out from 1 upward, so the two never collide in
295
/// `layout_results`.
296
#[must_use]
297
81
pub const fn transient_dom_id(index: usize) -> DomId {
298
81
    DomId {
299
81
        inner: 0x1000_0000 + index,
300
81
    }
301
81
}
302

            
303
#[cfg(test)]
304
mod tests {
305
    use azul_core::{dom::Dom, geom::LogicalPosition};
306

            
307
    use super::*;
308

            
309
17
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
310
17
        LogicalRect::new(LogicalPosition::new(x, y), LogicalSize::new(w, h))
311
17
    }
312

            
313
    /// Only OPEN transient windows are collected, and each one's anchor is its
314
    /// PARENT's rect — not its own, which has no layout.
315
    #[test]
316
1
    fn only_open_windows_are_collected_and_anchored_to_their_parent() {
317
1
        let dom = Dom::create_body()
318
1
            .with_child(Dom::create_div().with_child(Dom::create_from_data(
319
1
                azul_core::dom::NodeData::create_node(NodeType::TransientWindow(
320
1
                    TransientWindowConfig::opened(),
321
1
                )),
322
            )))
323
1
            .with_child(Dom::create_div().with_child(Dom::create_from_data(
324
1
                azul_core::dom::NodeData::create_node(NodeType::TransientWindow(
325
1
                    TransientWindowConfig::closed(),
326
1
                )),
327
            )));
328
1
        let styled = StyledDom::create_from_dom(dom);
329

            
330
        // Give every node a distinct rect keyed by its index so we can tell
331
        // "anchored to parent" from "anchored to self".
332
4
        let rect_of = |n: NodeId| Some(rect(n.index() as f32 * 100.0, 0.0, 50.0, 20.0));
333
1
        let found = collect_open_transient_windows(&styled, &[], &[], rect_of);
334

            
335
1
        assert_eq!(found.len(), 1, "the closed one must not be returned");
336
1
        let p = &found[0];
337
        // body=0, div=1, transient=2 — the anchor must be the DIV's rect (x=100),
338
        // not the transient node's own (x=200).
339
1
        assert_eq!(
340
            p.anchor_rect.origin.x, 100.0,
341
            "anchored to the parent, not itself"
342
        );
343
1
        assert_eq!(p.anchor, TransientAnchor::Bottom);
344
1
        assert_eq!(p.dismiss, TransientDismiss::Outside);
345

            
346
        // A callback's `set_transient_window_open(node, true)` opens the
347
        // CLOSED one too (body=0, div=1, tw=2, div=3, tw=4) — anchored to
348
        // its own parent (x=300), never to the other popup's.
349
1
        let forced = collect_open_transient_windows(&styled, &[NodeId::new(4)], &[], rect_of);
350
1
        assert_eq!(forced.len(), 2, "attribute-open plus forced-open");
351
1
        assert_eq!(forced[1].node, NodeId::new(4));
352
1
        assert_eq!(forced[1].anchor_rect.origin.x, 300.0);
353
        // Forcing a node that is not a transient window is ignored.
354
1
        let bogus = collect_open_transient_windows(&styled, &[NodeId::new(1)], &[], rect_of);
355
1
        assert_eq!(bogus.len(), 1);
356
1
    }
357

            
358
    /// A popup that would run off the parent flips to the other side when
359
    /// there is room, and is slid back in otherwise.
360
    #[test]
361
1
    fn resolve_within_flips_and_clamps_inside_the_parent() {
362
1
        let mk = |anchor, y| TransientPlacement {
363
5
            node: NodeId::new(0),
364
5
            anchor_rect: rect(700.0, y, 40.0, 20.0),
365
5
            anchor,
366
5
            dismiss: TransientDismiss::Outside,
367
5
            size: OptionLogicalSize::None,
368
5
            tearoff: TransientTearoff::None,
369
            torn: false,
370
5
            material: azul_core::window::WindowBackgroundMaterial::Opaque,
371
5
            dock: TransientDock::Popup,
372
5
        };
373
1
        let size = LogicalSize::new(200.0, 150.0);
374
1
        let bounds = rect(0.0, 0.0, 800.0, 600.0);
375
        // Plenty of room below: unchanged except the x clamp (700+200 > 800).
376
1
        let p = mk(TransientAnchor::Bottom, 100.0).resolve_within(size, None, bounds);
377
1
        assert_eq!((p.x, p.y), (600.0, 120.0));
378
        // Near the bottom: flips to open upward.
379
1
        let p = mk(TransientAnchor::Bottom, 550.0).resolve_within(size, None, bounds);
380
1
        assert_eq!(p.y, 400.0, "flipped above the anchor");
381
        // Near the top with anchor=top: flips to open downward.
382
1
        let p = mk(TransientAnchor::Top, 10.0).resolve_within(size, None, bounds);
383
1
        assert_eq!(p.y, 30.0);
384
        // No room either way: clamped to the bounds.
385
1
        let p = mk(TransientAnchor::Bottom, 590.0).resolve_within(
386
1
            LogicalSize::new(200.0, 700.0),
387
1
            None,
388
1
            bounds,
389
        );
390
1
        assert_eq!(p.y, 0.0);
391
        // Bounds that START above/left of the parent (a monitor around a
392
        // window that sits at (300, 200) on it): a popup may hang below the
393
        // parent's own bottom edge, since the screen continues there.
394
1
        let monitor = rect(-300.0, -200.0, 1920.0, 1080.0);
395
1
        let p = mk(TransientAnchor::Bottom, 550.0).resolve_within(size, None, monitor);
396
1
        assert_eq!(p.y, 570.0, "room on the screen below the window: no flip");
397
1
    }
398

            
399
    /// Placement arithmetic: the popup's top-left for each edge.
400
    #[test]
401
1
    fn resolve_places_the_popup_on_the_requested_edge() {
402
1
        let mk = |anchor| TransientPlacement {
403
6
            node: NodeId::new(0),
404
6
            anchor_rect: rect(100.0, 200.0, 40.0, 20.0),
405
6
            anchor,
406
6
            dismiss: TransientDismiss::Outside,
407
6
            size: OptionLogicalSize::None,
408
6
            tearoff: TransientTearoff::None,
409
            torn: false,
410
6
            material: azul_core::window::WindowBackgroundMaterial::Opaque,
411
6
            dock: TransientDock::Popup,
412
6
        };
413
1
        let popup = LogicalSize::new(300.0, 150.0);
414

            
415
1
        assert_eq!(
416
1
            mk(TransientAnchor::Bottom).resolve(popup, None),
417
1
            LogicalPosition::new(100.0, 220.0)
418
        );
419
1
        assert_eq!(
420
1
            mk(TransientAnchor::Top).resolve(popup, None),
421
1
            LogicalPosition::new(100.0, 50.0)
422
        );
423
1
        assert_eq!(
424
1
            mk(TransientAnchor::Right).resolve(popup, None),
425
1
            LogicalPosition::new(140.0, 200.0)
426
        );
427
1
        assert_eq!(
428
1
            mk(TransientAnchor::Left).resolve(popup, None),
429
1
            LogicalPosition::new(-200.0, 200.0)
430
        );
431
1
        assert_eq!(
432
1
            mk(TransientAnchor::Cursor).resolve(popup, Some(LogicalPosition::new(7.0, 9.0))),
433
1
            LogicalPosition::new(7.0, 9.0)
434
        );
435
1
        assert_eq!(
436
1
            mk(TransientAnchor::Cursor).resolve(popup, None),
437
1
            LogicalPosition::new(100.0, 200.0),
438
            "no cursor: fall back to the anchor corner rather than (0,0)"
439
        );
440
1
    }
441

            
442
    /// Transient dom ids must never collide with the VirtualView ids that
443
    /// count up from 1.
444
    #[test]
445
1
    fn transient_dom_ids_do_not_collide_with_virtual_view_ids() {
446
65
        for i in 0..64 {
447
64
            assert!(transient_dom_id(i).inner >= 0x1000_0000);
448
        }
449
1
        assert_ne!(transient_dom_id(0), transient_dom_id(1));
450
1
    }
451
}
452

            
453
// ============================================================================
454
// The manager: which transient windows are open, and their laid-out content
455
// ============================================================================
456

            
457
/// One open transient window as the ENGINE sees it: where it is anchored,
458
/// what it contains, and how big its content came out.
459
///
460
/// The backend owns the SURFACE (an `xdg_popup`, an `NSPanel`, a `WS_POPUP` hwnd,
461
/// or nothing at all headless); this owns everything the surface displays.
462
/// The split is deliberate — it is what lets one dismiss implementation and
463
/// one layout path serve every platform.
464
#[derive(Debug, Clone, PartialEq)]
465
pub struct OpenTransientWindow {
466
    /// The `<transient-window>` node in the parent DOM that this window IS.
467
    /// Identity: if the parent rebuilds and the same node is still open, the
468
    /// window persists rather than closing and re-opening.
469
    pub source_node: NodeId,
470
    /// The id under which the popup's content is laid out. Stable for the
471
    /// window's lifetime, so `layout_results[content_dom]` is its content.
472
    pub content_dom: DomId,
473
    /// Anchor, edge, dismiss, requested size — from the last parent layout.
474
    pub placement: TransientPlacement,
475
    /// The size the content came out at after its own layout, or the
476
    /// requested size if one was given. What the backend sizes the surface to.
477
    pub content_size: LogicalSize,
478
    /// The backend's handle on the surface — whatever it chooses to keep
479
    /// (the shell keeps the popup window's shared mailbox here). `None` until
480
    /// the backend has acted on `opened`, and always `None` headless. Opaque
481
    /// to this crate on purpose: the engine does not know what a surface is.
482
    pub surface: OptionRefAny,
483
    /// `Some` while the window is TORN OFF into a free toplevel: the
484
    /// toplevel's top-left in the parent's coordinates. `None` = a popup on
485
    /// its anchor.
486
    pub torn: Option<azul_core::geom::LogicalPosition>,
487
    /// The drop zone this window was docked onto, if any: it anchors to
488
    /// that node instead of its parent from then on.
489
    pub anchor_override: Option<NodeId>,
490
    /// The app's `torn` attribute as last seen, so a CHANGE of it can be
491
    /// told from the user's own drags. Bookkeeping, not state a backend reads.
492
    pub attr_torn: bool,
493
}
494

            
495
impl OpenTransientWindow {
496
    /// Laid out INLINE (`dock="inline"`, not torn off): no surface of its
497
    /// own; the subtree is content of its parent or of the zone it was
498
    /// dropped on (see [`TransientDocks`]).
499
    #[must_use]
500
6
    pub fn is_inline(&self) -> bool {
501
6
        self.placement.dock == TransientDock::Inline && self.torn.is_none()
502
6
    }
503
}
504

            
505
/// The docking state of one layout pass: which `<transient-window
506
/// dock="inline">` nodes are laid out inline, and onto which zone each is
507
/// grafted. Built by [`TransientWindowManager::layout_docks`] and handed to
508
/// the layout-tree builder for the duration of the pass
509
/// (`solver3::layout_tree::with_transient_docks`).
510
///
511
/// A node the manager does not know yet (its first layout, before the
512
/// reconcile that opens it) falls back to its config: inline if the config
513
/// says `dock="inline"`, `open`, and not `torn` - so a freshly mounted panel
514
/// is inline on its very first frame instead of one frame late.
515
#[derive(Debug, Clone, Default, PartialEq, Eq)]
516
pub struct TransientDocks {
517
    /// Inline nodes -> the zone they are grafted onto (`None` = laid out in
518
    /// place, as a child of their own DOM parent).
519
    pub inline: alloc::collections::BTreeMap<NodeId, Option<NodeId>>,
520
    /// Every transient node the manager has an opinion about (open ones).
521
    /// A node not in here is judged by its config alone.
522
    pub known: alloc::collections::BTreeSet<NodeId>,
523
}
524

            
525
impl TransientDocks {
526
    /// Is `node` (whose config is `cfg`) laid out inline this pass?
527
    #[must_use]
528
    pub fn is_inline(&self, node: NodeId, cfg: &TransientWindowConfig) -> bool {
529
        if self.known.contains(&node) {
530
            self.inline.contains_key(&node)
531
        } else {
532
            cfg.dock == TransientDock::Inline && cfg.open && !cfg.torn
533
        }
534
    }
535

            
536
    /// Is `node` an inline transient node grafted onto a zone OTHER than
537
    /// `parent` (its DOM parent) - i.e. must `parent` skip it?
538
    #[must_use]
539
    pub fn moved_away_from(&self, node: NodeId, parent: NodeId) -> bool {
540
        matches!(self.inline.get(&node), Some(Some(zone)) if *zone != parent)
541
    }
542

            
543
    /// The inline transient nodes grafted onto `zone` that are not already
544
    /// its DOM children (in dom order, stable across passes).
545
    pub fn grafted_onto<'a>(
546
        &'a self,
547
        zone: NodeId,
548
        styled_dom: &'a StyledDom,
549
    ) -> impl Iterator<Item = NodeId> + 'a {
550
        let hierarchy = styled_dom.node_hierarchy.as_container();
551
        self.inline.iter().filter_map(move |(node, z)| {
552
            if *z != Some(zone) {
553
                return None;
554
            }
555
            let dom_parent = hierarchy
556
                .get(*node)
557
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
558
            (dom_parent != Some(zone)).then_some(*node)
559
        })
560
    }
561
}
562

            
563
/// Tracks the open transient windows across parent layouts.
564
///
565
/// The hard part is CONTINUITY. The parent may rebuild its DOM sixty times a
566
/// second (a resize drag), and each rebuild produces a fresh `StyledDom` with
567
/// fresh node ids. A popup must not close and re-open on every one of those —
568
/// that is the flicker the screenshare fix (d386614cd) chased out of image
569
/// nodes, and it would be far worse on a window. So a window is matched to its
570
/// source node across rebuilds, and only a node that is genuinely gone (or
571
/// `open=false`) tears its window down.
572
#[derive(Debug, Default)]
573
pub struct TransientWindowManager {
574
    open: Vec<OpenTransientWindow>,
575
    /// Monotonic: a content `DomId` is never reused within a window's lifetime,
576
    /// so a stale reference to a closed popup cannot alias a new one.
577
    next_index: usize,
578
    /// Source nodes the USER dismissed (outside click, Escape) whose node may
579
    /// still say `open=true` — the app has not caught up yet, or does not
580
    /// care. Edge-triggered: such a node stays closed until its `open` goes
581
    /// false and true again. Without this a dismissed popup would reopen on
582
    /// the very next parent layout, which is the bug that makes "click
583
    /// outside to close" feel broken.
584
    dismissed: Vec<NodeId>,
585
    /// Surface handles of windows this manager closed on its own (the app
586
    /// set `open=false`, or the node unmounted), waiting for the backend to
587
    /// collect them with [`Self::take_closed_surfaces`] and tear the surfaces
588
    /// down. A dismissal hands its window straight back to the caller instead.
589
    closed_surfaces: Vec<OptionRefAny>,
590
    /// WHERE FOCUS WAS when each popup opened, so closing it can put focus
591
    /// back exactly there.
592
    ///
593
    /// Without this a popup was a one-way trip for the keyboard: you could
594
    /// Tab to a colour swatch and open its picker, but dismissing the picker
595
    /// left focus nowhere, so the next Tab restarted from the top of the
596
    /// document. Kept HERE, at the one seam every popup opens through, so no
597
    /// widget has to remember it (and none can forget).
598
    /// The bool is the opener's `:focus-visible` MODALITY, so a popup opened
599
    /// with Enter/Space hands the ring back too - not a bare, unringed focus.
600
    focus_before_open: Vec<(NodeId, azul_core::dom::DomNodeId, bool)>,
601
    /// A popup the ENGINE closed (Escape, an outside press, the popup
602
    /// dismissing itself) left this focus owed back to the parent.
603
    ///
604
    /// The explicit `set_transient_window_open(node, false)` route hands focus
605
    /// back at its own seam, but a DISMISSAL never reaches it - the widget only
606
    /// hears `Dismissed` and updates its own state - so an Escape used to leave
607
    /// focus (and the ring) nowhere (device report, 2026-09-01). Drained once,
608
    /// by the shell, on the next pass.
609
    pending_focus_restore: Option<(azul_core::dom::DomNodeId, bool)>,
610
    /// Nodes a callback opened with `set_transient_window_open(node, true)`.
611
    /// Held here, node-keyed, so a self-contained widget (the colour picker's
612
    /// swatch) can open its popup without the app threading an `open` flag
613
    /// through its state and layout callback. Cleared by
614
    /// `set_transient_window_open(node, false)` or by a user dismissal.
615
    forced_open: Vec<NodeId>,
616
    /// Bumped whenever the set of inline-docked nodes or their zones may
617
    /// have changed (a drop, a tear-off, a window opening or closing). The
618
    /// layout fast path compares it with the generation it last laid out:
619
    /// an identical DOM whose docking changed must still re-layout.
620
    dock_generation: u64,
621
}
622

            
623
/// What changed between two parent layouts, so the backend knows which
624
/// surfaces to create, move, or destroy. Returned by
625
/// [`TransientWindowManager::reconcile`] and accumulated on the window until
626
/// the backend takes it — a layout call may run several passes (lifecycle
627
/// callbacks re-layout) before the backend looks.
628
#[derive(Debug, Default, PartialEq, Eq)]
629
pub struct TransientDiff {
630
    /// Content dom ids whose window must be CREATED.
631
    pub opened: Vec<DomId>,
632
    /// Content dom ids whose window still exists but moved or resized.
633
    pub moved: Vec<DomId>,
634
    /// Content dom ids whose window must be DESTROYED.
635
    pub closed: Vec<DomId>,
636
    /// Nodes whose window was torn off (`true`) or docked (`false`) by the
637
    /// app's `torn` attribute during this reconcile, with the rect to report
638
    /// (the toplevel's, or the anchor's). The caller fires
639
    /// `TornOff` / `Docked` for them - the same events a user's drag fires.
640
    pub torn_changes: Vec<(NodeId, bool, LogicalRect)>,
641
}
642

            
643
impl TransientDiff {
644
    /// Nothing to do.
645
    #[must_use]
646
20
    pub const fn is_empty(&self) -> bool {
647
20
        self.opened.is_empty()
648
11
            && self.moved.is_empty()
649
9
            && self.closed.is_empty()
650
8
            && self.torn_changes.is_empty()
651
20
    }
652

            
653
    /// Fold a later pass's diff into this one.
654
    ///
655
    /// A window opened and then closed before the backend ever saw it cancels
656
    /// out entirely — creating a surface only to destroy it would flash. A
657
    /// move on a window that is about to be created or destroyed is noise.
658
    pub fn merge(&mut self, later: Self) {
659
        for dom in later.closed {
660
            if let Some(i) = self.opened.iter().position(|d| *d == dom) {
661
                self.opened.remove(i); // never existed as far as the backend knows
662
                self.moved.retain(|d| *d != dom);
663
                continue;
664
            }
665
            self.moved.retain(|d| *d != dom);
666
            if !self.closed.contains(&dom) {
667
                self.closed.push(dom);
668
            }
669
        }
670
        for dom in later.opened {
671
            // Content ids are never reused, so an id in `closed` cannot reopen.
672
            if !self.opened.contains(&dom) {
673
                self.opened.push(dom);
674
            }
675
        }
676
        for dom in later.moved {
677
            if !self.opened.contains(&dom) && !self.moved.contains(&dom) {
678
                self.moved.push(dom);
679
            }
680
        }
681
        self.torn_changes.extend(later.torn_changes);
682
    }
683
}
684

            
685
impl TransientWindowManager {
686
    #[must_use]
687
7589
    pub const fn new() -> Self {
688
7589
        Self {
689
7589
            open: Vec::new(),
690
7589
            next_index: 0,
691
7589
            dismissed: Vec::new(),
692
7589
            closed_surfaces: Vec::new(),
693
7589
            forced_open: Vec::new(),
694
7589
            focus_before_open: Vec::new(),
695
7589
            pending_focus_restore: None,
696
7589
            dock_generation: 0,
697
7589
        }
698
7589
    }
699

            
700
    /// Every currently open window.
701
    #[must_use]
702
40
    pub fn open_windows(&self) -> &[OpenTransientWindow] {
703
40
        &self.open
704
40
    }
705

            
706
    /// The open window whose content is laid out under `dom`, if any.
707
    #[must_use]
708
7
    pub fn get(&self, dom: DomId) -> Option<&OpenTransientWindow> {
709
7
        self.open.iter().find(|w| w.content_dom == dom)
710
7
    }
711

            
712
    /// Mutable access, for the backend to attach its surface handle.
713
    #[must_use]
714
    pub fn get_mut(&mut self, dom: DomId) -> Option<&mut OpenTransientWindow> {
715
        self.open.iter_mut().find(|w| w.content_dom == dom)
716
    }
717

            
718
    /// The USER closed the popup hanging off `source_node` (outside click,
719
    /// Escape). Closes it now and remembers the node as dismissed, so the
720
    /// node's still-`open` attribute does not reopen it on the next pass —
721
    /// only an `open` that goes false and true again can. Returns the window
722
    /// that was closed, so the caller can drop its surface and its layout
723
    /// result and tell the app.
724
    pub fn dismiss(&mut self, source_node: NodeId) -> Option<OpenTransientWindow> {
725
        // The user closed it: a callback's "keep open" is over too.
726
        self.forced_open.retain(|n| *n != source_node);
727
        // A dismissal is a close like any other: it owes focus back to
728
        // whatever opened the popup. Taken HERE so all three dismissal routes
729
        // (Escape in the parent, an outside press, the popup dismissing
730
        // itself) inherit it without each having to remember.
731
        if let Some(restore) = self.take_focus_before_open(source_node) {
732
            self.pending_focus_restore = Some(restore);
733
        }
734
        if !self.dismissed.contains(&source_node) {
735
            self.dismissed.push(source_node);
736
        }
737
        let i = self
738
            .open
739
            .iter()
740
            .position(|w| w.source_node == source_node)?;
741
        self.dock_generation += 1;
742
        Some(self.open.remove(i))
743
    }
744

            
745
    /// Source nodes currently held closed by a user dismissal.
746
    #[must_use]
747
    pub fn dismissed_nodes(&self) -> &[NodeId] {
748
        &self.dismissed
749
    }
750

            
751
    /// Surfaces of windows closed since the backend last asked. Each comes
752
    /// out exactly once.
753
1
    pub fn take_closed_surfaces(&mut self) -> Vec<OptionRefAny> {
754
1
        core::mem::take(&mut self.closed_surfaces)
755
1
    }
756

            
757
    /// A callback asked for `node`'s popup to be open (or closed) regardless
758
    /// of its `open` attribute. Opening also lifts an earlier user dismissal —
759
    /// the user clicked the swatch again, which is the re-arm. Takes effect
760
    /// on the next reconcile. Returns whether anything changed.
761
    pub fn set_forced_open(&mut self, node: NodeId, open: bool) -> bool {
762
        let was = self.forced_open.contains(&node);
763
        if open {
764
            self.dismissed.retain(|n| *n != node);
765
            if !was {
766
                self.forced_open.push(node);
767
            }
768
            !was
769
        } else {
770
            self.forced_open.retain(|n| *n != node);
771
            was
772
        }
773
    }
774

            
775
    /// Remember where focus was as `node`'s popup opens. Overwrites any
776
    /// earlier record for the same node: the latest opening is the one whose
777
    /// focus we owe the user back.
778
    /// `visible` is the opener's `:focus-visible` state, handed back on close.
779
5
    pub fn remember_focus_before_open(
780
5
        &mut self,
781
5
        node: NodeId,
782
5
        focused: azul_core::dom::DomNodeId,
783
5
        visible: bool,
784
5
    ) {
785
5
        self.focus_before_open.retain(|(n, _, _)| *n != node);
786
5
        self.focus_before_open.push((node, focused, visible));
787
5
    }
788

            
789
    /// Take back the focus recorded for `node` (one-shot, so a second close
790
    /// cannot steal focus from wherever the user has since moved it), together
791
    /// with whether it was INDICATED when the popup opened.
792
5
    pub fn take_focus_before_open(
793
5
        &mut self,
794
5
        node: NodeId,
795
5
    ) -> Option<(azul_core::dom::DomNodeId, bool)> {
796
5
        let i = self
797
5
            .focus_before_open
798
5
            .iter()
799
5
            .position(|(n, _, _)| *n == node)?;
800
4
        let (_, focused, visible) = self.focus_before_open.remove(i);
801
4
        Some((focused, visible))
802
5
    }
803

            
804
    /// Focus a dismissal owes back to the parent, if any. One-shot.
805
    pub const fn take_pending_focus_restore(
806
        &mut self,
807
    ) -> Option<(azul_core::dom::DomNodeId, bool)> {
808
        self.pending_focus_restore.take()
809
    }
810

            
811
    /// Nodes currently held open by a callback.
812
    #[must_use]
813
    pub fn forced_open_nodes(&self) -> &[NodeId] {
814
        &self.forced_open
815
    }
816

            
817
    /// Is `dom` one of ours? Lets a dispatcher route a click on a popup surface
818
    /// to the right content without the backend knowing about content ids.
819
    #[must_use]
820
    pub fn is_transient_dom(&self, dom: DomId) -> bool {
821
        self.get(dom).is_some()
822
    }
823

            
824
    /// Bring the open set in line with what the parent's latest layout says.
825
    ///
826
    /// `wanted` is what [`collect_open_transient_windows`] found this pass.
827
    /// `content_size_of` lays out a window's content and reports its extent;
828
    /// it is a closure because layout needs the whole `LayoutWindow` and this
829
    /// struct must not borrow it.
830
    ///
831
    /// Matching is by `source_node`. That is exactly right for a rebuild that
832
    /// preserved structure and exactly wrong for one that reordered siblings —
833
    /// which is the same trade the reconciler already makes for every other
834
    /// per-node state (datasets, images), so a transient window is no more and
835
    /// no less stable than the node it hangs off.
836
16
    pub fn reconcile(
837
16
        &mut self,
838
16
        wanted: &[TransientPlacement],
839
16
        mut content_size_of: impl FnMut(DomId, &TransientPlacement) -> Option<LogicalSize>,
840
16
    ) -> TransientDiff {
841
16
        let mut diff = TransientDiff::default();
842

            
843
        // 0. A dismissed node is re-armed the moment the app stops asking for it (`open=false`);
844
        //    while it still asks, the dismissal wins.
845
16
        self.dismissed
846
16
            .retain(|n| wanted.iter().any(|p| p.node == *n));
847
16
        let wanted: Vec<TransientPlacement> = wanted
848
16
            .iter()
849
16
            .filter(|p| !self.dismissed.contains(&p.node))
850
16
            .copied()
851
16
            .collect();
852

            
853
        // 1. Close anything no longer wanted.
854
16
        let still_wanted = |w: &OpenTransientWindow| wanted.iter().any(|p| p.node == w.source_node);
855
16
        let (keep, close): (Vec<_>, Vec<_>) = core::mem::take(&mut self.open)
856
16
            .into_iter()
857
16
            .partition(still_wanted);
858
17
        for w in close {
859
1
            diff.closed.push(w.content_dom);
860
1
            self.closed_surfaces.push(w.surface);
861
1
        }
862
16
        self.open = keep;
863

            
864
        // 2. Update or open each wanted window.
865
31
        for p in &wanted {
866
15
            if let Some(i) = self.open.iter().position(|w| w.source_node == p.node) {
867
7
                let existing = &mut self.open[i];
868
7
                let moved = existing.placement != *p;
869
7
                existing.placement = *p;
870
                // A popup follows its content's measure. A torn-off toplevel
871
                // keeps the size it was torn off at (its content reflows
872
                // inside; a `width: 100%` panel measures to nothing on its
873
                // own), and an inline panel is sized by its zone's layout.
874
7
                let remeasure = existing.torn.is_none() && !existing.is_inline();
875
7
                if let Some(sz) = if remeasure {
876
6
                    content_size_of(existing.content_dom, p)
877
                } else {
878
1
                    None
879
                } {
880
6
                    if moved || sz != existing.content_size {
881
3
                        existing.content_size = sz;
882
3
                        diff.moved.push(existing.content_dom);
883
3
                    }
884
1
                } else if moved {
885
1
                    diff.moved.push(existing.content_dom);
886
1
                }
887
                // The app flipped `torn`: follow it. Unchanged, the user's
888
                // own drags stand.
889
7
                if p.torn != existing.attr_torn {
890
3
                    existing.attr_torn = p.torn;
891
3
                    let want = p.torn && p.tearoff != TransientTearoff::None;
892
3
                    if want != existing.torn.is_some() {
893
2
                        let origin = p.resolve(existing.content_size, None);
894
2
                        existing.torn = want.then_some(origin);
895
2
                        let bounds = if want {
896
1
                            LogicalRect::new(origin, existing.content_size)
897
                        } else {
898
1
                            p.anchor_rect
899
                        };
900
2
                        let (old, new) = self.recreate(i);
901
2
                        diff.closed.push(old);
902
2
                        diff.opened.push(new);
903
2
                        diff.torn_changes.push((p.node, want, bounds));
904
1
                    }
905
4
                }
906
7
                continue;
907
8
            }
908

            
909
8
            let content_dom = transient_dom_id(self.next_index);
910
8
            self.next_index += 1;
911
8
            let Some(content_size) = content_size_of(content_dom, p) else {
912
1
                continue; // content could not be laid out; do not open onto nothing
913
            };
914
7
            let torn = (p.torn && p.tearoff != TransientTearoff::None)
915
7
                .then(|| p.resolve(content_size, None));
916
7
            self.open.push(OpenTransientWindow {
917
7
                source_node: p.node,
918
7
                content_dom,
919
7
                placement: *p,
920
7
                content_size,
921
7
                surface: OptionRefAny::None,
922
7
                torn,
923
7
                anchor_override: None,
924
7
                attr_torn: p.torn,
925
7
            });
926
7
            diff.opened.push(content_dom);
927
        }
928

            
929
16
        if !diff.is_empty() {
930
12
            self.dock_generation += 1;
931
12
        }
932
16
        diff
933
16
    }
934

            
935
    /// The window at `i` changes KIND (popup <-> toplevel): its surface must
936
    /// be destroyed and a new one created. Gives it a fresh content id - ids
937
    /// are never reused, so the backend sees an ordinary close + open - and
938
    /// hands the old surface to `closed_surfaces`. Returns `(old, new)`.
939
7
    fn recreate(&mut self, i: usize) -> (DomId, DomId) {
940
7
        let w = &mut self.open[i];
941
7
        let old = w.content_dom;
942
7
        let new = transient_dom_id(self.next_index);
943
7
        self.next_index += 1;
944
7
        w.content_dom = new;
945
7
        let surface = core::mem::replace(&mut w.surface, OptionRefAny::None);
946
7
        self.closed_surfaces.push(surface);
947
7
        (old, new)
948
7
    }
949

            
950
    /// The size the window at `source_node` has on screen right now - set
951
    /// by the engine from an INLINE panel's laid-out box before it is torn
952
    /// off, so the toplevel opens at that size instead of a shrink-to-fit
953
    /// measure that means nothing for a `width: 100%` panel.
954
    pub fn set_content_size(&mut self, source_node: NodeId, size: LogicalSize) {
955
        if let Some(w) = self.open.iter_mut().find(|w| w.source_node == source_node) {
956
            w.content_size = size;
957
        }
958
    }
959

            
960
    /// The docking state for the next layout pass (see [`TransientDocks`]).
961
    #[must_use]
962
7588
    pub fn layout_docks(&self) -> TransientDocks {
963
7588
        let mut docks = TransientDocks::default();
964
7588
        for w in &self.open {
965
            docks.known.insert(w.source_node);
966
            if w.is_inline() {
967
                docks.inline.insert(w.source_node, w.anchor_override);
968
            }
969
        }
970
7588
        docks
971
7588
    }
972

            
973
    /// See the `dock_generation` field.
974
    #[must_use]
975
15176
    pub const fn dock_generation(&self) -> u64 {
976
15176
        self.dock_generation
977
15176
    }
978

            
979
    /// `(transient node, zone node)` for every window docked onto a drop
980
    /// zone - what [`collect_open_transient_windows`] anchors them by.
981
    #[must_use]
982
2
    pub fn anchor_overrides(&self) -> Vec<(NodeId, NodeId)> {
983
2
        self.open
984
2
            .iter()
985
2
            .filter_map(|w| w.anchor_override.map(|z| (w.source_node, z)))
986
2
            .collect()
987
2
    }
988

            
989
    /// The user's drag of the window at `source_node` ended as `drop`. Applies
990
    /// it: tears the window off (a popup becomes a toplevel at the drop
991
    /// origin; an already-torn window just moves), docks it back, or docks
992
    /// it onto a zone. Returns the diff to accumulate and whether the
993
    /// window's torn-ness CHANGED (the lifecycle event the caller fires);
994
    /// `None` if no such window is open or it is not tear-off capable.
995
8
    pub fn apply_drop(
996
8
        &mut self,
997
8
        source_node: NodeId,
998
8
        drop: TearDrop,
999
8
    ) -> Option<(TransientDiff, bool)> {
8
        let i = self
8
            .open
8
            .iter()
8
            .position(|w| w.source_node == source_node)?;
8
        if self.open[i].placement.tearoff == TransientTearoff::None {
1
            return None;
7
        }
7
        let mut diff = TransientDiff::default();
7
        self.dock_generation += 1;
7
        let was_torn = self.open[i].torn.is_some();
7
        match drop {
3
            TearDrop::TearOff(origin) => {
3
                self.open[i].torn = Some(origin);
3
            }
3
            TearDrop::Dock => {
3
                self.open[i].torn = None;
3
            }
1
            TearDrop::DockOnto(zone) => {
1
                self.open[i].torn = None;
1
                self.open[i].anchor_override = Some(zone);
1
            }
        }
        // Same kind (a torn window moved, a docked one released back on an
        // anchor): the surface is kept; a changed anchor re-places it on the
        // next reconcile.
7
        let changed = was_torn != self.open[i].torn.is_some();
7
        if changed {
5
            let (old, new) = self.recreate(i);
5
            diff.closed.push(old);
5
            diff.opened.push(new);
5
        }
7
        Some((diff, changed))
8
    }
    /// A callback's `set_transient_window_torn(node, torn)`: the same as the
    /// app flipping the `torn` attribute, without waiting for a layout.
    pub fn set_torn(&mut self, source_node: NodeId, torn: bool) -> Option<(TransientDiff, bool)> {
        let w = self.open.iter().find(|w| w.source_node == source_node)?;
        let drop = if torn {
            TearDrop::TearOff(
                w.torn
                    .unwrap_or_else(|| w.placement.resolve(w.content_size, None)),
            )
        } else {
            TearDrop::Dock
        };
        self.apply_drop(source_node, drop)
    }
    /// Close everything — the parent window is going away.
    pub fn close_all(&mut self) -> Vec<DomId> {
        self.dock_generation += 1;
        core::mem::take(&mut self.open)
            .into_iter()
            .map(|w| {
                self.closed_surfaces.push(w.surface);
                w.content_dom
            })
            .collect()
    }
}
/// A popup is keyed by the node it hangs off, and node ids are arena indices
/// that shift when the parent rebuilds. Without this the popup would point at
/// a live but WRONG node after any rebuild that inserted or removed a sibling
/// above it — and `LayoutWindow`'s remap destructure refuses to compile until
/// every node-keyed manager is listed, which is how this impl came to exist.
///
/// A source node that is UNMOUNTED by the rebuild drops its window: the thing
/// it was anchored to is gone, so there is nothing for the popup to belong to.
// `managers` (the trait's home) is `text_layout`-gated; without it there is no
// remap machinery to implement against (e.g. the no-default-features ICU build).
#[cfg(feature = "text_layout")]
impl crate::managers::NodeIdRemap for TransientWindowManager {
446
    fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
446
        if dom != DomId::ROOT_ID {
420
            return; // transient windows hang off the parent (root) dom only
26
        }
26
        let mut unmounted = Vec::new();
26
        self.open.retain_mut(|w| {
            if let Some(new_id) = map.resolve(w.source_node) {
                w.source_node = new_id;
                w.placement.node = new_id;
                // A zone that unmounted is no anchor; back to the parent.
                w.anchor_override = w.anchor_override.and_then(|z| map.resolve(z));
                true
            } else {
                unmounted.push(core::mem::replace(&mut w.surface, OptionRefAny::None));
                false
            }
        });
26
        self.closed_surfaces.extend(unmounted);
        // A dismissal follows its node too; an unmounted node's is moot.
26
        self.dismissed = self
26
            .dismissed
26
            .iter()
26
            .filter_map(|n| map.resolve(*n))
26
            .collect();
26
        self.forced_open = self
26
            .forced_open
26
            .iter()
26
            .filter_map(|n| map.resolve(*n))
26
            .collect();
        // Focus owed back follows its nodes too - both the popup that
        // remembered it and the node the focus goes to (which lives in this
        // same root dom).
26
        let remap_target = |t: &azul_core::dom::DomNodeId| {
            if t.dom != DomId::ROOT_ID {
                return Some(*t);
            }
            let old = t.node.into_crate_internal()?;
            let new = map.resolve(old)?;
            Some(azul_core::dom::DomNodeId {
                dom: t.dom,
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(new)),
            })
        };
26
        self.focus_before_open = self
26
            .focus_before_open
26
            .iter()
26
            .filter_map(|(n, t, v)| Some((map.resolve(*n)?, remap_target(t)?, *v)))
26
            .collect();
26
        self.pending_focus_restore = self
26
            .pending_focus_restore
26
            .and_then(|(t, v)| Some((remap_target(&t)?, v)));
446
    }
}
#[cfg(test)]
mod manager_tests {
    use azul_core::geom::LogicalPosition;
    use super::*;
15
    fn placement(node: usize, x: f32) -> TransientPlacement {
15
        TransientPlacement {
15
            node: NodeId::new(node),
15
            anchor_rect: LogicalRect::new(
15
                LogicalPosition::new(x, 0.0),
15
                LogicalSize::new(10.0, 10.0),
15
            ),
15
            anchor: TransientAnchor::Bottom,
15
            dismiss: TransientDismiss::Outside,
15
            size: OptionLogicalSize::None,
15
            tearoff: TransientTearoff::None,
15
            torn: false,
15
            material: azul_core::window::WindowBackgroundMaterial::Opaque,
15
            dock: TransientDock::Popup,
15
        }
15
    }
13
    fn sized(_: DomId, _: &TransientPlacement) -> Option<LogicalSize> {
13
        Some(LogicalSize::new(100.0, 50.0))
13
    }
    /// THE property this exists for: a window that is still wanted after a
    /// parent rebuild keeps its content dom — it is not closed and re-opened.
    #[test]
1
    fn a_still_open_window_survives_a_rebuild_without_reopening() {
1
        let mut m = TransientWindowManager::new();
1
        let d1 = m.reconcile(&[placement(4, 0.0)], sized);
1
        assert_eq!(d1.opened.len(), 1);
1
        let id = d1.opened[0];
        // Same node, same place: nothing happens.
1
        let d2 = m.reconcile(&[placement(4, 0.0)], sized);
1
        assert_eq!(
            d2,
1
            TransientDiff::default(),
            "nothing changed, nothing to do"
        );
1
        assert_eq!(m.get(id).map(|w| w.source_node), Some(NodeId::new(4)));
        // Same node, anchor moved (the parent was resized): MOVED, not re-opened.
1
        let d3 = m.reconcile(&[placement(4, 50.0)], sized);
1
        assert_eq!(d3.moved, vec![id]);
1
        assert!(d3.opened.is_empty() && d3.closed.is_empty());
1
    }
    /// A node that stops being open closes its window, and a new open node
    /// gets a FRESH id — never a recycled one.
    #[test]
1
    fn closing_and_reopening_never_reuses_an_id() {
1
        let mut m = TransientWindowManager::new();
1
        let first = m.reconcile(&[placement(4, 0.0)], sized).opened[0];
1
        let d = m.reconcile(&[], sized);
1
        assert_eq!(d.closed, vec![first]);
1
        assert!(m.open_windows().is_empty());
1
        let second = m.reconcile(&[placement(4, 0.0)], sized).opened[0];
1
        assert_ne!(
            first, second,
            "a stale handle to the old popup must not alias the new one"
        );
1
    }
    /// Content that cannot be laid out does not open a window.
    #[test]
1
    fn unlayoutable_content_does_not_open() {
1
        let mut m = TransientWindowManager::new();
1
        let d = m.reconcile(&[placement(4, 0.0)], |_, _| None);
1
        assert!(d.opened.is_empty());
1
        assert!(m.open_windows().is_empty());
1
    }
7
    fn tearable(node: usize) -> TransientPlacement {
7
        TransientPlacement {
7
            tearoff: TransientTearoff::Free,
7
            ..placement(node, 0.0)
7
        }
7
    }
    #[test]
1
    fn a_drop_off_the_anchor_tears_off_with_a_fresh_id_and_back_on_it_docks() {
1
        let mut m = TransientWindowManager::new();
1
        let d = m.reconcile(&[tearable(4)], sized);
1
        let popup = d.opened[0];
1
        assert!(m.get(popup).unwrap().torn.is_none());
        // Off the anchor: a toplevel at the drop origin, under a NEW id (the
        // backend sees close + open, never a popup that changes shape).
1
        let (d, changed) = m
1
            .apply_drop(
1
                NodeId::new(4),
1
                TearDrop::TearOff(LogicalPosition::new(300.0, 40.0)),
1
            )
1
            .unwrap();
1
        assert!(changed);
1
        assert_eq!(d.closed, vec![popup]);
1
        assert_eq!(d.opened.len(), 1);
1
        let top = d.opened[0];
1
        assert_ne!(top, popup);
1
        assert!(m.get(popup).is_none(), "the old id is gone");
1
        assert_eq!(
1
            m.get(top).unwrap().torn,
1
            Some(LogicalPosition::new(300.0, 40.0))
        );
1
        assert_eq!(
1
            m.take_closed_surfaces().len(),
            1,
            "the popup's surface is handed back"
        );
        // A torn window dropped elsewhere just moves: same id, no diff.
1
        let (d, changed) = m
1
            .apply_drop(
1
                NodeId::new(4),
1
                TearDrop::TearOff(LogicalPosition::new(10.0, 10.0)),
1
            )
1
            .unwrap();
1
        assert!(!changed);
1
        assert!(d.is_empty());
1
        assert_eq!(
1
            m.get(top).unwrap().torn,
1
            Some(LogicalPosition::new(10.0, 10.0))
        );
        // Back over the anchor: a popup again, again under a fresh id.
1
        let (d, changed) = m.apply_drop(NodeId::new(4), TearDrop::Dock).unwrap();
1
        assert!(changed);
1
        assert_eq!(d.closed, vec![top]);
1
        let popup2 = d.opened[0];
1
        assert!(popup2 != top && popup2 != popup);
1
        assert!(m.get(popup2).unwrap().torn.is_none());
        // A rebuild keeps it: still one window, still the same id.
1
        let d = m.reconcile(&[tearable(4)], sized);
1
        assert!(d.is_empty());
1
        assert_eq!(m.open_windows().len(), 1);
1
        assert_eq!(m.open_windows()[0].content_dom, popup2);
1
    }
    #[test]
1
    fn a_window_without_tearoff_ignores_drops() {
1
        let mut m = TransientWindowManager::new();
1
        m.reconcile(&[placement(4, 0.0)], sized);
1
        assert!(m
1
            .apply_drop(NodeId::new(4), TearDrop::TearOff(LogicalPosition::zero()))
1
            .is_none());
1
        assert!(m.open_windows()[0].torn.is_none());
1
    }
    #[test]
1
    fn the_torn_attribute_is_followed_on_change_and_the_users_drag_stands_otherwise() {
1
        let mut m = TransientWindowManager::new();
1
        let torn_attr = |torn: bool| TransientPlacement {
5
            torn,
5
            ..tearable(4)
5
        };
        // Opens torn when the app says so, at the anchor position.
1
        let d = m.reconcile(&[torn_attr(true)], sized);
1
        let first = d.opened[0];
1
        let w = m.get(first).unwrap();
1
        assert_eq!(w.torn, Some(w.placement.resolve(w.content_size, None)));
        // The attribute stays true while the user docks it: the dock stands.
1
        let (_, changed) = m.apply_drop(NodeId::new(4), TearDrop::Dock).unwrap();
1
        assert!(changed);
1
        let d = m.reconcile(&[torn_attr(true)], sized);
1
        assert!(d.is_empty(), "unchanged attribute must not re-tear");
1
        assert!(m.open_windows()[0].torn.is_none());
        // The attribute flipping false->true tears it off again.
1
        m.reconcile(&[torn_attr(false)], sized);
1
        let d = m.reconcile(&[torn_attr(true)], sized);
1
        assert_eq!(d.closed.len(), 1);
1
        assert_eq!(d.opened.len(), 1);
1
        assert!(m.open_windows()[0].torn.is_some());
        // And true->false docks it.
1
        let d = m.reconcile(&[torn_attr(false)], sized);
1
        assert_eq!(d.closed.len(), 1);
1
        assert!(m.open_windows()[0].torn.is_none());
1
    }
    #[test]
1
    fn docking_onto_a_zone_re_anchors_and_survives_remaps() {
1
        let mut m = TransientWindowManager::new();
1
        m.reconcile(
1
            &[TransientPlacement {
1
                tearoff: TransientTearoff::Zone,
1
                ..placement(4, 0.0)
1
            }],
            sized,
        );
1
        let (d, changed) = m
1
            .apply_drop(NodeId::new(4), TearDrop::DockOnto(NodeId::new(9)))
1
            .unwrap();
1
        assert!(!changed, "popup to popup: same kind, the surface is kept");
1
        assert!(d.is_empty());
1
        assert_eq!(m.anchor_overrides(), vec![(NodeId::new(4), NodeId::new(9))]);
        // Torn off from the zone and docked back onto the anchor it has now.
1
        m.apply_drop(NodeId::new(4), TearDrop::TearOff(LogicalPosition::zero()))
1
            .unwrap();
1
        m.apply_drop(NodeId::new(4), TearDrop::Dock).unwrap();
1
        assert_eq!(
1
            m.anchor_overrides(),
1
            vec![(NodeId::new(4), NodeId::new(9))],
            "Dock keeps the zone"
        );
1
    }
    #[test]
1
    fn decide_drop_prefers_the_anchor_then_a_zone_then_tears_off() {
1
        let anchor = LogicalRect::new(
1
            LogicalPosition::new(10.0, 10.0),
1
            LogicalSize::new(50.0, 20.0),
        );
2
        let zone_at = |p: LogicalPosition| (p.x > 200.0).then_some(NodeId::new(7));
1
        let origin = LogicalPosition::new(400.0, 400.0);
1
        assert_eq!(
1
            decide_drop(LogicalPosition::new(20.0, 20.0), anchor, origin, zone_at),
            TearDrop::Dock
        );
1
        assert_eq!(
1
            decide_drop(LogicalPosition::new(250.0, 20.0), anchor, origin, zone_at),
1
            TearDrop::DockOnto(NodeId::new(7))
        );
1
        assert_eq!(
1
            decide_drop(LogicalPosition::new(100.0, 100.0), anchor, origin, zone_at),
1
            TearDrop::TearOff(origin)
        );
1
    }
}
#[cfg(test)]
mod focus_return_tests {
    use azul_core::{
        dom::{DomId, DomNodeId, NodeId},
        styled_dom::NodeHierarchyItemId,
    };
    use super::TransientWindowManager;
9
    fn dnid(n: usize) -> DomNodeId {
9
        DomNodeId {
9
            dom: DomId::ROOT_ID,
9
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(n))),
9
        }
9
    }
    /// A popup must be a ROUND TRIP for the keyboard: closing it puts focus
    /// back exactly where it was when it opened (2026-09-01 request - open a
    /// colour picker from a swatch, dismiss it, and land back on the swatch).
    #[test]
1
    fn a_popup_returns_focus_to_wherever_it_was_opened_from() {
1
        let mut m = TransientWindowManager::new();
1
        let popup = NodeId::new(7);
1
        m.remember_focus_before_open(popup, dnid(3), true);
1
        assert_eq!(
1
            m.take_focus_before_open(popup),
1
            Some((dnid(3), true)),
            "closing must hand back the node focus came from",
        );
        // ONE-SHOT: a second close must not yank focus away from wherever the
        // user has since moved it.
1
        assert_eq!(m.take_focus_before_open(popup), None);
1
    }
    /// Reopening records the LATEST origin - that is the focus we owe back.
    #[test]
1
    fn reopening_a_popup_overwrites_the_remembered_origin() {
1
        let mut m = TransientWindowManager::new();
1
        let popup = NodeId::new(7);
1
        m.remember_focus_before_open(popup, dnid(3), false);
1
        m.remember_focus_before_open(popup, dnid(9), true);
1
        assert_eq!(m.take_focus_before_open(popup), Some((dnid(9), true)));
1
    }
    /// Two popups do not cross their records.
    #[test]
1
    fn each_popup_remembers_its_own_origin() {
1
        let mut m = TransientWindowManager::new();
1
        m.remember_focus_before_open(NodeId::new(1), dnid(10), true);
1
        m.remember_focus_before_open(NodeId::new(2), dnid(20), false);
1
        assert_eq!(
1
            m.take_focus_before_open(NodeId::new(2)),
1
            Some((dnid(20), false))
        );
1
        assert_eq!(
1
            m.take_focus_before_open(NodeId::new(1)),
1
            Some((dnid(10), true))
        );
1
    }
}