adam_web_ui/binding/dioxus.rs
1//! Binds scope-owned reactive handles to the single reviewed transaction owner.
2//!
3//! Initialize with [`use_sheet`], pass [`SheetHandle::cell`] to bound controls,
4//! and match [`SheetEvent::outcome`] at the host boundary. Only the host restores
5//! rejected candidates. All access remains on the owning Dioxus event loop.
6use super::*;
7use crate::{BuildError, Labels};
8use ::dioxus::prelude::*;
9use adam_lang::ParsedSheet;
10use std::{
11 cell::{Cell, RefCell},
12 collections::VecDeque,
13 rc::Rc,
14};
15
16thread_local! {
17 /// Allocates event-loop-wide identities, including independent Dioxus roots.
18 static INSTANCE: Cell<u64> = const { Cell::new(0) };
19}
20
21/// Returns a distinct identity without wrapping into a retired identity.
22fn next_instance() -> u64 {
23 INSTANCE.with(|counter| {
24 let next = counter
25 .get()
26 .checked_add(1)
27 .expect("sheet identities exhausted");
28 counter.set(next);
29 next
30 })
31}
32
33/// Owns the model, callback, and ordered outcomes awaiting a safe delivery boundary.
34struct HandleState {
35 owner: RefCell<SheetOwner>,
36 instance: Cell<u64>,
37 on_outcome: EventHandler<SheetEvent>,
38 pending_outcomes: RefCell<VecDeque<HostOutcome>>,
39 draining_outcomes: Cell<bool>,
40}
41
42/// Clears the outcome-drain guard if host callback delivery unwinds.
43struct OutcomeDrainGuard<'a>(&'a Cell<bool>);
44
45impl Drop for OutcomeDrainGuard<'_> {
46 /// Marks the event queue available for a later drain.
47 fn drop(&mut self) {
48 self.0.set(false);
49 }
50}
51
52/// Shares a scope-owned model; copying a handle does not copy its model or journal.
53///
54/// Signals track accepted publications, while checked borrows reject reentrancy.
55/// Handles make no `Send` or `Sync` promise and expire with their Dioxus scope.
56///
57/// # Examples
58/// See [`use_sheet`] for initialization and a bound editor.
59#[derive(Clone, Copy, PartialEq)]
60pub struct SheetHandle {
61 state: Signal<Rc<HandleState>>,
62 revision: Signal<u64>,
63}
64
65/// Delivers a structured outcome after all enclosing model borrows end.
66///
67/// # Examples
68/// ```
69/// use adam_web_ui::binding::{SheetEvent, HostOutcome, BindingError};
70/// fn outcome(event: SheetEvent) {
71/// if matches!(event.outcome, HostOutcome::Rejected(_))
72/// && matches!(event.sheet.inspect(|_, _| ()), Err(BindingError::Unavailable))
73/// {
74/// let _ = event.sheet.restore_accepted(); // The host chooses recovery.
75/// }
76/// }
77/// ```
78pub struct SheetEvent {
79 /// Addresses the owner without circular callback initialization.
80 pub sheet: SheetHandle,
81 /// Preserves acceptance, recorder failure, validation and fatal categories.
82 pub outcome: HostOutcome,
83}
84
85/// Initializes one owner per mounted hook, including cached construction failure.
86///
87/// Later factory/key prop changes do not replace the owner; call [`SheetHandle::replace`].
88///
89/// # Errors
90/// Returns independently owned construction diagnostics without a partial model.
91///
92/// - Complexity: Factory and publication cost once; O(1) on subsequent renders.
93///
94/// # Examples
95/// ```
96/// use adam_web_ui::{binding::*, build_sheet};
97/// use dioxus::prelude::*;
98/// use std::rc::Rc;
99/// fn app() -> Element {
100/// let factory: ModelFactory = Rc::new(||
101/// build_sheet("sheet s { cell x: i32 = 1; }", "s.adm2"));
102/// match use_sheet(factory, "s/v1".into(), EventHandler::new(|_| {})) {
103/// Ok(sheet) => rsx! { EditNumber { bind: sheet.cell("x") } },
104/// Err(error) => rsx! { pre { "{error:?}" } },
105/// }
106/// }
107/// ```
108pub fn use_sheet(
109 factory: ModelFactory,
110 schema_key: String,
111 on_outcome: EventHandler<SheetEvent>,
112) -> Result<SheetHandle, Rc<BuildError>> {
113 use_hook(move || SheetHandle::new(factory, schema_key, on_outcome).map_err(Rc::new))
114}
115
116impl SheetHandle {
117 /// Constructs a scope-owned handle without installing a failed model.
118 ///
119 /// Call once during scope initialization, or prefer [`use_sheet`].
120 ///
121 /// # Errors
122 /// Returns the factory's construction or initial publication error.
123 ///
124 /// - Complexity: Factory and publication cost.
125 ///
126 /// # Examples
127 /// See [`use_sheet`]; `SheetHandle::new` uses the same arguments inside a hook.
128 pub fn new(
129 factory: ModelFactory,
130 schema_key: String,
131 on_outcome: EventHandler<SheetEvent>,
132 ) -> Result<Self, BuildError> {
133 Ok(Self::from_owner(
134 SheetOwner::new(factory, schema_key)?,
135 on_outcome,
136 ))
137 }
138
139 /// Adopts an owner without rebuilding or duplicating its model.
140 ///
141 /// Call in a mounted Dioxus scope; this transfers its journal, recordings and
142 /// availability state. A discarded or retired owner stays unavailable.
143 ///
144 /// # Examples
145 /// See [`SheetOwner`] for construction; inside a hook call
146 /// `SheetHandle::from_owner(owner, EventHandler::new(|_| {}))`.
147 pub fn from_owner(owner: SheetOwner, on_outcome: EventHandler<SheetEvent>) -> Self {
148 Self {
149 state: Signal::new(Rc::new(HandleState {
150 owner: RefCell::new(owner),
151 instance: Cell::new(next_instance()),
152 on_outcome,
153 pending_outcomes: RefCell::new(VecDeque::new()),
154 draining_outcomes: Cell::new(false),
155 })),
156 revision: Signal::new(0),
157 }
158 }
159
160 /// Returns the shared state without subscribing callers to internal ownership.
161 fn state(&self) -> Rc<HandleState> {
162 self.state.peek().clone()
163 }
164
165 /// Publishes one transition without retaining a model borrow across notification.
166 fn publish(&self) {
167 let mut revision = self.revision;
168 revision += 1;
169 }
170
171 /// Queues an outcome and delivers queued events when no model borrow is active.
172 ///
173 /// - Complexity: O(q) callback work for q queued outcomes.
174 fn emit(&self, outcome: HostOutcome) {
175 let state = self.state();
176 state.pending_outcomes.borrow_mut().push_back(outcome);
177 self.drain_outcomes();
178 }
179
180 /// Delivers pending outcomes in order without holding model or queue borrows.
181 ///
182 /// - Complexity: O(q) callback work and O(q) queue space for q outcomes.
183 fn drain_outcomes(&self) {
184 let state = self.state();
185 if state.draining_outcomes.replace(true) {
186 return;
187 }
188 let _guard = OutcomeDrainGuard(&state.draining_outcomes);
189 loop {
190 let outcome = {
191 let Ok(owner) = state.owner.try_borrow_mut() else {
192 break;
193 };
194 drop(owner);
195 state.pending_outcomes.borrow_mut().pop_front()
196 };
197 let Some(outcome) = outcome else {
198 break;
199 };
200 state.on_outcome.call(SheetEvent {
201 sheet: *self,
202 outcome,
203 });
204 }
205 }
206
207 /// Returns the reactive instance identity used to key replacement controls.
208 ///
209 /// # Examples
210 /// See [`Self::replace`]; a successful replacement changes `sheet.instance()`.
211 pub fn instance(&self) -> u64 {
212 let _ = self.revision.read();
213 self.state().instance.get()
214 }
215
216 /// Creates a symbolic binding owned by this exact model installation.
217 ///
218 /// Lookup errors are returned by [`CellBinding::view`], not hidden here.
219 ///
220 /// - Complexity: O(name bytes).
221 ///
222 /// # Examples
223 /// See [`use_sheet`]; `sheet.cell("x")` binds the named cell.
224 pub fn cell(&self, name: &str) -> CellBinding {
225 CellBinding {
226 sheet: *self,
227 instance: self.instance(),
228 key: name.into(),
229 }
230 }
231
232 /// Submits an ordered group and delivers each structured outcome to the host.
233 ///
234 /// Reentrant access rejects without invoking the transaction. Rejections that
235 /// discard a candidate retire its bindings; recovery installs a new instance.
236 /// Reentrant outcomes wait until every enclosing owner borrow ends, then drain
237 /// in submission order without recursive callback invocation.
238 ///
239 /// - Complexity: Transaction/publication cost plus queued callback work.
240 ///
241 /// # Examples
242 /// See [`SheetOwner`] for `CellEdit` groups; call `sheet.apply(&edits, UpdateOrigin::User)`.
243 pub fn apply(&self, edits: &[CellEdit], origin: UpdateOrigin) {
244 let state = self.state();
245 let outcome = match state.owner.try_borrow_mut() {
246 Ok(mut owner) => {
247 let outcome = owner.apply(edits, origin);
248 if owner.inspect(|_, _| ()).is_err() {
249 state.instance.set(next_instance());
250 }
251 outcome
252 }
253 Err(_) => {
254 HostOutcome::Rejected(HostRejection::Binding(BindingError::ReentrantMutation))
255 }
256 };
257 self.publish();
258 self.emit(outcome);
259 }
260
261 /// Restores accepted aspirations only at the host's explicit request.
262 ///
263 /// # Errors
264 /// Returns typed reconstruction, fatal retirement, or reentrancy errors.
265 ///
266 /// - Complexity: Factory, journal replay, publication, and queued callback cost.
267 ///
268 /// # Examples
269 /// See [`SheetEvent`] for explicit host recovery.
270 pub fn restore_accepted(&self) -> Result<(), BuildError> {
271 let state = self.state();
272 let result = match state.owner.try_borrow_mut() {
273 Ok(mut owner) => {
274 let result = owner.restore_accepted();
275 state.instance.set(next_instance());
276 Some(result)
277 }
278 Err(_) => None,
279 };
280 if let Some(result) = result {
281 self.publish();
282 self.drain_outcomes();
283 result
284 } else {
285 self.drain_outcomes();
286 Err(build_busy())
287 }
288 }
289
290 /// Borrows the single accepted journal, including after rejection or retirement.
291 ///
292 /// # Errors
293 /// Returns `ReentrantMutation` without invoking `f` while a mutation owns it.
294 /// Writes attempted inside `f` likewise reject without changing the journal.
295 /// Outcomes submitted inside `f` reach the host after `f` returns.
296 ///
297 /// - Complexity: O(1) plus callback and queued outcome delivery cost; does not
298 /// copy history.
299 ///
300 /// # Examples
301 /// See [`use_sheet`]; `sheet.with_accepted_state(|s| s.transactions.len())`
302 /// returns the number of accepted groups.
303 pub fn with_accepted_state<R>(
304 &self,
305 f: impl FnOnce(&RecoveryState) -> R,
306 ) -> Result<R, BindingError> {
307 let state = self.state();
308 let result = match state.owner.try_borrow() {
309 Ok(owner) => {
310 let result = f(owner.accepted_state());
311 drop(owner);
312 Ok(result)
313 }
314 Err(_) => Err(BindingError::ReentrantMutation),
315 };
316 self.drain_outcomes();
317 result
318 }
319
320 /// Tracks a read of an accepted live model without exposing mutable ownership.
321 ///
322 /// # Errors
323 /// Returns unavailable, retired, or reentrant diagnostics without calling `f`.
324 /// Outcomes submitted inside `f` reach the host after `f` returns.
325 ///
326 /// - Complexity: O(1) plus callback and queued outcome delivery cost.
327 ///
328 /// # Examples
329 /// See [`use_sheet`]; `sheet.inspect(|parsed, _| parsed.cell_names.len())`
330 /// counts named cells, and can project application-specific graph data.
331 pub fn inspect<R>(
332 &self,
333 f: impl FnOnce(&ParsedSheet, &Labels) -> R,
334 ) -> Result<R, BindingError> {
335 let _ = self.revision.read();
336 let state = self.state();
337 let result = match state.owner.try_borrow() {
338 Ok(owner) => {
339 let result = owner.inspect(f);
340 drop(owner);
341 result
342 }
343 Err(_) => Err(BindingError::ReentrantMutation),
344 };
345 self.drain_outcomes();
346 result
347 }
348
349 /// Captures exact effective sources from the accepted live model.
350 ///
351 /// # Errors
352 /// Returns capture capability, encoding, availability, or reentrancy failures.
353 ///
354 /// - Complexity: Source analysis, encoded bytes, and queued callback cost.
355 ///
356 /// # Examples
357 /// See [`use_sheet`]; `sheet.capture(&["x"])` selects the named result.
358 pub fn capture(&self, result_keys: &[&str]) -> Result<Recording, CaptureError> {
359 let state = self.state();
360 let result = state
361 .owner
362 .try_borrow()
363 .map_err(|_| capture_busy())
364 .and_then(|owner| owner.capture(result_keys));
365 self.drain_outcomes();
366 result
367 }
368
369 /// Enables capture for subsequent accepted user actions without cloning history.
370 ///
371 /// # Errors
372 /// Returns capture validation, availability, or reentrancy errors.
373 ///
374 /// - Complexity: Capture cost, selected-key bytes, and queued callback cost.
375 ///
376 /// # Examples
377 /// See [`use_sheet`]; `sheet.start_recording(&["x"])` starts action capture.
378 pub fn start_recording(&self, result_keys: &[&str]) -> Result<(), CaptureError> {
379 let state = self.state();
380 let result = state
381 .owner
382 .try_borrow_mut()
383 .map_err(|_| capture_busy())
384 .and_then(|mut owner| owner.start_recording(result_keys));
385 self.drain_outcomes();
386 result
387 }
388
389 /// Stops recording, reporting contention through the host outcome boundary.
390 ///
391 /// - Complexity: O(selected-key bytes) destruction plus queued callback cost.
392 ///
393 /// # Examples
394 /// See [`Self::start_recording`]; call `sheet.stop_recording()` to stop capture.
395 pub fn stop_recording(&self) {
396 let state = self.state();
397 let result = match state.owner.try_borrow_mut() {
398 Ok(mut owner) => {
399 owner.stop_recording();
400 Ok(())
401 }
402 Err(_) => Err(BindingError::ReentrantMutation),
403 };
404 if let Err(error) = result {
405 self.emit(HostOutcome::Rejected(HostRejection::Binding(error)));
406 }
407 self.drain_outcomes();
408 }
409
410 /// Returns the latest immutable recording without copying its values.
411 ///
412 /// Contention reports a structured host outcome and returns no recording.
413 ///
414 /// - Complexity: O(1) plus queued callback cost.
415 ///
416 /// # Examples
417 /// See [`Self::start_recording`]; before an action `sheet.last_recording().is_none()`.
418 pub fn last_recording(&self) -> Option<Rc<Recording>> {
419 let _ = self.revision.read();
420 let state = self.state();
421 let result = state
422 .owner
423 .try_borrow()
424 .map(|owner| owner.recordings().last().cloned());
425 let recording = match result {
426 Ok(recording) => recording,
427 Err(_) => {
428 self.emit(HostOutcome::Rejected(HostRejection::Binding(
429 BindingError::ReentrantMutation,
430 )));
431 None
432 }
433 };
434 self.drain_outcomes();
435 recording
436 }
437
438 /// Installs a fully validated replacement and retires all prior bindings on success.
439 ///
440 /// # Errors
441 /// Returns construction or reentrancy errors, preserving the prior owner.
442 /// A fatal owner rejects replacement without invoking the factory.
443 ///
444 /// - Complexity: Factory/publication cost, old-model destruction, and queued
445 /// callback cost.
446 ///
447 /// # Examples
448 /// See [`use_sheet`]; `sheet.replace(factory, "s/v2".into())` replaces explicitly.
449 pub fn replace(&self, factory: ModelFactory, schema_key: String) -> Result<(), BuildError> {
450 let state = self.state();
451 let result = match state.owner.try_borrow_mut() {
452 Ok(mut owner) => match replacement_allowed(&owner) {
453 Ok(()) => match SheetOwner::new(factory, schema_key) {
454 Ok(replacement) => {
455 *owner = replacement;
456 state.instance.set(next_instance());
457 Ok(())
458 }
459 Err(error) => Err(error),
460 },
461 Err(error) => Err(BuildError::Recovery(Box::new(HostRejection::Binding(
462 error,
463 )))),
464 },
465 Err(_) => Err(build_busy()),
466 };
467 if result.is_ok() {
468 self.publish();
469 }
470 self.drain_outcomes();
471 result
472 }
473
474 /// Adopts a prevalidated replacement and retires the preceding installation.
475 ///
476 /// This avoids rebuilding a candidate already checked by a host's load path.
477 ///
478 /// # Errors
479 /// Returns candidate availability, fatal retirement, or reentrancy errors
480 /// without replacing the current owner.
481 ///
482 /// - Complexity: Old model/history destruction, O(1) owner transfer, and queued
483 /// callback cost.
484 ///
485 /// # Examples
486 /// See [`Self::from_owner`]; `sheet.install(owner)` installs a validated load.
487 pub fn install(&self, candidate: SheetOwner) -> Result<(), BindingError> {
488 let state = self.state();
489 let result = match candidate.inspect(|_, _| ()) {
490 Ok(()) => match state.owner.try_borrow_mut() {
491 Ok(mut owner) => match replacement_allowed(&owner) {
492 Ok(()) => {
493 *owner = candidate;
494 state.instance.set(next_instance());
495 Ok(())
496 }
497 Err(error) => Err(error),
498 },
499 Err(_) => Err(BindingError::ReentrantMutation),
500 },
501 Err(error) => Err(error),
502 };
503 if result.is_ok() {
504 self.publish();
505 }
506 self.drain_outcomes();
507 result
508 }
509
510 /// Installs a fresh successfully replayed owner without recording playback as a user edit.
511 ///
512 /// # Errors
513 /// Returns compatibility, construction, playback or reentrancy errors;
514 /// failed replay leaves the prior owner installed. A retired owner never
515 /// invokes the factory.
516 ///
517 /// - Complexity: Factory, replay, publication, old-model destruction, and queued
518 /// callback cost.
519 ///
520 /// # Examples
521 /// See [`Self::capture`]; pass its recording to
522 /// `sheet.playback(factory, "s/v1".into(), &recording)`.
523 pub fn playback(
524 &self,
525 factory: ModelFactory,
526 schema_key: String,
527 recording: &Recording,
528 ) -> Result<(), PlaybackError> {
529 let state = self.state();
530 let result = match state.owner.try_borrow_mut() {
531 Ok(mut owner) => match replacement_allowed(&owner) {
532 Ok(()) => match SheetOwner::playback(factory, schema_key, recording) {
533 Ok(playback) => {
534 *owner = playback;
535 state.instance.set(next_instance());
536 Ok(())
537 }
538 Err(error) => Err(error),
539 },
540 Err(error) => Err(PlaybackError::Capture(CaptureError::Unavailable(error))),
541 },
542 Err(_) => Err(PlaybackError::Capture(capture_busy())),
543 };
544 if result.is_ok() {
545 self.publish();
546 }
547 self.drain_outcomes();
548 result
549 }
550
551 /// Copies shared view references, never the accepted history.
552 ///
553 /// # Errors
554 /// Returns an owner-state or reentrancy error without inspecting a failed model.
555 ///
556 /// - Complexity: O(named cells) time and space plus queued callback cost.
557 ///
558 /// # Examples
559 /// See [`use_sheet`]; `sheet.views()` enumerates accepted published cells.
560 pub fn views(&self) -> Result<Vec<Rc<CellView>>, BindingError> {
561 let _ = self.revision.read();
562 let state = self.state();
563 let result = state
564 .owner
565 .try_borrow()
566 .map_err(|_| BindingError::ReentrantMutation)
567 .and_then(|owner| owner.inspect(|_, _| ()).map(|()| owner.views().to_vec()));
568 self.drain_outcomes();
569 result
570 }
571}
572
573/// Addresses one cell in one installation, never a later same-named replacement.
574///
575/// # Examples
576/// See [`use_sheet`] for creating a binding and passing it to a widget.
577#[derive(Clone, PartialEq)]
578pub struct CellBinding {
579 sheet: SheetHandle,
580 instance: u64,
581 key: Rc<str>,
582}
583
584impl CellBinding {
585 /// Returns the accepted published view after checked instance and name lookup.
586 ///
587 /// # Errors
588 /// Returns unknown key, unavailable, retired-instance, or reentrancy errors.
589 ///
590 /// - Complexity: O(named cells + key bytes) plus queued callback cost.
591 ///
592 /// # Examples
593 /// See [`use_sheet`]; `sheet.cell("x").view()` reads its exact effective value.
594 pub fn view(&self) -> Result<Rc<CellView>, BindingError> {
595 let result = if self.instance != self.sheet.instance() {
596 Err(BindingError::RetiredInstance)
597 } else {
598 let state = self.sheet.state();
599 state
600 .owner
601 .try_borrow()
602 .map_err(|_| BindingError::ReentrantMutation)
603 .and_then(|owner| {
604 owner.inspect(|_, _| ())?;
605 owner
606 .views()
607 .iter()
608 .find(|view| view.key == self.key.as_ref())
609 .cloned()
610 .ok_or_else(|| BindingError::UnknownKey(self.key.to_string()))
611 })
612 };
613 self.sheet.drain_outcomes();
614 result
615 }
616
617 /// Submits canonical user input only to the originating instance.
618 ///
619 /// All outcomes, including stale events and conversion errors, reach the host.
620 ///
621 /// - Complexity: Transaction cost plus key and input bytes.
622 ///
623 /// # Examples
624 /// See [`use_sheet`]; `sheet.cell("x").submit("2".into())` submits an aspiration.
625 pub fn submit(&self, canonical: String) {
626 // A reactive caller must not subscribe to the revision this edit publishes.
627 if self.instance != self.sheet.state().instance.get() {
628 self.report(HostRejection::Binding(BindingError::RetiredInstance));
629 return;
630 }
631 self.sheet.apply(
632 &[CellEdit {
633 key: self.key.to_string(),
634 canonical,
635 }],
636 UpdateOrigin::User,
637 );
638 }
639
640 /// Reports widget input/configuration failures without mutating the model.
641 pub(super) fn report(&self, rejection: HostRejection) {
642 let rejection = if self.instance == self.sheet.state().instance.get() {
643 rejection
644 } else {
645 HostRejection::Binding(BindingError::RetiredInstance)
646 };
647 self.sheet.emit(HostOutcome::Rejected(rejection));
648 }
649
650 /// Returns a stable installation-qualified key for component remounts.
651 ///
652 /// - Complexity: O(key bytes) time and space.
653 pub(super) fn identity(&self) -> String {
654 format!("{}:{}", self.instance, self.key)
655 }
656
657 /// Supplies the stable name when a widget omits its accessible label.
658 ///
659 /// - Complexity: O(key bytes) time and space when the label is empty.
660 pub(super) fn label(&self, label: String) -> String {
661 if label.is_empty() {
662 self.key.to_string()
663 } else {
664 label
665 }
666 }
667}
668
669/// Wraps checked owner contention in the construction/recovery error channel.
670fn build_busy() -> BuildError {
671 BuildError::Recovery(Box::new(HostRejection::Binding(
672 BindingError::ReentrantMutation,
673 )))
674}
675
676/// Wraps checked owner contention in the recording error channel.
677fn capture_busy() -> CaptureError {
678 CaptureError::Unavailable(BindingError::ReentrantMutation)
679}
680
681/// Forbids factory calls and installation on a permanently retired owner.
682fn replacement_allowed(owner: &SheetOwner) -> Result<(), BindingError> {
683 match owner.inspect(|_, _| ()) {
684 Err(BindingError::RetiredInstance) => Err(BindingError::RetiredInstance),
685 _ => Ok(()),
686 }
687}