remedy-ui 1.1.2

RemedyUI for apps: open windows, run them on the platform's bridge with the GPU renderer (CPU fallback), persist window geometry, timers and the clipboard.
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
# Thinking in signals

A RemedyUI component is a function that runs once. It builds elements and connects them to
state. When the state changes, only the properties that read it update. Nothing re-runs the
component, nothing diffs a tree, and nothing runs while nothing changes.

The state lives in [`Signal`](crate::reactive::Signal)s. Values computed from it are
[`Memo`](crate::reactive::Memo)s. Work that follows it is an
[`Effect`](crate::reactive::Effect), or more often a binding on an element
([`El::bind`](crate::El::bind), and properties given a closure or a signal). This page shows each of them, then
batching, untracked reads and who owns what.

## Signals

A signal holds one value. Reading it inside a memo, effect or binding subscribes that reader;
writing it updates exactly the readers that read it.

```
use remedy_ui::reactive::Signal;

let count = Signal::new(0u32);
count.set(2);
count.update(|c| *c += 1);
assert_eq!(count.get(), 3);

// `with` borrows instead of cloning, for big values.
let names = Signal::new(vec!["Ada".to_string(), "Grace".to_string()]);
assert_eq!(names.with(|n| n.len()), 2);
```

A `Signal` is a `Copy` handle, so closures capture it by value with no `Rc` or `clone`. Its
value lives in the UI thread's reactive runtime, and only that thread can reach it.

- [`set`]crate::reactive::Signal::set and [`update`]crate::reactive::Signal::update
  always notify readers.
- [`set_if_changed`]crate::reactive::Signal::set_if_changed notifies only when the new
  value differs, for values that are often written with what they already hold.
- [`take`]crate::reactive::Signal::take moves the value out and leaves the default.

## Memos

A memo is a value derived from signals. It runs again only when something it read changed,
and when its new value equals the old one it stops there: nothing downstream runs.

```
use remedy_ui::reactive::{Effect, Memo, Signal};
use std::cell::Cell;
use std::rc::Rc;

let text = Signal::new("hello".to_string());
let words = Memo::new(move || text.with(|t| t.split_whitespace().count()));

let runs = Rc::new(Cell::new(0));
let r = runs.clone();
Effect::new(move || {
    let _ = words.get();
    r.set(r.get() + 1);
});
assert_eq!(runs.get(), 1);

text.set("hello world".into()); // two words: the effect runs
assert_eq!(runs.get(), 2);
text.set("hello there".into()); // still two words: the memo stops the change
assert_eq!(runs.get(), 2);
```

Memos need `PartialEq`, which is how they know a value did not change. They are lazy: a
memo nobody reads does not run.

## Effects

An effect runs once when created and again whenever a signal it read changes. Effects are
for work outside the UI: saving a draft, logging, telling another part of the app. Effects
never see half-updated state: when two signals change together, the effect runs once, after
both.

```
use remedy_ui::reactive::{Effect, Signal};
use std::cell::RefCell;
use std::rc::Rc;

let draft = Signal::new(String::new());
let saved = Rc::new(RefCell::new(Vec::new()));
let s = saved.clone();
Effect::new(move || s.borrow_mut().push(draft.get()));

draft.set("Hi".into());
draft.set("Hi there".into());
assert_eq!(*saved.borrow(), ["", "Hi", "Hi there"]);
```

An effect tracks what it read on its latest run, not what it might read. A branch that was
not taken subscribes nothing, so there are no dependency lists to keep right.

## Binds: signals on elements

On elements, use a binding instead of a free-standing effect. A binding is an effect that
belongs to its element: it runs while the element lives and is disposed with it.

- [`El::text`]crate::El::text: the element's text.
- [`El::style`]crate::El::style: its local style.
- [`El::disabled`]crate::El::disabled: whether it can be used.
- [`El::variant`]crate::El::variant: which variant of its widget it shows.
- [`El::semantics`]crate::El::semantics: what it tells screen readers.
- The widgets' labels: [`widgets::text`]crate::widgets::text,
  [`widgets::button`]crate::widgets::button and the rest.
- [`El::bind`]crate::El::bind: anything else.

