dioxus-dnd 3.1.0

Modular, accessible drag-and-drop for Dioxus: sortable lists, kanban boards, trees, grids, file drops, multi-select, touch support and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
#![doc = include_str!("../../docs/api/drop-effects.md")]

use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::mem::ManuallyDrop;
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use std::rc::Rc;

use dioxus::prelude::{provide_context, use_hook};
use dioxus::signals::{AnyStorage, Owner, SyncStorage, UnsyncStorage};

use super::{DropEffect, DropOutcome, ZoneId};

/// A model helper refused to guess semantics for an unsupported effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApplyDropError {
    UnsupportedEffect(DropEffect),
}

impl fmt::Display for ApplyDropError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedEffect(effect) => {
                write!(formatter, "unsupported drop effect `{}`", effect.as_str())
            }
        }
    }
}

impl std::error::Error for ApplyDropError {}

thread_local! {
    /// Owner pairs backing models created by [`use_dnd_model`]. App-wide
    /// models deliberately outlive every window: a copyable signal/store
    /// handle must never dangle because the window that created it closed.
    /// Bounded in normal use to one scope per app-wide model. `ManuallyDrop`
    /// is load-bearing: ordinary thread-local values are destroyed when their
    /// creator thread exits, which would make a transferred `SyncSignal`
    /// dangle before process exit.
    static MODEL_OWNERS: RefCell<Vec<ManuallyDrop<DndScope>>> = const { RefCell::new(Vec::new()) };
}

/// An explicit lifetime for Dioxus signals and stores created outside a
/// component scope.
///
/// A scope owns both storage flavors Dioxus state may allocate: ordinary
/// signals use [`UnsyncStorage`], while a [`Store`](struct@dioxus::prelude::Store)
/// keeps its subscription tree in [`SyncStorage`]. Create state inside
/// [`with`](Self::with), then retain a clone of the scope for exactly as long
/// as that state may be used. Storage is reclaimed when the last clone drops.
///
/// Use [`use_dnd_model`] instead for an app-wide model shared by windows. A
/// `DndScope` is intended for dynamic state whose lifetime really should end,
/// such as the contents owned by one spawned window.
///
/// `with` must run inside a Dioxus runtime, like the state constructors it
/// contains.
///
/// Do not drop the last scope clone while any owned read or write guard is
/// live. Unsynchronized storage cannot be recycled through an active
/// `RefCell` borrow and synchronized storage must wait for its lock guard.
///
/// ```no_run
/// use dioxus::prelude::*;
/// use dioxus_dnd::prelude::DndScope;
///
/// fn app() -> Element {
///     let scope = use_hook(DndScope::new);
///     let count = use_hook(|| scope.with(|| Signal::new(0)));
///     rsx! { "{count}" }
/// }
/// ```
#[must_use = "keep a DndScope alive while using state created under it"]
#[derive(Clone)]
pub struct DndScope {
    owners: Rc<DndScopeOwners>,
}

struct DndScopeOwners {
    unsync: Owner<UnsyncStorage>,
    sync: Owner<SyncStorage>,
}

impl DndScope {
    /// Create an empty scope. Mint every signal or store it owns with
    /// [`Self::with`].
    pub fn new() -> Self {
        Self {
            owners: Rc::new(DndScopeOwners {
                unsync: UnsyncStorage::owner(),
                sync: SyncStorage::owner(),
            }),
        }
    }

    /// Run `init` with this scope as the current owner for both Dioxus
    /// storage flavors.
    ///
    /// Owner restoration is unwind-safe: a panic from `init` is resumed only
    /// after both Dioxus owner overrides have returned normally and restored
    /// their previous values.
    pub fn with<R>(&self, init: impl FnOnce() -> R) -> R {
        let result = dioxus::core::with_owner(self.owners.unsync.clone(), || {
            dioxus::core::with_owner(self.owners.sync.clone(), || {
                catch_unwind(AssertUnwindSafe(init))
            })
        });
        match result {
            Ok(value) => value,
            Err(panic) => resume_unwind(panic),
        }
    }
}

