Skip to main content

leptos_node_graph/
overlay.rs

1//! Node-anchored overlays.
2//!
3//! A panel rendered inside a node body can't escape two things on its own:
4//!
5//! 1. The node's `overflow: hidden` clips any absolutely-positioned child to the
6//!    node box.
7//! 2. The canvas carries `transform: translate() scale()`, and a transformed
8//!    ancestor is the containing block for `position: fixed` descendants — so a
9//!    fixed panel is offset by the pan and scaled by the zoom instead of being
10//!    positioned against the viewport. (At pan 0,0 / zoom 1 it looks correct,
11//!    which is how this tends to survive review.)
12//!
13//! [`NodeOverlay`] solves both by portalling its children into a layer that
14//! `NodeEditor` renders inside the graph pane but OUTSIDE the transformed
15//! canvas. Content is therefore unscaled and positioned in pane space, while
16//! still being clipped by the graph's own box rather than escaping to a global
17//! layer.
18//!
19//! ```ignore
20//! // In a node body — mount the overlay to open it, unmount to close.
21//! let open = RwSignal::new(false);
22//! view! {
23//!     <button data-curve-trigger on:click=move |_| open.set(true)>"✎"</button>
24//!     <Show when=move || open.get()>
25//!         <NodeOverlay
26//!             anchor=OverlayAnchor::Selector("[data-curve-trigger]".into())
27//!             side=OverlaySide::Right
28//!             on_dismiss=Callback::new(move |_| open.set(false))
29//!         >
30//!             <CurveEditor />
31//!         </NodeOverlay>
32//!     </Show>
33//! }
34//! ```
35
36use std::sync::{
37    Arc,
38    atomic::{AtomicBool, Ordering},
39};
40
41use leptos::portal::Portal;
42use leptos::prelude::*;
43use leptos::wasm_bindgen::JsCast;
44use leptos_use::use_event_listener;
45
46use crate::node::NodeElement;
47use crate::types::{Rect, ViewportTransform};
48
49/// Mount point for node-anchored overlays, provided by `NodeEditor`.
50///
51/// The mount element sits inside the graph pane but outside the transformed
52/// canvas, so children render unscaled and are clipped at the pane boundary.
53#[derive(Clone, Copy)]
54pub struct NodeOverlayLayer {
55    /// The layer element overlays are portalled into.
56    pub mount: NodeRef<leptos::html::Div>,
57    /// The live canvas transform. Overlays re-place when this changes, so they
58    /// track their anchor across pan and zoom.
59    pub viewport: Signal<ViewportTransform>,
60}
61
62/// What a [`NodeOverlay`] positions itself against.
63#[derive(Clone, Default)]
64pub enum OverlayAnchor {
65    /// The enclosing node's root element. Requires being rendered inside a
66    /// `Node` (which provides [`NodeElement`]).
67    #[default]
68    Node,
69    /// An element within the enclosing node, by CSS selector — e.g. the trigger
70    /// button that opened the overlay: `"[data-curve-trigger]"`.
71    Selector(String),
72    /// An element resolved on demand. Build with [`OverlayAnchor::element`].
73    Element(Arc<dyn Fn() -> Option<web_sys::Element> + Send + Sync>),
74    /// A fixed rect in pane space (pixels from the graph container's top-left).
75    Pane(Rect),
76}
77
78impl OverlayAnchor {
79    /// Anchor to whatever element a `NodeRef` holds, of any element type.
80    pub fn element<E>(node_ref: NodeRef<E>) -> Self
81    where
82        E: leptos::html::ElementType + 'static,
83        E::Output: JsCast + Clone + 'static,
84    {
85        Self::Element(Arc::new(move || {
86            node_ref
87                .get()
88                .map(|el| el.unchecked_into::<web_sys::Element>())
89        }))
90    }
91}
92
93/// Which side of the anchor the overlay sits on.
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
95pub enum OverlaySide {
96    #[default]
97    Right,
98    Left,
99    Top,
100    Bottom,
101}
102
103/// How the overlay lines up along the anchor's cross axis.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
105pub enum OverlayAlign {
106    #[default]
107    Start,
108    Center,
109    End,
110}
111
112/// A rect in pane space: pixels from the graph container's top-left, unscaled.
113#[derive(Clone, Copy, Debug, Default)]
114struct PaneRect {
115    x: f64,
116    y: f64,
117    w: f64,
118    h: f64,
119}
120
121/// A panel anchored to a node (or to an element inside one), rendered at the
122/// graph-pane level so it escapes the node's clipping and the canvas transform.
123///
124/// Mount it to open and unmount it to close — there is no `open` prop, so the
125/// caller keeps full control (and the children's reactive owner is only alive
126/// while the panel is). `on_dismiss` fires on a pointerdown outside the panel
127/// and on Escape; acting on it is the caller's choice.
128///
129/// See the [module docs](self) for why this exists.
130#[component]
131pub fn NodeOverlay(
132    /// What to position against. Defaults to the enclosing node.
133    #[prop(optional)]
134    anchor: OverlayAnchor,
135    #[prop(optional)] side: OverlaySide,
136    #[prop(optional)] align: OverlayAlign,
137    /// Gap between anchor and panel, in unscaled pixels.
138    #[prop(default = 8.0)]
139    offset: f64,
140    /// Flip to the opposite side when the panel doesn't fit, then shift it to
141    /// stay inside the pane.
142    #[prop(default = true)]
143    keep_in_view: bool,
144    /// Re-place every frame, so the panel follows its anchor through node drags
145    /// and content reflow. Pan and zoom are tracked either way.
146    #[prop(default = true)]
147    track_anchor: bool,
148    /// Render a transparent click-catching backdrop over the pane, which fires
149    /// `on_dismiss` when clicked.
150    #[prop(optional)]
151    backdrop: bool,
152    /// Fired on a pointerdown outside the panel, and on Escape.
153    #[prop(optional, into)]
154    on_dismiss: Option<Callback<()>>,
155    /// Extra style on the panel wrapper (e.g. `"width: 320px;"`).
156    #[prop(optional, into)]
157    style: Option<String>,
158    children: ChildrenFn,
159) -> impl IntoView {
160    let Some(layer) = use_context::<NodeOverlayLayer>() else {
161        leptos::logging::warn!(
162            "<NodeOverlay> rendered outside a <NodeEditor>; nothing will be shown"
163        );
164        return ().into_any();
165    };
166    let node_el = use_context::<NodeElement>();
167
168    let panel_ref = NodeRef::<leptos::html::Div>::new();
169    // `None` until the first placement, so the panel never flashes at 0,0.
170    let placement = RwSignal::new(None::<(f64, f64)>);
171
172    let anchor = Arc::new(anchor);
173    let anchor_for_place = Arc::clone(&anchor);
174    let extra_style = style.unwrap_or_default();
175
176    // Resolve the anchor to a rect in pane space.
177    let resolve_anchor = move |layer_el: &web_sys::Element| -> Option<PaneRect> {
178        let lr = layer_el.get_bounding_client_rect();
179        let from_element = |el: web_sys::Element| {
180            let r = el.get_bounding_client_rect();
181            PaneRect {
182                x: r.left() - lr.left(),
183                y: r.top() - lr.top(),
184                w: r.width(),
185                h: r.height(),
186            }
187        };
188        match anchor_for_place.as_ref() {
189            OverlayAnchor::Node => node_el
190                .and_then(|n| n.0.get_untracked())
191                .map(|el| from_element(el.unchecked_into())),
192            OverlayAnchor::Selector(sel) => node_el
193                .and_then(|n| n.0.get_untracked())
194                .and_then(|el| {
195                    el.unchecked_into::<web_sys::Element>()
196                        .query_selector(sel)
197                        .ok()
198                        .flatten()
199                })
200                .map(from_element),
201            OverlayAnchor::Element(get) => get().map(from_element),
202            OverlayAnchor::Pane(rect) => Some(PaneRect {
203                x: rect.position.x,
204                y: rect.position.y,
205                w: rect.size.width,
206                h: rect.size.height,
207            }),
208        }
209    };
210
211    let place = move || {
212        let Some(layer_el) = layer.mount.get_untracked() else {
213            return;
214        };
215        let layer_el: web_sys::Element = layer_el.unchecked_into();
216        let Some(a) = resolve_anchor(&layer_el) else {
217            return;
218        };
219        let Some(panel) = panel_ref.get_untracked() else {
220            return;
221        };
222
223        let lr = layer_el.get_bounding_client_rect();
224        let (pane_w, pane_h) = (lr.width(), lr.height());
225        let (pw, ph) = (panel.offset_width() as f64, panel.offset_height() as f64);
226
227        let cross = |start: f64, extent: f64, size: f64| match align {
228            OverlayAlign::Start => start,
229            OverlayAlign::Center => start + (extent - size) / 2.0,
230            OverlayAlign::End => start + extent - size,
231        };
232
233        let main = |side: OverlaySide| match side {
234            OverlaySide::Right => (a.x + a.w + offset, cross(a.y, a.h, ph)),
235            OverlaySide::Left => (a.x - offset - pw, cross(a.y, a.h, ph)),
236            OverlaySide::Bottom => (cross(a.x, a.w, pw), a.y + a.h + offset),
237            OverlaySide::Top => (cross(a.x, a.w, pw), a.y - offset - ph),
238        };
239
240        let (mut x, mut y) = main(side);
241
242        if keep_in_view {
243            // Flip to the opposite side only if that side actually has room —
244            // otherwise the shift below is the better of two bad options.
245            let overflows = match side {
246                OverlaySide::Right => x + pw > pane_w,
247                OverlaySide::Left => x < 0.0,
248                OverlaySide::Bottom => y + ph > pane_h,
249                OverlaySide::Top => y < 0.0,
250            };
251            if overflows {
252                let opposite = match side {
253                    OverlaySide::Right => OverlaySide::Left,
254                    OverlaySide::Left => OverlaySide::Right,
255                    OverlaySide::Bottom => OverlaySide::Top,
256                    OverlaySide::Top => OverlaySide::Bottom,
257                };
258                let (fx, fy) = main(opposite);
259                let fits = match opposite {
260                    OverlaySide::Right => fx + pw <= pane_w,
261                    OverlaySide::Left => fx >= 0.0,
262                    OverlaySide::Bottom => fy + ph <= pane_h,
263                    OverlaySide::Top => fy >= 0.0,
264                };
265                if fits {
266                    (x, y) = (fx, fy);
267                }
268            }
269            // Shift into the pane. A panel larger than the pane pins to the
270            // top-left rather than being pushed off the other edge.
271            x = x.min(pane_w - pw).max(0.0);
272            y = y.min(pane_h - ph).max(0.0);
273        }
274
275        // Skip no-op writes: this runs every frame while tracking.
276        if placement.get_untracked() != Some((x, y)) {
277            placement.set(Some((x, y)));
278        }
279    };
280
281    let place: Arc<dyn Fn() + Send + Sync> = Arc::new(place);
282
283    // Place on mount and whenever the canvas transform changes, so pan and zoom
284    // are tracked without depending on animation frames.
285    let place_vp = Arc::clone(&place);
286    Effect::new(move || {
287        let _ = layer.viewport.get();
288        let _ = panel_ref.get();
289        place_vp();
290    });
291
292    // Everything else the panel should follow — node drags, resizes, content
293    // reflow — is caught by re-placing each frame.
294    if track_anchor {
295        let state = Arc::new(AtomicBool::new(true));
296        let cleanup_state = state.clone();
297        on_cleanup(move || cleanup_state.store(false, Ordering::Relaxed));
298
299        fn tick(f: Arc<dyn Fn() + Send + Sync>, state: Arc<AtomicBool>) {
300            if !state.load(Ordering::Relaxed) {
301                return;
302            }
303            f();
304            crate::raf::request_animation_frame(move || tick(f, state));
305        }
306        tick(place, state);
307    }
308
309    // Dismissal: a pointerdown that lands outside the panel, or Escape.
310    if let Some(on_dismiss) = on_dismiss {
311        let _ = use_event_listener(
312            leptos::prelude::document(),
313            leptos::ev::pointerdown,
314            move |ev: web_sys::PointerEvent| {
315                let Some(panel) = panel_ref.get_untracked() else {
316                    return;
317                };
318                let inside = ev
319                    .target()
320                    .and_then(|t| t.dyn_into::<web_sys::Node>().ok())
321                    .is_some_and(|n| panel.contains(Some(&n)));
322                if !inside {
323                    on_dismiss.run(());
324                }
325            },
326        );
327
328        let _ = use_event_listener(
329            leptos::prelude::document(),
330            leptos::ev::keydown,
331            move |ev: web_sys::KeyboardEvent| {
332                if ev.key() == "Escape" {
333                    on_dismiss.run(());
334                }
335            },
336        );
337    }
338
339    // A Signal (not a closure): the view below can re-run, so this has to be
340    // Copy rather than move-once.
341    let panel_style = Signal::derive(move || {
342        let placed = placement.get();
343        let (x, y) = placed.unwrap_or((0.0, 0.0));
344        // Hidden until placed, so it never paints in the wrong spot first.
345        let vis = if placed.is_some() {
346            ""
347        } else {
348            "visibility: hidden;"
349        };
350        format!(
351            "position: absolute; left: {x}px; top: {y}px; pointer-events: auto; \
352             {vis} {extra_style}"
353        )
354    });
355
356    let backdrop_view = backdrop.then(|| {
357        let dismiss = on_dismiss;
358        view! {
359            <div
360                data-node-overlay-backdrop=""
361                style="position: absolute; inset: 0; pointer-events: auto;"
362                on:pointerdown=move |_| {
363                    if let Some(cb) = dismiss {
364                        cb.run(());
365                    }
366                }
367            />
368        }
369    });
370
371    view! {
372        {move || {
373            layer.mount.get().map(|mount_el| {
374                let mount_el: web_sys::Element = mount_el.unchecked_into();
375                let children = children.clone();
376                let backdrop_view = backdrop_view.clone();
377                view! {
378                    <Portal mount=mount_el>
379                        {backdrop_view.clone()}
380                        <div data-node-overlay="" node_ref=panel_ref style=panel_style>
381                            {children()}
382                        </div>
383                    </Portal>
384                }
385            })
386        }}
387    }
388    .into_any()
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    #[test]
396    fn animation_loop_state_survives_owner_cleanup() {
397        let owner = Owner::new();
398        let state = Arc::new(AtomicBool::new(true));
399        let cleanup_state = state.clone();
400        owner.with(|| on_cleanup(move || cleanup_state.store(false, Ordering::Relaxed)));
401
402        owner.cleanup();
403
404        assert!(!state.load(Ordering::Relaxed));
405    }
406}