dioxus-mind-elixir 0.1.1

A Rust-native Dioxus mind map component with CSS-variable styling
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
use crate::plugins::{Capability, Command, Plugin, PluginRegistry};
use crate::{
    CoreEvent, MindMapData, MindMapError, MindMapState, Operation, OperationOptions,
    OperationResult,
};
use dioxus::prelude::*;
use std::{collections::BTreeMap, rc::Rc};

type Before = Rc<dyn Fn(&Operation) -> bool>;
type Listener = Rc<dyn Fn(CoreEvent)>;

/// Copyable shared document handle. Mutation always passes through checked core
/// transactions. Individual views own their viewport, editor and mounted nodes.
#[derive(Clone, Copy, PartialEq)]
pub struct MindMapHandle {
    state: Signal<MindMapState>,
    before: Signal<Option<Before>>,
    listener: Signal<Option<Listener>>,
    editor_owner: Signal<Option<usize>>,
    pending: Signal<Option<(usize, PendingEdit)>>,
    subscribers: Signal<BTreeMap<u64, Listener>>,
    next_subscription: Signal<u64>,
    plugins: Signal<PluginRegistry>,
}

/// A topic draft that is being edited in one of the views. Hosts read it to
/// protect unsaved text (before switching documents or closing a window) and
/// decide with [`MindMapHandle::commit_pending`] or
/// [`MindMapHandle::cancel_pending`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingEdit {
    /// Edited node.
    pub id: String,
    /// Topic when editing started.
    pub original: String,
    /// Current draft text.
    pub draft: String,
}
impl PendingEdit {
    /// Whether committing would change the document.
    pub fn is_changed(&self) -> bool {
        !self.draft.trim().is_empty() && self.draft != self.original
    }
}