impl Default for DndScope {
    fn default() -> Self {
        Self::new()
    }
}

/// Create and provide an app-wide model whose Dioxus state survives every
/// window close order.
///
/// `init` runs once for this component instance under a paired, process-lived
/// [`DndScope`]. The returned model is also provided in context. Seed spawned
/// windows with the model by chaining `with_root_context(model)` after
/// [`DndWorld::vdom`](crate::core::DndWorld::vdom).
/// The process lifetime is deliberate: copyable signal and store handles do
/// not carry an ownership guard, so tying storage to a particular window (or
/// to an `Rc` callers must remember to propagate) can leave a survivor holding
/// a dangling handle.
///
/// Every signal, store, or other owner-backed value that needs this lifetime
/// must be allocated synchronously inside `init`. Wrapping a handle created
/// earlier does not reparent it, and an allocation performed later uses
/// whichever owner is current then. For later app-lived allocations, mint
/// them under a new [`DndScope`] and retain that scope in process-lived model
/// state.
///
/// Call this once for each app-wide model. Use [`DndScope`] for dynamic state
/// that should be reclaimed before process exit.
///
/// # Allocation boundary
///
/// The following compiles, but does **not** give `cards` process lifetime:
/// it was already owned by the component before `use_dnd_model` ran.
///
/// ```no_run
/// use dioxus::prelude::*;
/// use dioxus_dnd::prelude::use_dnd_model;
///
/// #[derive(Clone, Copy)]
/// struct Model {
///     cards: Signal<Vec<String>>,
/// }
///
/// fn app() -> Element {
///     let cards = use_signal(Vec::<String>::new);
///     let _model = use_dnd_model(|| Model { cards }); // not reparented
///     rsx! {}
/// }
/// ```
///
/// Allocate the signal inside the initializer instead:
///
/// ```
/// use dioxus::prelude::*;
/// use dioxus_dnd::prelude::use_dnd_model;
///
/// #[derive(Clone, Copy)]
/// struct Model {
///     cards: Signal<Vec<String>>,
/// }
///
/// fn app() -> Element {
///     let model = use_dnd_model(|| Model {
///         cards: Signal::new(Vec::new()),
///     });
///     rsx! { "{model.cards.read().len()} cards" }
/// }
/// ```
pub fn use_dnd_model<M: Clone + 'static>(init: impl FnOnce() -> M) -> M {
    use_hook(move || {
        let scope = DndScope::new();
        let model = scope.with(init);
        MODEL_OWNERS.with_borrow_mut(|owners| owners.push(ManuallyDrop::new(scope)));
        provide_context(model)
    })
}

/// Apply a drop to a `HashMap<ZoneId, Vec<T>>` model.
///
/// `Move` removes the matching item from `outcome.from` before appending it
/// to `outcome.to`. `Copy` leaves the source alone and passes the payload
/// through `clone_item` first, which is where you should assign a fresh id.
///
/// Semantics worth knowing:
///
/// - Removal matches **every** item in the source whose key equals the
///   payload's key. Keys are expected to be unique within a zone; if they
///   are not, a single `Move` prunes all of them.
/// - A `Move` where `from == Some(to)` removes and re-appends, so dropping
///   an item back onto its own zone sends it to the **end of that list**.
/// - A `Move` with `from: None` (payload from outside any zone, e.g. a
///   palette) skips removal and just appends.
/// - An unknown `to` zone is created on the fly rather than dropping the
///   item on the floor.
/// - For backwards compatibility, every non-`Copy` effect follows the legacy
///   move path. Use [`try_apply_clone_or_move`] when unsupported effects must
///   be rejected explicitly.
pub fn apply_clone_or_move<T, K>(
    zones: &mut HashMap<ZoneId, Vec<T>>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    clone_item: impl FnMut(T) -> T,
) where
    K: PartialEq,
{
    let result = apply_clone_or_move_impl(zones, outcome, key, clone_item, false);
    debug_assert!(
        result.is_ok(),
        "legacy model helper cannot reject an effect"
    );
}

