Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as Queue from "effect/Queue";
5import * as Schema from "effect/Schema";
6import * as Stream from "effect/Stream";
7import * as AsyncResult from "effect/reactivity/AsyncResult";
8import { Atom } from "effect/reactivity";
9import { msg } from "gt-react";
10
11import { m } from "../i18n/messages";
12
13type DesktopUpdateBridge = Pick<DesktopBridge, "getUpdateState" | "onUpdateState">;
14
15const INITIAL_STATE_READ_ATTEMPT_COUNT = 3;
16
17export class DesktopUpdateStateReadError extends Schema.TaggedError<DesktopUpdateStateReadError>()(
18 "DesktopUpdateStateReadError",
19 {
20 attemptCount: Schema.Number,
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return m(
26 msg`Failed to read the initial desktop update state after ${{ count: this.attemptCount }} attempts.`,
27 );
28 }
29}
30
31function getDesktopUpdateBridge(): DesktopUpdateBridge | undefined {
32 return typeof window === "undefined" ? undefined : window.desktopBridge;
33}
34
35export function createDesktopUpdateStateAtom(getBridge: () => DesktopUpdateBridge | undefined) {
36 const updates = Stream.callback<DesktopUpdateState | null>((queue) =>
37 Effect.gen(function* () {
38 const bridge = getBridge();
39 if (!bridge) {
40 Queue.offerUnsafe(queue, null);
41 return yield* Effect.never;
42 }
43
44 let receivedUpdate = false;
45 yield* Effect.acquireRelease(
46 Effect.sync(() =>
47 bridge.onUpdateState((state) => {
48 receivedUpdate = true;
49 Queue.offerUnsafe(queue, state);
50 }),
51 ),
52 (unsubscribe) => Effect.sync(unsubscribe),
53 );
54
55 const initialState = yield* Effect.tryPromise({
56 try: () => bridge.getUpdateState(),
57 catch: (cause) =>
58 new DesktopUpdateStateReadError({
59 attemptCount: INITIAL_STATE_READ_ATTEMPT_COUNT,
60 cause,
61 }),
62 }).pipe(
63 Effect.retry({ times: INITIAL_STATE_READ_ATTEMPT_COUNT - 1 }),
64 Effect.catchTags({
65 DesktopUpdateStateReadError: (error) =>
66 Effect.logError(error.message, {
67 error,
68 errorTag: error._tag,
69 attemptCount: error.attemptCount,
70 }).pipe(Effect.as(null)),
71 }),
72 );
73 if (!receivedUpdate && initialState !== null) {
74 Queue.offerUnsafe(queue, initialState);
75 }
76
77 return yield* Effect.never;
78 }),
79 );
80
81 return Atom.make(updates, { initialValue: null }).pipe(
82 Atom.keepAlive,
83 Atom.withLabel("desktop:update-state"),
84 );
85}
86
87export const desktopUpdateStateAtom = createDesktopUpdateStateAtom(getDesktopUpdateBridge);
88
89export function useDesktopUpdateState(): DesktopUpdateState | null {
90 return AsyncResult.getOrElse(useAtomValue(desktopUpdateStateAtom), () => null);
91}