rok-ui 0.9.2

shadcn/ui-style component system for GPUI desktop apps, with a React-like developer experience.
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
//! Mutations: writes with pending / error / data state, invalidation and optimistic updates.

use std::{
    collections::VecDeque,
    fmt,
    future::Future,
    rc::Rc,
    sync::Arc,
    time::{Duration, Instant},
};

use gpui::{App, Entity, Global, Task};

use super::{
    cache::{cache, AnyData},
    invalidate,
    options::BoxFuture,
    services::task_cx,
    QueryKey, TaskCx,
};
use crate::Cx;

type Runner<I, O, E> = Arc<dyn Fn(TaskCx, I) -> BoxFuture<Result<O, E>> + Send + Sync>;
type SuccessHandler<I, O> = Rc<dyn Fn(&O, &I, &mut App)>;
type ErrorHandler<I, E> = Rc<dyn Fn(&E, &I, &mut App)>;
type OptimisticUpdate<I> = Rc<dyn Fn(&I, &mut Optimistic<'_>)>;

/// What a mutation runs and what happens around it.
///
/// ```
/// use rok_ui::{query::MutationOptions, query_key};
///
/// let rename = MutationOptions::new(|_cx, name: String| async move {
///     Ok::<_, std::io::Error>(name.to_uppercase())
/// })
/// .invalidates(query_key!["users"]);
/// # let _ = rename;
/// ```
pub struct MutationOptions<I, O, E> {
    run: Runner<I, O, E>,
    key: Option<QueryKey>,
    invalidates: Vec<QueryKey>,
    on_success: Vec<SuccessHandler<I, O>>,
    on_error: Vec<ErrorHandler<I, E>>,
    optimistic: Option<OptimisticUpdate<I>>,
}

impl<I, O, E> MutationOptions<I, O, E>
where
    I: Send + 'static,
    O: Send + 'static,
    E: Send + 'static,
{
    /// A mutation that runs `run` on the shared background runtime with the mutation's input.
    pub fn new<F, Fut>(run: F) -> Self
    where
        F: Fn(TaskCx, I) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<O, E>> + Send + 'static,
    {
        Self {
            run: Arc::new(move |cx, input| Box::pin(run(cx, input))),
            key: None,
            invalidates: Vec::new(),
            on_success: Vec::new(),
            on_error: Vec::new(),
            optimistic: None,
        }
    }
}

impl<I, O, E> MutationOptions<I, O, E> {
    /// Name the mutation, like TanStack Query's `mutationKey`: [`mutations`] and the devtools
    /// show it. Unnamed mutations show as `mutation`.
    #[must_use]
    pub fn key(mut self, key: QueryKey) -> Self {
        self.key = Some(key);
        self
    }

    /// Invalidate every query whose key starts with `prefix` after a success.
    #[must_use]
    pub fn invalidates(mut self, prefix: QueryKey) -> Self {
        self.invalidates.push(prefix);
        self
    }

    /// Run after a success, on the UI thread, before invalidated queries refetch.
    #[must_use]
    pub fn on_success(mut self, handler: impl Fn(&O, &I, &mut App) + 'static) -> Self {
        self.on_success.push(Rc::new(handler));
        self
    }

    /// Run after a failure, on the UI thread, after optimistic updates are rolled back.
    #[must_use]
    pub fn on_error(mut self, handler: impl Fn(&E, &I, &mut App) + 'static) -> Self {
        self.on_error.push(Rc::new(handler));
        self
    }

    /// Update cached queries before the mutation runs, for instant UI. The changes are rolled
    /// back if it fails.
    #[must_use]
    pub fn optimistic(mut self, update: impl Fn(&I, &mut Optimistic<'_>) + 'static) -> Self {
        self.optimistic = Some(Rc::new(update));
        self
    }
}

impl<I, O, E> Clone for MutationOptions<I, O, E> {
    fn clone(&self) -> Self {
        Self {
            run: self.run.clone(),
            key: self.key.clone(),
            invalidates: self.invalidates.clone(),
            on_success: self.on_success.clone(),
            on_error: self.on_error.clone(),
            optimistic: self.optimistic.clone(),
        }
    }
}

/// Cache access for [`MutationOptions::optimistic`]. Every change is recorded so it can be
/// rolled back.
pub struct Optimistic<'a> {
    cx: &'a mut App,
    snapshots: Vec<Snapshot>,
}

struct Snapshot {
    key: QueryKey,
    data: Option<AnyData>,
}

impl Optimistic<'_> {
    /// Change the cached data for `key` in place, if there is data of type `T`.
    pub fn update<T: Clone + 'static>(&mut self, key: &QueryKey, update: impl FnOnce(&mut T)) {
        self.record(key);
        super::update_query_data(self.cx, key, update);
    }

    /// Replace the cached data for `key`.
    pub fn set<T: 'static>(&mut self, key: &QueryKey, data: T) {
        self.record(key);
        super::set_query_data(self.cx, key, data);
    }

    fn record(&mut self, key: &QueryKey) {
        if self.snapshots.iter().any(|snapshot| &snapshot.key == key) {
            return;
        }
        let data = cache(self.cx)
            .entries
            .get(key)
            .and_then(|entry| entry.data.clone());
        self.snapshots.push(Snapshot {
            key: key.clone(),
            data,
        });
    }
}

