Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PermissionUpdateNotice.tsx

83 lines2.8 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { useAtomValue } from "@effect/atom-react";
3import { sessionHasLegacyPermissions } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5import * as SecureStore from "expo-secure-store";
6import { useEffect, useMemo, useRef, useState } from "react";
7​
8import { whenProtectedDataAvailable } from "../../lib/protectedData";
9import { useEnvironments } from "../../state/environments";
10import { environmentSession } from "../../state/session";
11​
12const storageKey = "t3code.permission-update.v1";
13const dismissedThisLaunch = new Set<string>();
14const shownThisLaunch = new Set<string>();
15​
16export function PermissionUpdateNotice() {
17 const { environments } = useEnvironments();
18 const [dismissed, setDismissed] = useState<ReadonlySet<string> | null>(null);
19 const showing = useRef(false);
20 const affected = useAtomValue(
21 useMemo(
22 () =>
23 Atom.make((get) =>
24 environments.filter(({ environmentId }) => {
25 const session = get(environmentSession.sessionStateAtom(environmentId));
26 return (
27 session._tag === "Success" &&
28 !session.waiting &&
29 sessionHasLegacyPermissions(session.value)
30 );
31 }),
32 ),
33 [environments],
34 ),
35 );
36​
37 useEffect(() => {
38 let active = true;
39 void whenProtectedDataAvailable()
40 .then(() => SecureStore.getItemAsync(storageKey))
41 .then((raw) => {
42 const value: unknown = raw === null ? [] : JSON.parse(raw);
43 if (active)
44 setDismissed(
45 new Set(
46 Array.isArray(value)
47 ? value.filter((id): id is string => typeof id === "string")
48 : [],
49 ),
50 );
51 })
52 .catch(() => {
53 if (active) setDismissed(new Set());
54 });
55 return () => {
56 active = false;
57 };
58 }, []);
59​
60 useEffect(() => {
61 if (dismissed === null || showing.current) return;
62 const environment = affected.find(
63 ({ environmentId }) => !dismissed.has(environmentId) && !shownThisLaunch.has(environmentId),
64 );
65 if (!environment) return;
66 showing.current = true;
67 shownThisLaunch.add(environment.environmentId);
68 const dismiss = () => {
69 dismissedThisLaunch.add(environment.environmentId);
70 const next = new Set([...dismissed, ...dismissedThisLaunch]);
71 showing.current = false;
72 setDismissed(next);
73 void SecureStore.setItemAsync(storageKey, JSON.stringify([...next])).catch(() => {});
74 };
75 Dialog.alert(
76 `Permissions have changed for ${environment.label}`,
77 "This connection still uses the old permissions, so some actions may no longer be available. Pair again using a new link with the permissions you need.",
78 [{ text: "Got it", onPress: dismiss }],
79 { cancelable: false },
80 );
81 }, [affected, dismissed]);
82 return null;