/// Create one shared document for any number of views in the current scope.
/// The initial value is consumed only when the component first mounts.
pub fn use_mind_map(data: MindMapData) -> Result<MindMapHandle, MindMapError> {
    use_hook(|| {
        MindMapState::new(data).map(|state| MindMapHandle {
            state: Signal::new(state),
            before: Signal::new(None),
            listener: Signal::new(None),
            editor_owner: Signal::new(None),
            pending: Signal::new(None),
            subscribers: Signal::new(BTreeMap::new()),
            next_subscription: Signal::new(0),
            plugins: Signal::new(PluginRegistry::default()),
        })
    })
}
impl MindMapHandle {
    /// Read a reactive persistent snapshot. No internal mutable signal is exposed.
    pub fn document(self) -> Result<MindMapData, MindMapError> {
        self.state
            .try_read()
            .map(|state| state.data().clone())
            .map_err(|_| MindMapError::StaleOperation)
    }
    /// Current selected IDs, reactively tracked.
    pub fn selection(self) -> Result<Vec<String>, MindMapError> {
        self.state
            .try_read()
            .map(|state| state.selection().to_vec())
            .map_err(|_| MindMapError::StaleOperation)
    }
    /// Current generation, reactively tracked.
    pub fn revision(self) -> Result<u64, MindMapError> {
        self.state
            .try_read()
            .map(|state| state.revision())
            .map_err(|_| MindMapError::StaleOperation)
    }
    /// Whether mutation is disabled.
    pub fn is_read_only(self) -> Result<bool, MindMapError> {
        self.state
            .try_read()
            .map(|state| state.is_read_only())
            .map_err(|_| MindMapError::StaleOperation)
    }
    /// Set a synchronous veto hook. Invoked without a state borrow; reentrant
    /// mutations cause the outer operation to fail with StaleOperation.
    pub fn set_before(
        mut self,
        hook: impl Fn(&Operation) -> bool + 'static,
    ) -> Result<(), MindMapError> {
        *self
            .before
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = Some(Rc::new(hook));
        Ok(())
    }
    /// Clear the veto hook.
    pub fn clear_before(mut self) -> Result<(), MindMapError> {
        *self
            .before
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = None;
        Ok(())
    }
    /// Install a host event listener. Events are delivered after releasing state.
    pub fn set_listener(
        mut self,
        listener: impl Fn(CoreEvent) + 'static,
    ) -> Result<(), MindMapError> {
        *self
            .listener
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = Some(Rc::new(listener));
        Ok(())
    }
    /// Execute a checked mutation using the current before hook.
    pub fn apply(self, operation: Operation) -> Result<OperationResult, MindMapError> {
        self.apply_with(operation, OperationOptions::default())
    }
    /// Execute a checked mutation with explicit recording options.
    pub fn apply_with(
        mut self,
        operation: Operation,
        options: OperationOptions,
    ) -> Result<OperationResult, MindMapError> {
        let revision = self.revision()?;
        if self.is_read_only()? {
            return Err(MindMapError::ReadOnly);
        }
        let before = self
            .before
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            .clone();
        if let Some(before) = before {
            if !before(&operation) {
                return Err(MindMapError::Rejected);
            }
        }
        let result = {
            let mut state = self
                .state
                .try_write()
                .map_err(|_| MindMapError::StaleOperation)?;
            if state.revision() != revision {
                return Err(MindMapError::StaleOperation);
            }
            state.apply_with(operation, options)?
        };
        self.emit(&result.events)?;
        Ok(result)
    }
    /// Select existing IDs, including collapsed descendants.
    pub fn select(mut self, ids: &[String]) -> Result<(), MindMapError> {
        let events = self
            .state
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .select(ids)?;
        self.emit(&events)
    }
    /// Enable/disable all document mutation entry points.
    pub fn set_read_only(mut self, value: bool) -> Result<(), MindMapError> {
        self.state
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .set_read_only(value);
        Ok(())
    }
    /// Undo and restore selection.
    pub fn undo(mut self) -> Result<(), MindMapError> {
        let events = self
            .state
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .undo()?;
        self.emit(&events)
    }
    /// Redo and restore selection.
    pub fn redo(mut self) -> Result<(), MindMapError> {
        let events = self
            .state
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .redo()?;
        self.emit(&events)
    }
    /// Validate and replace the document, clearing selection and history.
    pub fn refresh(mut self, data: MindMapData) -> Result<(), MindMapError> {
        let events = self
            .state
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .refresh(data)?;
        self.emit(&events)
    }
    /// The topic draft currently being edited, reactively tracked.
    pub fn pending_edit(self) -> Result<Option<PendingEdit>, MindMapError> {
        self.pending
            .try_read()
            .map(|pending| pending.as_ref().map(|(_, edit)| edit.clone()))
            .map_err(|_| MindMapError::StaleOperation)
    }
    /// Apply the pending draft as a normal undoable topic change and close the
    /// editor. Blank or unchanged drafts only close the editor. Returns whether
    /// the document changed. On failure the draft stays pending.
    pub fn commit_pending(mut self) -> Result<bool, MindMapError> {
        let pending = self
            .pending
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            .clone();
        let Some((_, edit)) = pending else {
            return Ok(false);
        };
        let changed = if edit.is_changed() {
            self.apply(Operation::SetTopic {
                id: edit.id.clone(),
                topic: edit.draft.clone(),
            })?
            .changed
        } else {
            false
        };
        *self
            .pending
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = None;
        Ok(changed)
    }
    /// Discard the pending draft and close the editor.
    pub fn cancel_pending(mut self) -> Result<(), MindMapError> {
        *self
            .pending
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = None;
        Ok(())
    }
    pub(crate) fn begin_edit(
        mut self,
        owner: usize,
        id: &str,
        original: &str,
    ) -> Result<(), MindMapError> {
        self.claim_editor(owner)?;
        *self
            .pending
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = Some((
            owner,
            PendingEdit {
                id: id.into(),
                original: original.into(),
                draft: original.into(),
            },
        ));
        Ok(())
    }
    pub(crate) fn update_draft(mut self, owner: usize, draft: String) {
        if let Ok(mut pending) = self.pending.try_write() {
            if let Some((current, edit)) = pending.as_mut() {
                if *current == owner {
                    edit.draft = draft;
                }
            }
        }
    }
    /// Start a draft without a view (tests and host-driven editors).
    #[doc(hidden)]
    pub fn begin_edit_for_test(self, id: &str, original: &str) -> Result<(), MindMapError> {
        self.begin_edit(usize::MAX, id, original)
    }
    /// Update a draft started by [`Self::begin_edit_for_test`].
    #[doc(hidden)]
    pub fn update_draft_for_test(self, draft: &str) {
        self.update_draft(usize::MAX, draft.into());
    }
    /// Whether `owner` still edits node `id` (the host may have closed it).
    pub(crate) fn edits(self, owner: usize, id: &str) -> bool {
        self.pending
            .try_read()
            .is_ok_and(|p| p.as_ref().is_some_and(|(o, e)| *o == owner && e.id == id))
    }
    pub(crate) fn claim_editor(mut self, owner: usize) -> Result<(), MindMapError> {
        *self
            .editor_owner
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = Some(owner);
        Ok(())
    }
    pub(crate) fn owns_editor(self, owner: usize) -> Result<bool, MindMapError> {
        Ok(*self
            .editor_owner
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            == Some(owner))
    }
    /// Add an independent listener. Dropping the returned guard unsubscribes it.
    pub fn subscribe(
        mut self,
        listener: impl Fn(CoreEvent) + 'static,
    ) -> Result<Subscription, MindMapError> {
        let id = *self
            .next_subscription
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?;
        let next = id
            .checked_add(1)
            .ok_or_else(|| MindMapError::InvalidOperation("Subscription ID exhausted".into()))?;
        *self
            .next_subscription
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)? = next;
        self.subscribers
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .insert(id, Rc::new(listener));
        Ok(Subscription { handle: self, id })
    }
    /// Register a plugin for the lifetime of a guard. No document/history mutation.
    pub fn register_plugin(mut self, plugin: Plugin) -> Result<PluginGuard, MindMapError> {
        let id = plugin.id.clone();
        self.plugins
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .register(plugin)?;
        Ok(PluginGuard {
            handle: self,
            id,
            subscriptions: Vec::new(),
        })
    }
    /// Toggle an existing registration. Disabled capabilities disappear reactively.
    pub fn set_plugin_enabled(mut self, id: &str, enabled: bool) -> Result<(), MindMapError> {
        self.plugins
            .try_write()
            .map_err(|_| MindMapError::StaleOperation)?
            .set_enabled(id, enabled)
    }
    /// Test an enabled capability for this document only.
    pub fn has_plugin(self, capability: Capability) -> bool {
        self.plugins
            .try_read()
            .is_ok_and(|plugins| plugins.provides(capability))
    }
    /// Commands supplied by enabled plugins.
    pub fn plugin_commands(self) -> Result<Vec<Command>, MindMapError> {
        Ok(self
            .plugins
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            .commands())
    }
    fn emit(self, events: &[CoreEvent]) -> Result<(), MindMapError> {
        let listener = self
            .listener
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            .clone();
        let subscribers = self
            .subscribers
            .try_read()
            .map_err(|_| MindMapError::StaleOperation)?
            .iter()
            .map(|(id, listener)| (*id, listener.clone()))
            .collect::<Vec<_>>();
        for event in events {
            if let Some(listener) = &listener {
                listener(event.clone());
            }
            for (id, callback) in &subscribers {
                if self
                    .subscribers
                    .try_read()
                    .is_ok_and(|current| current.contains_key(id))
                {
                    callback(event.clone());
                }
            }
        }
        Ok(())
    }
}