fn roll_back(cx: &mut App, snapshots: Vec<Snapshot>) {
    let entries = &mut cache(cx).entries;
    for snapshot in snapshots {
        match snapshot.data {
            Some(data) => {
                if let Some(entry) = entries.get_mut(&snapshot.key) {
                    entry.set_data(data);
                }
            }
            None => {
                entries.remove(&snapshot.key);
            }
        }
    }
}

/// Where a mutation is in its lifecycle.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MutationStatus {
    /// Not run yet (or reset).
    Idle,
    /// Running.
    Pending,
    /// The last run succeeded.
    Success,
    /// The last run failed.
    Error,
}

struct MutationState<O, E> {
    status: MutationStatus,
    data: Option<Rc<O>>,
    error: Option<Rc<E>>,
    run: u64,
    submitted_at: Option<Instant>,
    task: Option<Task<()>>,
    /// This call site's latest run in the [`MutationLog`].
    logged: Option<u64>,
}

impl<O, E> Default for MutationState<O, E> {
    fn default() -> Self {
        Self {
            status: MutationStatus::Idle,
            data: None,
            error: None,
            run: 0,
            submitted_at: None,
            task: None,
            logged: None,
        }
    }
}

/// A mutation for one call site, returned by [`use_mutation`] and
/// [`use_procedure`](super::use_procedure). Cheap to clone into event handlers.
pub struct Mutation<I, O, E> {
    state: Entity<MutationState<O, E>>,
    options: MutationOptions<I, O, E>,
    status: MutationStatus,
    data: Option<Rc<O>>,
    error: Option<Rc<E>>,
}

impl<I, O, E> Clone for Mutation<I, O, E> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            options: self.options.clone(),
            status: self.status,
            data: self.data.clone(),
            error: self.error.clone(),
        }
    }
}

impl<I, O, E> fmt::Debug for Mutation<I, O, E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Mutation")
            .field("status", &self.status)
            .finish_non_exhaustive()
    }
}

