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