1use 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
24struct ChannelSession {
26 identity: Rc<()>,
28 eval: document::Eval,
30 task: Task,
32}
33
34fn 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
43async 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 fn stop(self) {
64 let _ = self.eval.send(serde_json::json!({ "kind": "close" }));
65 self.task.cancel();
66 }
67}
68
69fn 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
81fn 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
97async 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144pub enum GraphDrive {
150 Init,
153 Update,
155}
156
157impl GraphDrive {
158 fn method(self) -> &'static str {
160 match self {
161 GraphDrive::Init => "init",
162 GraphDrive::Update => "update",
163 }
164 }
165}
166
167pub 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 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#[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 #[test]
322 fn external_graph_host_does_not_steal_existing_container() {
323 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 #[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 #[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 #[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 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 fn graph_drive_script_init_calls_begin_graph_init() {
399 let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Init);
400 assert!(script.contains("window.beginGraph.init(\"g1\""));
402 assert!(script.contains("window.__beginGraphData[\"g1\"]"));
403 }
404
405 #[test]
406 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 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 #[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 fn graph_drive_script_embeds_the_serialized_data() {
429 let script = graph_drive_script("g1", &empty_graph_data(), GraphDrive::Init);
430 assert!(script.contains("\"nodes\""));
432 }
433
434 #[test]
435 fn graph_drive_script_escapes_a_quote_in_the_container_id() {
437 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 fn graph_drive_script_escapes_a_double_quote_and_backslash_in_the_container_id() {
448 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}