/// Checked form of [`apply_clone_or_move`].
///
/// `Move` and `Copy` use the same behavior as the compatibility helper.
/// `Link` and `None` return [`ApplyDropError::UnsupportedEffect`] without
/// mutating the model.
pub fn try_apply_clone_or_move<T, K>(
    zones: &mut HashMap<ZoneId, Vec<T>>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    clone_item: impl FnMut(T) -> T,
) -> Result<(), ApplyDropError>
where
    K: PartialEq,
{
    apply_clone_or_move_impl(zones, outcome, key, clone_item, true)
}

fn apply_clone_or_move_impl<T, K>(
    zones: &mut HashMap<ZoneId, Vec<T>>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    mut clone_item: impl FnMut(T) -> T,
    checked: bool,
) -> Result<(), ApplyDropError>
where
    K: PartialEq,
{
    let DropOutcome {
        payload,
        from,
        to,
        effect,
        ..
    } = outcome;
    let item = match effect {
        DropEffect::Copy => clone_item(payload),
        DropEffect::Move => {
            if let Some(from) = from {
                let payload_key = key(&payload);
                if let Some(source) = zones.get_mut(&from) {
                    source.retain(|item| key(item) != payload_key);
                }
            }
            payload
        }
        unsupported if checked => return Err(ApplyDropError::UnsupportedEffect(unsupported)),
        _ => {
            if let Some(from) = from {
                let payload_key = key(&payload);
                if let Some(source) = zones.get_mut(&from) {
                    source.retain(|item| key(item) != payload_key);
                }
            }
            payload
        }
    };

    zones.entry(to).or_default().push(item);
    Ok(())
}

/// Apply a drop between two plain `Vec<T>` lists.
///
/// `Move` removes the matching item from `source` before appending it to
/// `target`. `Copy` leaves the source alone and passes the payload through
/// `clone_item` first, which is where you should assign a fresh id.
///
/// You choose which lists to pass, so the outcome's `from` and `to` fields
/// are **ignored** here; only `payload` and `effect` are consulted. Pass
/// `None` for `source` when the payload came from outside any list. As with
/// [`apply_clone_or_move`], removal matches every item whose key equals the
/// payload's key. For backwards compatibility, every non-`Copy` effect uses
/// the legacy move path. Use [`try_apply_list_clone_or_move`] to reject
/// unsupported effects explicitly.
pub fn apply_list_clone_or_move<T, K>(
    source: Option<&mut Vec<T>>,
    target: &mut Vec<T>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    clone_item: impl FnMut(T) -> T,
) where
    K: PartialEq,
{
    let result = apply_list_clone_or_move_impl(source, target, outcome, key, clone_item, false);
    debug_assert!(
        result.is_ok(),
        "legacy model helper cannot reject an effect"
    );
}

/// Checked form of [`apply_list_clone_or_move`].
///
/// `Move` and `Copy` use the same behavior as the compatibility helper.
/// `Link` and `None` return [`ApplyDropError::UnsupportedEffect`] without
/// mutating either list.
pub fn try_apply_list_clone_or_move<T, K>(
    source: Option<&mut Vec<T>>,
    target: &mut Vec<T>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    clone_item: impl FnMut(T) -> T,
) -> Result<(), ApplyDropError>
where
    K: PartialEq,
{
    apply_list_clone_or_move_impl(source, target, outcome, key, clone_item, true)
}

