Open History to see the last commit
1import { Atom } from "effect/reactivity";
2
3import { subscribeAppActive } from "./appState";
4
5/**
6 * A system permission as the app last saw it. Reads it when first mounted and
7 * again each time the app returns to the foreground, where the user may have
8 * changed it in system Settings. Writing stores the outcome of a request.
9 */
10export function makePermissionStatusAtom<S>(options: {
11 readonly label: string;
12 readonly initial: S;
13 readonly read: () => Promise<S>;
14}): Atom.Writable<S, S> {
15 return Atom.writable(
16 (get) => {
17 // A read that settles after unmount is dropped: setSelf on a disposed lifetime is a no-op.
18 const refresh = () => {
19 void options.read().then((status) => get.setSelf(status));
20 };
21 refresh();
22 get.addFinalizer(subscribeAppActive(refresh));
23 return options.initial;
24 },
25 (ctx, status: S) => ctx.setSelf(status),
26 ).pipe(Atom.withLabel(options.label));
27}