Each of these takes an [`IntoProp`](crate::view::IntoProp): a plain value sets it once and
creates no binding, while a [`Signal`](crate::reactive::Signal), a
[`Memo`](crate::reactive::Memo) or a closure binds it. Making a property follow state never
changes the call's shape.

Each one marks only the work its change needs. A new text relays out that text and repaints
it; a new color only repaints.

```
# use remedy_ui::AppConfig;
# use remedy_ui::testing::TestApp;
use remedy_ui::reactive::Signal;
use remedy_ui::widgets as w;
use remedy_ui::{App, WindowSpec};

let count = Signal::new(0u32);
let app = move |app: &App| {
    app.open(WindowSpec::new("Counter"), move |ui, _| {
        let add = w::button(ui, "Add one", move || count.update(|c| *c += 1));
        let shown = w::text(ui, move || format!("Count: {}", count.get()));
        let reset = w::button(ui, "Reset", move || count.set(0)).disabled(move || count.get() == 0);
        ui.root().child(add).child(shown).child(reset);
    });
};
# let mut test = TestApp::new(AppConfig::new("Counter"), app);
# let Some(ui) = test.ui() else { unreachable!("the window is open") };
# let shows = |ui: &remedy_ui::Ui, name: &str| ui.reader_view().iter().any(|n| n.name.as_deref() == Some(name));
assert!(shows(&ui, "Count: 0"));

count.set(2); // from a handler, a timer, a background result...
test.frames(1);
assert!(shows(&ui, "Count: 2"));
```

The component ran once. Setting `count` re-ran two small closures: the text and the
disabled state.

When a value is the same for the element's whole life, pass the value, not a closure. A
constant creates no binding at all. When it is exactly a signal's value, pass the signal
itself: `w::text(ui, status)` follows `status`.

## Batching

Writes inside [`batch`](crate::reactive::batch) notify once, when the batch ends. Each event
handler, timer and posted closure already runs in a batch, so most code never calls it.
Call it yourself when you change several signals from somewhere else, such as a test or a
setup function.

```
use remedy_ui::reactive::{Effect, Signal, batch};
use std::cell::RefCell;
use std::rc::Rc;

let first = Signal::new("Ada".to_string());
let last = Signal::new("Lovelace".to_string());
let seen = Rc::new(RefCell::new(Vec::new()));
let s = seen.clone();
Effect::new(move || s.borrow_mut().push(format!("{} {}", first.get(), last.get())));

batch(|| {
    first.set("Grace".into());
    last.set("Hopper".into());
});
// One run for the batch: no effect ever saw "Grace Lovelace".
assert_eq!(*seen.borrow(), ["Ada Lovelace", "Grace Hopper"]);
```

## Reading without subscribing

Sometimes a binding needs a value without following it: the current theme for a one-off
calculation, or a signal it writes to. Wrap the read in
[`untrack`](crate::reactive::untrack), or use
[`get_untracked`](crate::reactive::Signal::get_untracked).

```
use remedy_ui::reactive::{Effect, Signal, untrack};
use std::cell::Cell;
use std::rc::Rc;

let query = Signal::new(String::from("rust"));
let page_size = Signal::new(20usize);
let runs = Rc::new(Cell::new(0));
let r = runs.clone();
Effect::new(move || {
    let q = query.get();
    let size = untrack(|| page_size.get());
    let _ = (q, size);
    r.set(r.get() + 1);
});

page_size.set(50); // read untracked: the search does not run again
assert_eq!(runs.get(), 1);
query.set("signals".into());
assert_eq!(runs.get(), 2);
```

`get_untracked` returns a `Result`, because outside a binding there is no nearby owner to
report a disposed signal to.

## Lifetimes

Every signal, memo and effect has an owner: the [`Scope`](crate::reactive::Scope), memo or
effect that was running when it was made. Disposing an owner disposes everything it owns and
runs its clean-ups ([`on_cleanup`](crate::reactive::on_cleanup)).

- An element's bindings are owned by the element. Removing the element
  ([`El::remove`]crate::El::remove) disposes them, and runs its
  [`El::on_removed`]crate::El::on_removed callbacks.
- A list row built by [`widgets::for_each`]crate::widgets::for_each lives as long as its
  key stays in the list.