fn apply_list_clone_or_move_impl<T, K>(
    source: Option<&mut Vec<T>>,
    target: &mut Vec<T>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    mut clone_item: impl FnMut(T) -> T,
    checked: bool,
) -> Result<(), ApplyDropError>
where
    K: PartialEq,
{
    let DropOutcome {
        payload, effect, ..
    } = outcome;
    let item = match effect {
        DropEffect::Copy => clone_item(payload),
        DropEffect::Move => {
            if let Some(source) = source {
                let payload_key = key(&payload);
                source.retain(|item| key(item) != payload_key);
            }
            payload
        }
        unsupported if checked => return Err(ApplyDropError::UnsupportedEffect(unsupported)),
        _ => {
            if let Some(source) = source {
                let payload_key = key(&payload);
                source.retain(|item| key(item) != payload_key);
            }
            payload
        }
    };

    target.push(item);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{DragMode, Point};
    use dioxus::prelude::*;
    use dioxus::signals::SyncSignal;
    use std::cell::Cell;
    use std::sync::mpsc::Sender;

    #[derive(Debug, Clone, PartialEq)]
    struct Card {
        id: u32,
        title: &'static str,
    }

    #[derive(Clone, Copy, PartialEq)]
    struct SignalModel {
        value: Signal<i32>,
    }

    type SignalModelSlot = Rc<RefCell<Option<SignalModel>>>;

    #[derive(Store, Clone, PartialEq)]
    struct StoreState {
        value: i32,
    }

    #[derive(Clone, Copy, PartialEq)]
    struct StoreModel {
        state: Store<StoreState>,
    }

    type StoreModelSlot = Rc<RefCell<Option<StoreModel>>>;

    type ScopeSlot = Rc<RefCell<Option<(DndScope, Signal<i32>, Store<i32>, SyncSignal<i32>)>>>;

    type PanicScopeSlot = Rc<RefCell<Option<(DndScope, DndScope, Signal<i32>)>>>;

    type ScopePairSlot = Rc<RefCell<Option<(DndScope, Signal<i32>, DndScope, Signal<i32>)>>>;

    #[derive(Clone, Copy, PartialEq)]
    struct ThreadModel {
        value: SyncSignal<i32>,
    }

    #[derive(Default)]
    struct SurvivorProbe {
        renders: Cell<usize>,
        value: Cell<i32>,
    }

    fn signal_model_creator() -> Element {
        let slot = use_context::<SignalModelSlot>();
        let model = use_dnd_model(|| SignalModel {
            value: Signal::new(0),
        });
        *slot.borrow_mut() = Some(model);
        rsx! {}
    }

    fn signal_model_survivor() -> Element {
        let model = use_context::<SignalModel>();
        let probe = use_context::<Rc<SurvivorProbe>>();
        let value = *model.value.read();
        probe.value.set(value);
        probe.renders.set(probe.renders.get() + 1);
        rsx! { "{value}" }
    }

    fn store_model_creator() -> Element {
        let slot = use_context::<StoreModelSlot>();
        let model = use_dnd_model(|| StoreModel {
            state: Store::new(StoreState { value: 0 }),
        });
        *slot.borrow_mut() = Some(model);
        rsx! {}
    }

    fn store_model_survivor() -> Element {
        let model = use_context::<StoreModel>();
        let probe = use_context::<Rc<SurvivorProbe>>();
        let value = *model.state.value().read();
        probe.value.set(value);
        probe.renders.set(probe.renders.get() + 1);
        rsx! { "{value}" }
    }

    fn scoped_state_creator() -> Element {
        let slot = use_context::<ScopeSlot>();
        let state = use_hook(|| {
            let scope = DndScope::new();
            let (signal, store, sync_signal) =
                scope.with(|| (Signal::new(1), Store::new(2), SyncSignal::new_maybe_sync(3)));
            (scope, signal, store, sync_signal)
        });
        *slot.borrow_mut() = Some(state);
        rsx! {}
    }

    fn panic_scope_creator() -> Element {
        let slot = use_context::<PanicScopeSlot>();
        let state = use_hook(|| {
            let outer = DndScope::new();
            let inner = DndScope::new();
            let signal = outer.with(|| {
                let panic = catch_unwind(AssertUnwindSafe(|| {
                    inner.with(|| panic!("expected owner-restoration probe"));
                }));
                assert!(panic.is_err());
                Signal::new(7)
            });
            (outer, inner, signal)
        });
        *slot.borrow_mut() = Some(state);
        rsx! {}
    }

    fn scope_pair_creator() -> Element {
        let slot = use_context::<ScopePairSlot>();
        let state = use_hook(|| {
            let first = DndScope::new();
            let first_signal = first.with(|| Signal::new(1));
            let second = DndScope::new();
            let second_signal = second.with(|| Signal::new(2));
            (first, first_signal, second, second_signal)
        });
        *slot.borrow_mut() = Some(state);
        rsx! {}
    }

    fn scoped_survivor() -> Element {
        let value = *use_context::<Signal<i32>>().read();
        let probe = use_context::<Rc<SurvivorProbe>>();
        probe.value.set(value);
        probe.renders.set(probe.renders.get() + 1);
        rsx! { "{value}" }
    }

    fn thread_model_creator() -> Element {
        let sender = use_context::<Sender<ThreadModel>>();
        let model = use_dnd_model(|| ThreadModel {
            value: SyncSignal::new_maybe_sync(21),
        });
        sender.send(model).expect("receiver remains alive");
        rsx! {}
    }

    #[test]
    fn dnd_scope_reclaims_state_only_after_its_last_clone_drops() {
        let slot = ScopeSlot::default();
        let mut creator = VirtualDom::new(scoped_state_creator).with_root_context(slot.clone());
        creator.rebuild_in_place();
        let (scope, signal, mut store, sync_signal) = slot
            .borrow_mut()
            .take()
            .expect("creator provided its scoped state");

        // The hook-owned clone drops with the creator; this retained clone is
        // now the sole lifetime guard.
        drop(creator);
        store.set(3);
        assert_eq!(*signal.peek(), 1);
        assert_eq!(*store.peek(), 3);

        drop(scope);
        assert!(signal.try_read().is_err());
        assert!(sync_signal.try_read().is_err());
    }

    #[test]
    fn dnd_scope_restores_outer_owners_before_resuming_a_panic() {
        let slot = PanicScopeSlot::default();
        let mut creator = VirtualDom::new(panic_scope_creator).with_root_context(slot.clone());
        creator.rebuild_in_place();
        let (outer, inner, signal) = slot
            .borrow_mut()
            .take()
            .expect("creator provided its scopes");

        drop(creator);
        drop(inner);
        assert_eq!(*signal.peek(), 7, "signal must remain owned by outer");
        drop(outer);
        assert!(signal.try_read().is_err());
    }

    #[test]
    fn retiring_one_dynamic_scope_does_not_break_a_surviving_sibling() {
        let slot = ScopePairSlot::default();
        let mut creator = VirtualDom::new(scope_pair_creator).with_root_context(slot.clone());
        creator.rebuild_in_place();
        let (first, first_signal, second, second_signal) = slot
            .borrow_mut()
            .take()
            .expect("creator provided both scopes");
        let probe = Rc::new(SurvivorProbe::default());
        let mut survivor = VirtualDom::new(scoped_survivor)
            .with_root_context(second_signal)
            .with_root_context(probe.clone());
        survivor.rebuild_in_place();
        let renders_before_close = probe.renders.get();

        drop(creator);
        drop(first);
        assert!(first_signal.try_read().is_err());
        survivor.in_runtime(|| {
            let mut value = second_signal;
            value.set(9);
        });
        survivor.render_immediate(&mut dioxus::core::NoOpMutations);
        assert_eq!(probe.value.get(), 9);
        assert!(probe.renders.get() > renders_before_close);

        drop(survivor);
        drop(second);
        assert!(second_signal.try_read().is_err());
    }

    #[test]
    fn model_sync_storage_survives_its_creator_thread() {
        let (sender, receiver) = std::sync::mpsc::channel::<ThreadModel>();
        std::thread::spawn(move || {
            let mut creator =
                VirtualDom::new(thread_model_creator).with_root_context(sender.clone());
            creator.rebuild_in_place();
        })
        .join()
        .expect("creator thread completed");

        let model = receiver.recv().expect("creator published its model");
        assert_eq!(*model.value.peek(), 21);
        let mut value = model.value;
        value.set(22);
        assert_eq!(*model.value.peek(), 22);
    }

    #[test]
    fn model_survives_its_creator_window() {
        let slot = SignalModelSlot::default();
        let mut creator = VirtualDom::new(signal_model_creator).with_root_context(slot.clone());
        creator.rebuild_in_place();
        let model = slot
            .borrow_mut()
            .take()
            .expect("creator provided its model");
        let probe = Rc::new(SurvivorProbe::default());
        let mut survivor = VirtualDom::new(signal_model_survivor)
            .with_root_context(model)
            .with_root_context(probe.clone());
        survivor.rebuild_in_place();
        let renders_before_close = probe.renders.get();

        drop(creator);
        survivor.in_runtime(|| {
            let mut value = model.value;
            value.set(7);
        });
        survivor.render_immediate(&mut dioxus::core::NoOpMutations);

        assert_eq!(probe.value.get(), 7);
        assert!(probe.renders.get() > renders_before_close);
    }

    #[test]
    fn store_model_keeps_its_sync_subscription_storage_after_creator_close() {
        let slot = StoreModelSlot::default();
        let mut creator = VirtualDom::new(store_model_creator).with_root_context(slot.clone());
        creator.rebuild_in_place();
        let model = slot
            .borrow_mut()
            .take()
            .expect("creator provided its store model");
        let probe = Rc::new(SurvivorProbe::default());
        let mut survivor = VirtualDom::new(store_model_survivor)
            .with_root_context(model)
            .with_root_context(probe.clone());
        survivor.rebuild_in_place();
        let renders_before_close = probe.renders.get();

        drop(creator);
        survivor.in_runtime(|| model.state.value().set(11));
        survivor.render_immediate(&mut dioxus::core::NoOpMutations);

        assert_eq!(probe.value.get(), 11);
        assert!(probe.renders.get() > renders_before_close);
    }

    fn outcome(
        payload: Card,
        from: Option<ZoneId>,
        to: ZoneId,
        effect: DropEffect,
    ) -> DropOutcome<Card> {
        DropOutcome {
            payload,
            from,
            to,
            effect,
            mode: DragMode::Pointer,
            client: Point::default(),
            element: Point::default(),
            grab: Point::default(),
            edge: None,
        }
    }

    #[test]
    fn move_removes_from_source_and_appends_to_target() {
        let a = ZoneId(1);
        let b = ZoneId(2);
        let mut zones = HashMap::from([
            (
                a,
                vec![
                    Card {
                        id: 1,
                        title: "one",
                    },
                    Card {
                        id: 2,
                        title: "two",
                    },
                ],
            ),
            (
                b,
                vec![Card {
                    id: 3,
                    title: "three",
                }],
            ),
        ]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 2,
                    title: "two",
                },
                Some(a),
                b,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&a],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            zones[&b],
            vec![
                Card {
                    id: 3,
                    title: "three"
                },
                Card {
                    id: 2,
                    title: "two"
                }
            ]
        );
    }

    #[test]
    fn copy_leaves_source_and_allows_new_identity() {
        let a = ZoneId(1);
        let b = ZoneId(2);
        let mut zones = HashMap::from([
            (
                a,
                vec![Card {
                    id: 1,
                    title: "one",
                }],
            ),
            (b, Vec::new()),
        ]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                b,
                DropEffect::Copy,
            ),
            |card| card.id,
            |mut card| {
                card.id = 10;
                card
            },
        );

        assert_eq!(
            zones[&a],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            zones[&b],
            vec![Card {
                id: 10,
                title: "one"
            }]
        );
    }

    /// Pins the self-drop semantics documented on `apply_clone_or_move`: a
    /// `Move` back onto the source zone reorders the item to the end.
    #[test]
    fn move_onto_own_zone_reorders_to_end() {
        let a = ZoneId(1);
        let mut zones = HashMap::from([(
            a,
            vec![
                Card {
                    id: 1,
                    title: "one",
                },
                Card {
                    id: 2,
                    title: "two",
                },
            ],
        )]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                a,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&a],
            vec![
                Card {
                    id: 2,
                    title: "two"
                },
                Card {
                    id: 1,
                    title: "one"
                }
            ]
        );
    }

    /// A payload from outside any zone (palette, external drop) has no
    /// source to prune; `Move` just appends.
    #[test]
    fn move_without_source_zone_just_appends() {
        let b = ZoneId(2);
        let mut zones = HashMap::from([(b, Vec::new())]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 7,
                    title: "seven",
                },
                None,
                b,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&b],
            vec![Card {
                id: 7,
                title: "seven"
            }]
        );
    }

    /// An unknown target zone is created rather than losing the item.
    #[test]
    fn unknown_target_zone_is_created() {
        let a = ZoneId(1);
        let ghost = ZoneId(99);
        let mut zones = HashMap::from([(
            a,
            vec![Card {
                id: 1,
                title: "one",
            }],
        )]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                ghost,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert!(zones[&a].is_empty());
        assert_eq!(
            zones[&ghost],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
    }

    #[test]
    fn list_move_removes_from_source_and_appends_to_target() {
        let mut source = vec![
            Card {
                id: 1,
                title: "one",
            },
            Card {
                id: 2,
                title: "two",
            },
        ];
        let mut target = vec![Card {
            id: 3,
            title: "three",
        }];

        apply_list_clone_or_move(
            Some(&mut source),
            &mut target,
            outcome(
                Card {
                    id: 2,
                    title: "two",
                },
                Some(ZoneId(1)),
                ZoneId(2),
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            source,
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            target,
            vec![
                Card {
                    id: 3,
                    title: "three"
                },
                Card {
                    id: 2,
                    title: "two"
                }
            ]
        );
    }

    #[test]
    fn list_copy_leaves_source_and_allows_new_identity() {
        let mut source = vec![Card {
            id: 1,
            title: "one",
        }];
        let mut target = Vec::new();

        apply_list_clone_or_move(
            Some(&mut source),
            &mut target,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(ZoneId(1)),
                ZoneId(2),
                DropEffect::Copy,
            ),
            |card| card.id,
            |mut card| {
                card.id = 10;
                card
            },
        );

        assert_eq!(
            source,
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            target,
            vec![Card {
                id: 10,
                title: "one"
            }]
        );
    }

    /// `Move` into a list without a source (`None`) skips removal.
    #[test]
    fn list_move_without_source_just_appends() {
        let mut target = Vec::new();

        apply_list_clone_or_move(
            None,
            &mut target,
            outcome(
                Card {
                    id: 7,
                    title: "seven",
                },
                None,
                ZoneId(2),
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            target,
            vec![Card {
                id: 7,
                title: "seven"
            }]
        );
    }

    #[test]
    fn unsupported_effect_is_explicit_and_does_not_mutate() {
        let zone = ZoneId(1);
        let original = vec![Card {
            id: 1,
            title: "one",
        }];
        let mut zones = HashMap::from([(zone, original.clone())]);
        let result = try_apply_clone_or_move(
            &mut zones,
            outcome(original[0].clone(), Some(zone), ZoneId(2), DropEffect::Link),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            result,
            Err(ApplyDropError::UnsupportedEffect(DropEffect::Link))
        );
        assert_eq!(zones, HashMap::from([(zone, original)]));
    }

    #[test]
    fn legacy_helpers_keep_their_unit_return_contract() {
        let zone = ZoneId(1);
        let mut zones = HashMap::new();
        let _: () = apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                None,
                zone,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        let mut target = Vec::new();
        let _: () = apply_list_clone_or_move(
            None,
            &mut target,
            outcome(
                Card {
                    id: 2,
                    title: "two",
                },
                None,
                zone,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );
    }
}