/// An event subscription; dropping it releases the callback, including on unmount.
pub struct Subscription {
    handle: MindMapHandle,
    id: u64,
}
impl Drop for Subscription {
    fn drop(&mut self) {
        if let Ok(mut entries) = self.handle.subscribers.try_write() {
            entries.remove(&self.id);
        }
    }
}
/// Registration lifetime and owned event subscriptions for one plugin instance.
pub struct PluginGuard {
    handle: MindMapHandle,
    id: String,
    subscriptions: Vec<Subscription>,
}
impl PluginGuard {
    /// Attach a listener that is removed together with this plugin.
    pub fn subscribe(
        &mut self,
        listener: impl Fn(CoreEvent) + 'static,
    ) -> Result<(), MindMapError> {
        let handle = self.handle;
        let id = self.id.clone();
        self.subscriptions.push(handle.subscribe(move |event| {
            let enabled = handle
                .plugins
                .try_read()
                .is_ok_and(|registry| registry.is_enabled(&id));
            if enabled {
                listener(event);
            }
        })?);
        Ok(())
    }
    /// Toggle this registration without releasing it.
    pub fn set_enabled(&self, enabled: bool) -> Result<(), MindMapError> {
        self.handle.set_plugin_enabled(&self.id, enabled)
    }
}
impl Drop for PluginGuard {
    fn drop(&mut self) {
        if let Ok(mut registry) = self.handle.plugins.try_write() {
            let _ = registry.unregister(&self.id);
        }
    }
}
/// Install plugins for the current component's lifetime. Returns errors explicitly.
pub fn use_plugins(
    handle: MindMapHandle,
    plugins: Vec<Plugin>,
) -> Result<Rc<Vec<PluginGuard>>, MindMapError> {
    use_hook(|| {
        plugins
            .into_iter()
            .map(|plugin| handle.register_plugin(plugin))
            .collect::<Result<Vec<_>, _>>()
            .map(Rc::new)
    })
}