impl<I, O, E> Mutation<I, O, E>
where
    I: Clone + Send + 'static,
    O: Send + 'static,
    E: Send + 'static,
{
    /// Run the mutation with `input`. A run started while another is pending supersedes it:
    /// only the latest run's result is kept.
    pub fn mutate(&self, cx: &mut App, input: I) {
        let options = self.options.clone();
        let snapshots = match &options.optimistic {
            Some(update) => {
                let mut optimistic = Optimistic {
                    cx,
                    snapshots: Vec::new(),
                };
                update(&input, &mut optimistic);
                optimistic.snapshots
            }
            None => Vec::new(),
        };

        let logged = log_start(cx, options.key.clone());
        let (run_id, superseded) = self.state.update(cx, |state, _| {
            state.run += 1;
            state.status = MutationStatus::Pending;
            state.submitted_at = Some(Instant::now());
            (state.run, state.logged.replace(logged))
        });
        if let Some(superseded) = superseded {
            log_finish(cx, superseded, MutationStatus::Idle);
        }
        let services = task_cx(cx);
        let run = options.run.clone();
        let sent_input = input.clone();
        let running = crate::runtime::spawn(async move { run(services, sent_input).await });
        let state = self.state.clone();
        let task = cx.spawn(async move |cx| {
            let outcome = running.await;
            cx.update(|cx| {
                if state.read(cx).run != run_id {
                    return;
                }
                let status = match &outcome {
                    Ok(Ok(_)) => MutationStatus::Success,
                    Ok(Err(_)) => MutationStatus::Error,
                    Err(_) => MutationStatus::Idle,
                };
                log_finish(cx, logged, status);
                match outcome {
                    Ok(Ok(data)) => {
                        let data = Rc::new(data);
                        state.update(cx, |state, _| {
                            state.status = MutationStatus::Success;
                            state.data = Some(data.clone());
                            state.error = None;
                            state.task = None;
                        });
                        for handler in &options.on_success {
                            handler(&data, &input, cx);
                        }
                        for prefix in &options.invalidates {
                            invalidate(cx, prefix);
                        }
                    }
                    Ok(Err(error)) => {
                        roll_back(cx, snapshots);
                        let error = Rc::new(error);
                        state.update(cx, |state, _| {
                            state.status = MutationStatus::Error;
                            state.error = Some(error.clone());
                            state.task = None;
                        });
                        for handler in &options.on_error {
                            handler(&error, &input, cx);
                        }
                    }
                    Err(_) => {
                        roll_back(cx, snapshots);
                        state.update(cx, |state, _| {
                            state.status = MutationStatus::Idle;
                            state.task = None;
                        });
                    }
                }
                cx.refresh_windows();
            })
            .ok();
        });
        self.state.update(cx, |state, _| state.task = Some(task));
        cx.refresh_windows();
    }

    /// A click handler that runs the mutation with a clone of `input`.
    pub fn mutate_handler<Event>(
        &self,
        input: I,
    ) -> impl Fn(&Event, &mut gpui::Window, &mut App) + 'static {
        let mutation = self.clone();
        move |_, _, cx| mutation.mutate(cx, input.clone())
    }
}

impl<I, O: 'static, E: 'static> Mutation<I, O, E> {
    /// Run `handler` after a success, in addition to the options' handlers.
    #[must_use]
    pub fn on_success(mut self, handler: impl Fn(&O, &I, &mut App) + 'static) -> Self {
        self.options.on_success.push(Rc::new(handler));
        self
    }

    /// Run `handler` after a failure, in addition to the options' handlers.
    #[must_use]
    pub fn on_error(mut self, handler: impl Fn(&E, &I, &mut App) + 'static) -> Self {
        self.options.on_error.push(Rc::new(handler));
        self
    }

    /// Update cached queries before the mutation runs; rolled back if it fails.
    #[must_use]
    pub fn optimistic(mut self, update: impl Fn(&I, &mut Optimistic<'_>) + 'static) -> Self {
        self.options.optimistic = Some(Rc::new(update));
        self
    }

    /// Where the mutation is, as of this render.
    #[must_use]
    pub fn status(&self) -> MutationStatus {
        self.status
    }

    /// Whether a run is in progress.
    #[must_use]
    pub fn is_pending(&self) -> bool {
        self.status == MutationStatus::Pending
    }

    /// Whether nothing has run since the mutation was created or reset.
    #[must_use]
    pub fn is_idle(&self) -> bool {
        self.status == MutationStatus::Idle
    }

    /// Whether the last run succeeded.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.status == MutationStatus::Success
    }