- Signals made at the top of a component, outside any scope, live until you dispose them.
  Give long-lived state one home (the app's state struct) instead of making new signals in
  code that runs often.

```
use remedy_ui::reactive::{Effect, Scope, Signal, on_cleanup};
use std::cell::Cell;
use std::rc::Rc;

let online = Signal::new(true);
let cleaned = Rc::new(Cell::new(false));
let c = cleaned.clone();
let (status, scope) = Scope::new(move || {
    let status = Signal::new("Online");
    Effect::new(move || status.set(if online.get() { "Online" } else { "Offline" }));
    on_cleanup(move || c.set(true));
    status
});
online.set(false);
assert_eq!(status.get(), "Offline");

scope.dispose();
assert!(cleaned.get(), "clean-ups run on dispose");
assert!(!status.is_alive(), "what the scope owned is gone");
assert!(status.try_get().is_err(), "reading it says so instead of inventing a value");
```

A clean-up registered inside an effect runs before the effect's next run as well, so an
effect that starts something (a timer, a subscription) can stop it each time.

## Context

Some values belong to a whole subtree rather than to one component: the document a screen
edits, the account that is signed in, a service. Instead of passing them through every
function, provide them on an element with [`El::provide`](crate::El::provide), and read the
nearest one below it with [`El::use_context`](crate::El::use_context), or with
[`reactive::use_context`](crate::reactive::use_context) in code built inside it
([`El::child_with`](crate::El::child_with), its bindings). A value that changes is provided
as a signal.

```
use remedy_ui::reactive::Signal;
use remedy_ui::testing::TestApp;
use remedy_ui::widgets as w;
use remedy_ui::{El, Ui};

/// Who is signed in, for everything under the account screen.
#[derive(Clone, Copy)]
struct Account {
    name: Signal<String>,
}

/// A greeting that finds the account itself, wherever it is placed below.
fn greeting(ui: &Ui) -> El {
    let account = remedy_ui::reactive::use_context::<Account>();
    w::text(ui, move || match account {
        Some(a) => format!("Signed in as {}", a.name.get()),
        None => "Not signed in".into(),
    })
}

let name = Signal::new("Ada".to_string());
let mut app = TestApp::window(move |ui, _| {
    let u = ui.clone();
    let screen = w::column(ui).provide(Account { name }).child_with(move || greeting(&u));
    ui.root().child(screen);
});
let Some(ui) = app.ui() else { unreachable!("open") };
let shows = |text: &str| ui.reader_view().iter().any(|n| n.name.as_deref() == Some(text));
assert!(shows("Signed in as Ada"));
name.set("Grace".into());
app.frames(1);
assert!(shows("Signed in as Grace"));
```

Context is for what many parts of a subtree need. A value one child needs is an argument.

## State that outlives the app

[`Signal::persist`](crate::reactive::Signal::persist) makes a signal remember its value
between runs: window splits, the last tab, a draft, the choices people made. The saved value
replaces the signal's value when it is made, and each change is saved: debounced, off the UI
thread, and atomically, so a crash leaves the old value or the new one, never half of each.
Values are saved as JSON (the type implements `serde`'s `Serialize` and `Deserialize`).

```no_run
use remedy_ui::reactive::Signal;
use remedy_ui::widgets as w;
use remedy_ui::{App, AppConfig, WindowSpec};

remedy_ui::run(AppConfig::new("Notes"), |app: &App| {
    app.open(WindowSpec::new("Notes"), |ui, _| {
        // Restored at start; saved after every change.
        let wrap = Signal::new(true).persist("editor.wrap");
        ui.root().child(w::switch(ui, "Wrap long lines", wrap));
    });
})
.ok();
```

The app's windows are built with its [`PersistStore`](crate::reactive::PersistStore)
provided as context ([`App::persist_store`]crate::App::persist_store), which is where
`persist` saves. It is flushed when the app quits, is suspended, or goes out of sight (every
window hidden or covered, a page's tab hidden), since a phone or a browser may end an app
from there without another word. Where it keeps things, by platform:

| Platform | Where |
|---|---|
| Windows | `%APPDATA%\<app name>\state\<key>.json` |
| macOS | `~/Library/Application Support/<app name>/state/<key>.json` |
| Linux | `$XDG_CONFIG_HOME/<app name>/state/<key>.json` (or `~/.config/…`) |
| Android | the app's private internal storage: `/data/user/<user>/<package>/files/state/<key>.json` |
| Browser page | the origin's `localStorage`, key `remedy:<app name>:<key>` |

The folder is the app's data folder ([`App::data_dir`](crate::App::data_dir), or the one
[`AppConfig::data_dir`](crate::AppConfig::data_dir) names); keys with characters other than
letters, digits, `.`, `-` and `_` are escaped in file names. A page has no folder (`data_dir`
is `None` there), so its store keeps the same versioned JSON in `localStorage`, under a prefix
per app (`~` and `:` in the app's name are written `~7e` and `~3a`) so apps sharing an origin
keep apart. A browser keeps an origin's `localStorage` across reloads and restarts, and
installed web apps keep theirs until the person clears the site's data; it holds a few
megabytes per origin, and a write the browser refuses is reported by
[`PersistStore::take_errors`](crate::reactive::PersistStore::take_errors) and
[`flush`](crate::reactive::PersistStore::flush), with the value still seen by loads until a
later write lands it.

A value other code shares is kept plain instead: [`Persist::plain`](crate::reactive::Persist::plain)
keeps it alone, with no version around it, under exactly its key. In a page that is the
origin's own `localStorage` item of that name, outside the app's prefix, so an older web
version of the app on the same origin reads and writes the same item, and a choice made in
either survives a reload of both; on the desktop it is the key's file in the same folder,
holding just the value. [`Plain::Json`](crate::reactive::Plain::Json) writes the value as
`JSON.stringify` does, [`Plain::Text`](crate::reactive::Plain::Text) a string as the string
itself (`localStorage.setItem("theme", "dark")`). Plain values have no version or migration,
so read what another program writes leniently (serde defaults for fields it may leave out).
[`Persist::session`](crate::reactive::Persist::session) keeps a plain value for the session
only: in a page, the tab's own `sessionStorage` item (shared with the origin's other pages in
that tab, gone with the tab); elsewhere, memory for the app's run. It is written at once,
with no debounce. [`PersistStore::forget`](crate::reactive::PersistStore::forget) removes a
value of any kind.

```
use remedy_ui::reactive::{Persist, Plain, Signal};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
struct Fonts {
    #[serde(default)]
    text: String,
    #[serde(default)]
    headings: String,
}

# fn setup() {
// The items the old page keeps: `portal-theme` is "midnight", `portal-fonts` is
// {"text":"remedy-sans","headings":"ahmi-pixel"}.
let theme = Signal::new("portal".to_owned()).persist(Persist::new("portal-theme").plain(Plain::Text));
let fonts = Signal::new(Fonts { text: "remedy-sans".into(), headings: "ahmi-pixel".into() })
    .persist(Persist::new("portal-fonts").plain(Plain::Json));
// `portal-seasons` is in the tab's sessionStorage.
let seasons = Signal::new(serde_json::Value::Null).persist(Persist::new("portal-seasons").session());
# let _ = (theme, fonts, seasons);
# }
```

Window geometry ([`WindowSpec::persist_geometry`](crate::WindowSpec::persist_geometry)) is kept
beside it, in `windows.txt` in the data folder, and in a page in the same store
(`remedy:<app name>:remedy-ui.windows`), so floating windows come back where they were.

### The app's own documents

The store is also the one way to keep an app's own data that works on every platform,
browser pages included: [`save`](crate::reactive::PersistStore::save) and
[`load`](crate::reactive::PersistStore::load) take any serializable value under a key, with
the same versions and migrations as persisted signals, and
[`remove`](crate::reactive::PersistStore::remove) forgets one. A load sees a save at once,
before the debounced write lands. A recipe calculator keeping its library:

```no_run
use remedy_ui::reactive::Persist;
use remedy_ui::{App, AppConfig};

// A recipe: its name and its oils in grams (an app's own types derive `serde`'s traits).
type Recipe = (String, Vec<(String, f64)>);

remedy_ui::run(AppConfig::new("Craft Calc"), |app: &App| {
    let Some(store) = app.persist_store() else { return };
    let library = Persist::new("recipes");
    let mut recipes: Vec<Recipe> = store.load(&library).ok().flatten().unwrap_or_default();
    recipes.push(("Castile".into(), vec![("Olive".into(), 1000.0)]));
    // Written after the debounce, and before the app quits or goes to the background.
    if let Err(e) = store.save(&library, &recipes) {
        eprintln!("the library was not saved: {e}");
    }
})
.ok();
```

A value
whose shape changes over releases takes a [`Persist`](crate::reactive::Persist) with a
version and a migration from older versions; a file from a newer version of the app is left
alone. [`Signal::persist_in`](crate::reactive::Signal::persist_in) saves in a store the app
opens itself:

```
use remedy_ui::reactive::{Persist, PersistStore, Scope, Signal, batch};

let dir = std::env::temp_dir().join(format!("remedy-guide-persist-{}", std::process::id()));
let store = PersistStore::open(&dir)?;
let ((), first_run) = Scope::new(|| {
    let split = Signal::new(0.3f32).persist_in(&store, Persist::new("split")).unwrap_or_else(|(s, _)| s);
    split.set(0.6);
});
batch(|| {});
store.flush()?;
first_run.dispose();

// The next start: the value comes back.
let ((), _next_run) = Scope::new(|| {
    let split = Signal::new(0.3f32).persist_in(&store, Persist::new("split")).unwrap_or_else(|(s, _)| s);
    assert_eq!(split.get(), 0.6);
});
let _ = std::fs::remove_dir_all(&dir);
# Ok::<(), std::io::Error>(())
```

## State from other threads

Signals are reached only on their UI thread. Slow work goes elsewhere and comes back:

- [`App::background`](crate::App::background) runs a closure on a worker and hands its
  result to a closure on the UI thread, which can set signals. It returns a
  [`BackgroundJob`](crate::BackgroundJob): [`cancel`](crate::BackgroundJob::cancel) it when the
  result is no longer wanted (the person typed a new search), and its result is dropped.
- [`App::background_cancellable`](crate::App::background_cancellable) also hands the work a
  [`Cancelled`](crate::Cancelled) to check between steps, so long work stops early.
- [`App::completion`](crate::App::completion) gives a handle another thread (an async
  runtime's task, a library callback) completes later.
- [`reactive::waker`](crate::reactive::waker) gives a `Send` handle that posts closures to
  the UI thread, for code below the app layer.

```
use remedy_ui::reactive::Signal;
use remedy_ui::testing::TestApp;
use remedy_ui::widgets as w;
use remedy_ui::{App, AppConfig, WindowSpec};

let digest = Signal::new(String::from("Working…"));
let app = move |app: &App| {
    // A slow computation off the UI thread; the window stays responsive meanwhile.
    // Keep the job to cancel it; once cancelled, `done` never runs.
    let _job = app.background_cancellable(
        |cancelled| {
            let mut h = 0u64;
            for i in 0..5_000_000u64 {
                if i % 100_000 == 0 && cancelled.is_cancelled() {
                    break;
                }
                h = h.rotate_left(5) ^ i;
            }
            h.to_string()
        },
        move |result| digest.set(result),
    );
    app.open(WindowSpec::new("Hasher"), move |ui, _| {
        ui.root().child(w::text(ui, digest));
    });
};
let mut test = TestApp::new(AppConfig::new("Hasher"), app);
for _ in 0..10_000 {
    if digest.get() != "Working…" {
        break;
    }
    std::thread::yield_now();
    test.frames(1);
}
assert_ne!(digest.get(), "Working…", "the result came back to the UI thread");
```

## Collections and nested state

- [`SignalVec`]crate::reactive::SignalVec is a list that records what changed (push,
  insert, remove, move, set) instead of handing out new copies. Readers take the changes
  with a [`VecReader`]crate::reactive::VecReader.
- [`Store`]crate::reactive::Store tracks a nested structure field by field, so a write to
  one message's `edited` flag wakes readers of that field and not its siblings.

The list widgets take either a `Signal<Vec<T>>` or a `SignalVec`, whose operations they apply
row by row; see [`crate::guide::lists`].

## Finding out why something updated

Give important signals a name with
[`Signal::named`](crate::reactive::Signal::named). The inspector's Signals page (feature
`devtools`, F12 in a debug build) shows each element's bindings, what they read, and a log
such as "row “42” relaid out because its text binding re-ran: `message.text` changed".