Open History to see the last commit
1import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device";
2import { resolveDeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { useAtomValue } from "@effect/atom-react";
8
9import { connectionAtomRuntime } from "../connection/runtime";
10import { useEnvironmentQuery } from "./query";
11import { environmentSession, usePreparedConnection } from "./session";
12
13export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
14
15// A number, so a device state read that leaves the thread's previews as they were re-renders nothing.
16const threadDevicePreviewCountAtom = Atom.family((key: string) => {
17 const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId];
18 return Atom.make((get) => {
19 const state = AsyncResult.getOrElse(
20 get(deviceEnvironment.state({ environmentId, input: {} })),
21 () => null,
22 );
23 return (state?.sessions ?? []).filter((session) => session.threadId === threadId).length;
24 });
25});
26
27/** How many device previews belong to the thread. */
28export function useThreadDevicePreviewCount(environmentId: EnvironmentId, threadId: ThreadId) {
29 return useAtomValue(threadDevicePreviewCountAtom(JSON.stringify([environmentId, threadId])));
30}
31
32// Hub tickets are single use, so each viewer resolves its own access: a new
33// viewer (a reload, a device switch, a return to the screen) never reuses a
34// ticket an earlier connection already spent.
35const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
36 Atom.family((_viewer: string) =>
37 connectionAtomRuntime
38 .atom((get) => {
39 const prepared = Option.getOrNull(
40 get(environmentSession.preparedConnectionValueAtom(environmentId)),
41 );
42 return prepared === null
43 ? Effect.never
44 : resolveDeviceHubAccess({ prepared, hubBasePath: "/api/device-hub" });
45 })
46 .pipe(Atom.withLabel(`mobile-device-hub-access:${environmentId}`)),
47 ),
48);
49
50export function useDeviceHubAccess(environmentId: EnvironmentId, hostId: string, viewer: string) {
51 const prepared = usePreparedConnection(environmentId);
52 const query = useEnvironmentQuery(deviceHubAccessAtom(environmentId)(viewer));
53 const access =
54 query.data && query.error === null && Option.isSome(prepared)
55 ? { ...query.data, query: { ...query.data.query, hostId } }
56 : null;
57 return { access, error: query.error, refresh: query.refresh };
58}