    /// Whether the last run failed.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.status == MutationStatus::Error
    }

    /// The last successful result.
    #[must_use]
    pub fn data(&self) -> Option<&O> {
        self.data.as_deref()
    }

    /// The last error.
    #[must_use]
    pub fn error(&self) -> Option<&E> {
        self.error.as_deref()
    }

    /// Forget the last result and return to idle. A pending run's result is dropped.
    pub fn reset(&self, cx: &mut App) {
        let logged = self.state.update(cx, |state, _| {
            let logged = state.logged;
            *state = MutationState {
                run: state.run + 1,
                ..MutationState::default()
            };
            logged
        });
        if let Some(logged) = logged {
            log_finish(cx, logged, MutationStatus::Idle);
        }
        cx.refresh_windows();
    }
}

/// A mutation for this call site, like TanStack Query's `useMutation`.
///
/// ```no_run
/// # use rok_ui::{prelude::*, query::{self, MutationOptions}, query_key};
/// #[component]
/// fn SaveButton(cx: &mut Cx) -> impl IntoElement {
///     let save = query::use_mutation(
///         cx,
///         MutationOptions::new(|_cx, title: String| async move {
///             Ok::<_, std::io::Error>(title)
///         })
///         .invalidates(query_key!["notes"]),
///     );
///     Button::new("save")
///         .label("Save")
///         .loading(save.is_pending())
///         .on_click(save.mutate_handler("Untitled".to_string()))
/// }
/// ```
#[track_caller]
pub fn use_mutation<I, O, E>(cx: &mut Cx, options: MutationOptions<I, O, E>) -> Mutation<I, O, E>
where
    O: 'static,
    E: 'static,
{
    let state = cx
        .window
        .use_state(cx.app, |_, _| MutationState::<O, E>::default());
    let (status, data, error) = {
        let current = state.read(cx.app);
        (current.status, current.data.clone(), current.error.clone())
    };
    Mutation {
        state,
        options,
        status,
        data,
        error,
    }
}

/// How many finished runs [`mutations`] keeps.
const LOG_LIMIT: usize = 50;

/// Recent mutation runs, newest last, for [`mutations`] and the devtools.
#[derive(Default)]
struct MutationLog {
    next: u64,
    entries: VecDeque<MutationInfo>,
}

impl Global for MutationLog {}

/// One mutation run, from [`mutations`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MutationInfo {
    /// The mutation's [`key`](MutationOptions::key), if it has one.
    pub key: Option<QueryKey>,
    /// `Pending` while it runs; `Idle` when it was superseded, reset or cancelled.
    pub status: MutationStatus,
    /// When it started.
    pub submitted_at: Instant,
    /// How long it ran, once finished.
    pub duration: Option<Duration>,
    id: u64,
}

fn log_start(cx: &mut App, key: Option<QueryKey>) -> u64 {
    let log = cx.default_global::<MutationLog>();
    log.next += 1;
    log.entries.push_back(MutationInfo {
        key,
        status: MutationStatus::Pending,
        submitted_at: Instant::now(),
        duration: None,
        id: log.next,
    });
    // Drop the oldest finished runs; running ones stay until they finish.
    while log.entries.len() > LOG_LIMIT {
        let Some(finished) = log
            .entries
            .iter()
            .position(|entry| entry.status != MutationStatus::Pending)
        else {
            break;
        };
        log.entries.remove(finished);
    }
    log.next
}

fn log_finish(cx: &mut App, id: u64, status: MutationStatus) {
    let log = cx.default_global::<MutationLog>();
    if let Some(entry) = log.entries.iter_mut().find(|entry| entry.id == id) {
        if entry.status == MutationStatus::Pending {
            entry.status = status;
            entry.duration = Some(entry.submitted_at.elapsed());
        }
    }
}

/// Recent mutation runs across the app, newest first, like TanStack Query's mutation cache:
/// running ones and up to 50 finished ones.
#[must_use]
pub fn mutations(cx: &App) -> Vec<MutationInfo> {
    cx.try_global::<MutationLog>()
        .map(|log| log.entries.iter().rev().cloned().collect())
        .unwrap_or_default()
}