Skip to main content

adam_web_ui/graph/
view.rs

1//! [`GraphView`] — renders the D3 force graph inside a `<div>`.
2//!
3//! Mount [`GraphView`] with a container id, graph-data signal and source id.
4//! Ordinary data updates preserve layout. Source/container changes retire the
5//! old evaluation channel and initialize a fresh graph; unmount cancels both
6//! Rust reception and JS polling/subscriptions. The shared component owns this
7//! lifecycle on desktop and web, independently of any Begin-only integration.
8//! D3 submits geometry and absolute gesture proposals; only Adam-approved
9//! frames reach the visible zoom layer.
10
11use std::{
12    cell::RefCell,
13    future::{Future, poll_fn},
14    pin::Pin,
15    rc::Rc,
16    task::Poll,
17};
18
19use dioxus::core::Task;
20use dioxus::prelude::*;
21
22use super::{BridgeState, data::GraphData};
23
24/// Owns the Rust receiver and its matching cancellable JavaScript evaluation.
25struct ChannelSession {
26    /// An identity retained by one-shot updates to reject delayed old failures.
27    identity: Rc<()>,
28    /// The live bidirectional evaluation.
29    eval: document::Eval,
30    /// The component-scoped Rust receiver.
31    task: Task,
32}
33
34/// Returns whether a one-shot update still belongs to the current channel owner.
35fn same_owner(current: Option<&Rc<()>>, expected: Option<&Rc<()>>) -> bool {
36    match (current, expected) {
37        (Some(current), Some(expected)) => Rc::ptr_eq(current, expected),
38        (None, None) => true,
39        _ => false,
40    }
41}
42
43/// Selects a message before channel completion when both are ready.
44///
45/// A pending message never hides a completed/failed evaluation. This preserves
46/// queued diagnostics while preventing a broken JS sender from hanging Rust.
47async fn prefer_message<M: Future, E: Future>(
48    message: M,
49    mut ended: Pin<&mut E>,
50) -> Result<M::Output, E::Output> {
51    let mut message = std::pin::pin!(message);
52    poll_fn(|context| {
53        if let Poll::Ready(message) = message.as_mut().poll(context) {
54            return Poll::Ready(Ok(message));
55        }
56        ended.as_mut().poll(context).map(Err)
57    })
58    .await
59}
60
61impl ChannelSession {
62    /// Closes JS polling/subscriptions/resources before aborting the Rust receiver.
63    fn stop(self) {
64        let _ = self.eval.send(serde_json::json!({ "kind": "close" }));
65        self.task.cancel();
66    }
67}
68
69/// Embeds the tested shared channel runtime and safely encoded initial arguments.
70///
71/// - Complexity: O(n) time and space in serialized graph data.
72fn graph_channel_script(container_id: &str, data: &GraphData, external_container: bool) -> String {
73    let id = serde_json::to_string(container_id).expect("strings serialize");
74    let data = serde_json::to_string(data).expect("graph data serializes");
75    format!(
76        "{}\nawait runGraphChannel(window, {id}, {data}, dioxus, {external_container});",
77        include_str!("channel.js")
78    )
79}
80
81/// Reports a terminal channel failure and requests JS resource disposal.
82///
83/// - Complexity: O(message.len()) diagnostic reporting work.
84fn channel_failed(
85    eval: document::Eval,
86    mut failure: Signal<Option<String>>,
87    error: super::GraphFailure,
88    on_error: EventHandler<super::GraphFailure>,
89) {
90    let message = error.to_string();
91    crate::diagnostics::report_error(&message);
92    failure.set(Some(message.clone()));
93    let _ = eval.send(serde_json::json!({ "kind": "fatal", "message": message }));
94    on_error.call(error);
95}
96
97/// Processes typed messages sequentially through the generation's cached model.
98///
99/// - Complexity: each received frame adds deserialization, layout-constraint evaluation,
100///   and reply serialization work; total work follows frames received until closure/cancellation.
101async fn receive_views(
102    mut eval: document::Eval,
103    failure: Signal<Option<String>>,
104    on_error: EventHandler<super::GraphFailure>,
105) {
106    let mut bridge = BridgeState::default();
107    let mut ended = std::pin::pin!(eval.join::<serde_json::Value>());
108    loop {
109        let result = async {
110            let payload =
111                match prefer_message(eval.recv::<serde_json::Value>(), ended.as_mut()).await {
112                    Ok(message) => message
113                        .map_err(|error| super::GraphFailure::Transport(error.to_string()))?,
114                    Err(completion) => {
115                        completion
116                            .map_err(|error| super::GraphFailure::Transport(error.to_string()))?;
117                        return Err(super::GraphFailure::Transport(
118                            "graph channel ended unexpectedly".into(),
119                        ));
120                    }
121                };
122            if let Some(reply) = bridge.receive(payload)? {
123                if let Some(error) = bridge.take_failure() {
124                    if error.stops_channel() {
125                        return Err(error);
126                    }
127                    on_error.call(error);
128                }
129                eval.send(reply)
130                    .map_err(|error| super::GraphFailure::Transport(error.to_string()))?;
131            }
132            Ok::<(), super::GraphFailure>(())
133        }
134        .await;
135        if let Err(error) = result {
136            channel_failed(eval, failure, error, on_error);
137            return;
138        }
139    }
140}
141
142/// Which `window.beginGraph` driver method a [`graph_drive_script`] invokes.
143#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144///
145/// # Examples
146///
147/// Pass `GraphDrive::Init` for a new container and `GraphDrive::Update` for its
148/// subsequent snapshots to `graph_drive_script`.
149pub enum GraphDrive {
150    /// `window.beginGraph.init` — build a fresh D3 instance for the container, replacing any
151    /// existing one (a new sheet, or the first mount).
152    Init,
153    /// `window.beginGraph.update` — push new data into the container's existing instance.
154    Update,
155}
156
157impl GraphDrive {
158    /// The `window.beginGraph` method name this variant invokes.
159    fn method(self) -> &'static str {
160        match self {
161            GraphDrive::Init => "init",
162            GraphDrive::Update => "update",
163        }
164    }
165}
166
167/// Builds the JavaScript that stores `data` (serialized) as container `container_id`'s entry in
168/// `window.__beginGraphData` and invokes the [`GraphDrive`] method `call` on `window.beginGraph`
169/// when the driver script (`begin/assets/graph.js`) is loaded.
170///
171/// `container_id` is embedded as a JSON-encoded JS string literal, so any characters it contains
172/// (quotes, backslashes, newlines) are escaped rather than breaking or injecting into the emitted
173/// JS — `graph_id` is a public [`GraphView`] prop, so the id is not assumed to be a bare DOM id.
174/// The invoked method name comes from the [`GraphDrive`] enum, never a free string, so it can
175/// never be an arbitrary (injecting) value.
176///
177/// - Complexity: O(n) in the size of `data` (serialization plus string formatting).
178///
179/// # Examples
180///
181/// `graph_drive_script("graph", &data, GraphDrive::Update)` creates an update for
182/// an existing graph container; execute the returned script through the renderer.
183pub fn graph_drive_script(container_id: &str, data: &GraphData, call: GraphDrive) -> String {
184    let id = serde_json::to_string(container_id).unwrap_or_else(|_| "\"\"".to_string());
185    // Fall back to a valid JS literal (`null`), never an empty string, so the emitted assignment
186    // stays syntactically valid even in the (unreachable for `GraphData`) serialization-failure case.
187    let json = serde_json::to_string(data).unwrap_or_else(|_| "null".to_string());
188    let method = call.method();
189    format!(
190        "window.__beginGraphData = window.__beginGraphData || Object.create(null); \
191         window.__beginGraphData[{id}] = {json}; \
192         if (typeof window.beginGraph !== 'undefined') \
193         window.beginGraph.{method}({id}, window.__beginGraphData[{id}]); \
194         dioxus.close(); return null;"
195    )
196}
197
198/// Renders the property model bipartite graph using D3.
199///
200/// Installs a container-scoped bidirectional evaluation channel before D3
201/// initialization on desktop and web (including book hosts). Each generation
202/// owns one cached Adam model. Source/container replacement and unmount close
203/// JavaScript subscriptions/polling and abort the Rust receiver. Errors are
204/// reported through the platform diagnostics channel and a visible alert;
205/// no JavaScript view policy substitutes for a failed model.
206///
207/// Calls `on_error` with the original typed failure. A runtime failure stops the
208/// channel before transport can mask its cause; the application owns shutdown policy.
209/// Invalid requests leave the channel available for another request.
210///
211/// With `external_container`, the host supplies an existing container outside
212/// this Dioxus root (as mdBook does). This component renders only its lifecycle
213/// anchor and fallback diagnostic, never a second element with the same id.
214/// The shared channel also displays failures inside that external container.
215///
216/// The zoom controls and the "Show inactive" toggle live in `App`'s top bar
217/// (not here) — they only ever call `window.beginGraph.*`/set a signal `App`
218/// owns, so they don't need to be inside this component to work.
219///
220/// # Examples
221///
222/// ```
223/// use adam_web_ui::{GraphData, GraphView};
224/// use dioxus::prelude::*;
225///
226/// fn graph(id: ReadSignal<String>, data: ReadSignal<GraphData>,
227///          source: ReadSignal<String>) -> Element {
228///     rsx! { GraphView { graph_id: id, data, source_id: source, on_error: |_| {} } }
229/// }
230/// ```
231#[component]
232pub fn GraphView(
233    graph_id: ReadSignal<String>,
234    data: ReadSignal<GraphData>,
235    source_id: ReadSignal<String>,
236    on_error: EventHandler<super::GraphFailure>,
237    #[props(default = false)] external_container: bool,
238) -> Element {
239    let container_id = graph_id.read().clone();
240    let mut mounted = use_signal(|| false);
241    let mut failure = use_signal(|| None::<String>);
242    let session = use_hook(|| Rc::new(RefCell::new(None::<ChannelSession>)));
243    let cleanup = session.clone();
244    use_drop(move || {
245        if let Some(session) = cleanup.borrow_mut().take() {
246            session.stop();
247        }
248    });
249
250    let update_session = session.clone();
251    use_effect(move || {
252        let id = graph_id.read().clone();
253        let _source = source_id.read();
254        if !mounted() {
255            return;
256        }
257        if let Some(previous) = session.borrow_mut().take() {
258            previous.stop();
259        }
260        failure.set(None);
261        let eval = document::eval(&graph_channel_script(&id, &data.peek(), external_container));
262        let task = spawn(receive_views(eval, failure, on_error));
263        *session.borrow_mut() = Some(ChannelSession {
264            identity: Rc::new(()),
265            eval,
266            task,
267        });
268    });
269
270    use_effect(move || {
271        let id = graph_id.read().clone();
272        let script = graph_drive_script(&id, &data.read(), GraphDrive::Update);
273        let update_session = update_session.clone();
274        let identity = update_session
275            .borrow()
276            .as_ref()
277            .map(|session| session.identity.clone());
278        spawn(async move {
279            if let Err(error) = document::eval(&script).await {
280                let current = update_session.borrow();
281                if !same_owner(
282                    current.as_ref().map(|session| &session.identity),
283                    identity.as_ref(),
284                ) {
285                    return;
286                }
287                let message = format!("Graph update failed: {error}");
288                if let Some(session) = current.as_ref() {
289                    channel_failed(
290                        session.eval,
291                        failure,
292                        super::GraphFailure::Transport(message),
293                        on_error,
294                    );
295                } else {
296                    crate::diagnostics::report_error(&message);
297                    failure.set(Some(message.clone()));
298                    on_error.call(super::GraphFailure::Transport(message));
299                }
300            }
301        });
302    });
303
304    rsx! {
305        div {
306            id: (!external_container).then_some(container_id),
307            class: if external_container { "graph-channel-owner" } else { "graph-view" },
308            onmounted: move |_| mounted.set(true),
309            if let Some(message) = failure() {
310                p { class: "graph-failure", role: "alert", "{message}" }
311            }
312        }
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    /// External book containers retain their DOM identity while sharing the channel owner.
321    #[test]
322    fn external_graph_host_does_not_steal_existing_container() {
323        /// Renders a lifecycle owner for a container outside this Dioxus root.
324        fn external_host() -> Element {
325            let id = use_signal(|| "book-graph".to_string());
326            let data = use_signal(empty_graph_data);
327            let source = use_signal(|| "book-source".to_string());
328            rsx! { GraphView { graph_id: id, data, source_id: source, external_container: true, on_error: |_| {} } }
329        }
330        let mut dom = VirtualDom::new(external_host);
331        let mutations = dom.rebuild_to_vec();
332        assert!(!mutations.edits.iter().any(|edit| matches!(
333            edit,
334            dioxus::core::Mutation::SetAttribute {
335                name: "id",
336                value: dioxus::core::AttributeValue::Text(_),
337                ..
338            }
339        )));
340    }
341
342    /// A replaced channel's one-shot evaluation failure cannot affect its successor.
343    #[test]
344    fn delayed_update_error_requires_the_same_channel_owner() {
345        let old = Rc::new(());
346        let new = Rc::new(());
347        assert!(same_owner(Some(&old), Some(&old)));
348        assert!(!same_owner(Some(&new), Some(&old)));
349        assert!(!same_owner(None, Some(&old)));
350        assert!(!same_owner(Some(&new), None));
351        assert!(same_owner(None, None));
352    }
353
354    /// Queued diagnostics win a simultaneous channel completion; closed channels cannot hang.
355    #[test]
356    fn receiver_prioritizes_messages_and_detects_completion() {
357        use std::{
358            future::{pending, ready},
359            task::{Context, Poll, Waker},
360        };
361        let mut context = Context::from_waker(Waker::noop());
362        let mut completed = std::pin::pin!(ready("closed"));
363        let mut message = std::pin::pin!(prefer_message(ready("diagnostic"), completed.as_mut()));
364        assert_eq!(
365            message.as_mut().poll(&mut context),
366            Poll::Ready(Ok("diagnostic"))
367        );
368        let mut completed = std::pin::pin!(ready("closed"));
369        let mut message = std::pin::pin!(prefer_message(pending::<()>(), completed.as_mut()));
370        assert_eq!(
371            message.as_mut().poll(&mut context),
372            Poll::Ready(Err("closed"))
373        );
374        let mut completed = std::pin::pin!(pending::<()>());
375        let mut message = std::pin::pin!(prefer_message(pending::<()>(), completed.as_mut()));
376        assert_eq!(message.as_mut().poll(&mut context), Poll::Pending);
377    }
378    /// The mounted channel script starts its receiver before graph initialization.
379    #[test]
380    fn channel_script_embeds_shared_runtime_and_escapes_ids() {
381        let script = graph_channel_script("a\"b", &empty_graph_data(), false);
382        assert!(script.contains("async function runGraphChannel"));
383        assert!(script.contains(r#"await runGraphChannel(window, "a\"b""#));
384    }
385    /// Returns an empty graph snapshot for bridge protocol tests.
386    fn empty_graph_data() -> GraphData {
387        GraphData {
388            nodes: vec![],
389            links: vec![],
390            changed: vec![],
391            forced: vec![],
392            forced_relationships: vec![],
393        }
394    }
395
396    #[test]
397    /// Initialization scripts invoke the graph initializer.
398    fn graph_drive_script_init_calls_begin_graph_init() {
399        let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Init);
400        // The id is embedded as a JSON string literal (double-quoted).
401        assert!(script.contains("window.beginGraph.init(\"g1\""));
402        assert!(script.contains("window.__beginGraphData[\"g1\"]"));
403    }
404
405    #[test]
406    /// Update scripts invoke the graph updater.
407    fn graph_drive_script_update_calls_begin_graph_update() {
408        let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Update);
409        assert!(script.contains("window.beginGraph.update(\"g1\""));
410    }
411
412    #[test]
413    /// Drive scripts tolerate an unavailable browser graph runtime.
414    fn graph_drive_script_guards_on_begin_graph_being_defined() {
415        let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Init);
416        assert!(script.contains("typeof window.beginGraph !== 'undefined'"));
417    }
418
419    /// The one-shot evaluation closes its transport and returns a JSON value on web.
420    #[test]
421    fn graph_drive_script_has_explicit_serializable_completion() {
422        let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Update);
423        assert!(script.ends_with("dioxus.close(); return null;"));
424    }
425
426    #[test]
427    /// Drive scripts embed the supplied graph snapshot.
428    fn graph_drive_script_embeds_the_serialized_data() {
429        let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Init);
430        // GraphData serializes its fields; `nodes` is always present.
431        assert!(script.contains("\"nodes\""));
432    }
433
434    #[test]
435    /// Container IDs preserve single quotes without script injection.
436    fn graph_drive_script_escapes_a_quote_in_the_container_id() {
437        // A container id containing a single quote must not break out of the JS string or
438        // inject: JSON-encoding turns `'` into a plain character inside a double-quoted literal,
439        // and there must be no raw `'g'` string-open left in the output.
440        let script = graph_drive_script("a'b", &empty_graph_data(), GraphDrive::Init);
441        assert!(script.contains("window.beginGraph.init(\"a'b\""));
442        assert!(!script.contains("['a'b']"));
443    }
444
445    #[test]
446    /// Container IDs escape double quotes and backslashes as JSON strings.
447    fn graph_drive_script_escapes_a_double_quote_and_backslash_in_the_container_id() {
448        // JSON-encoding escapes `"` and `\`, so the emitted literal stays a single well-formed
449        // JS string rather than terminating early.
450        let script = graph_drive_script("a\"b\\c", &empty_graph_data(), GraphDrive::Init);
451        assert!(script.contains(r#"window.beginGraph.init("a\"b\\c""#));
452    }
453}