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

SecretRequestCard.tsx

298 lines10.6 KB

1import {
2 secretRequestAnswerInput,
3 secretRequestDisplay,
4 secretRequestFailureMessage,
5 secretRequestInputs,
6 secretRequestLink,
7 secretRequestPrivacyNote,
8 secretRequestReference,
9 secretRequestSources,
10 secretRequestValue,
11 type SecretRequestItem,
12 type SecretRequestReply,
13 type SecretRequestSource,
14} from "@t3tools/client-runtime/secret-request";
15import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18} from "@t3tools/client-runtime/state/runtime";
19import {
20 AuthProvidersManageScope,
21 type EnvironmentId,
22 type OrchestrationV2ProjectedTurnItem,
23 type SecretProviderId,
24} from "@t3tools/contracts";
25import { useAtomValue } from "@effect/atom-react";
26import { useGT, useMessages } from "gt-react-native";
27import { useRef, useState } from "react";
28import { View, type ColorValue } from "react-native";
29​
30import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
31import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
32import { SecretTextInput } from "../../components/ui/SecretTextInput";
33import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types";
34import { serverEnvironment } from "../../state/server";
35import { useEnvironmentScope } from "../../state/session";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
38import { Button } from "../../components/ui/Button";
39import { Chip } from "../../components/ui/Chip";
40​
41const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
42const PRIVATE_SYMBOL: AppSymbolName = { ios: "checkmark.shield", android: "lock" };
43const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
44​
45export function SecretRequestCard(props: {
46 readonly environmentId: EnvironmentId;
47 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
48 readonly iconColor: ColorValue;
49}) {
50 const m = useMessages();
51 const { item, visibility } = props.projectedItem;
52 if (item.type !== "secret_request") return null;
53 const display = secretRequestDisplay(item, visibility, m);
54 if (display.kind === "pending") {
55 return (
56 <PendingSecretRequestForm
57 environmentId={props.environmentId}
58 item={item}
59 iconColor={props.iconColor}
60 />
61 );
62 }
63 const icon: AppSymbolName =
64 display.kind === "pending-elsewhere"
65 ? LOCK_SYMBOL
66 : display.outcome === "saved"
67 ? "checkmark"
68 : "minus";
69 return (
70 <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
71 <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
72 <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
73 {item.label} · {display.label}
74 </Text>
75 </View>
76 );
78​
79function PendingSecretRequestForm(props: {
80 readonly environmentId: EnvironmentId;
81 readonly item: SecretRequestItem;
82 readonly iconColor: ColorValue;
83}) {
84 const gt = useGT();
85 const m = useMessages();
86 const { item } = props;
87 const answer = useAtomCommand(serverEnvironment.answerSecretRequest, {
88 label: "answer secret request",
89 // The failure cause holds the request; keep it out of the console.
90 reportFailure: false,
91 reportDefect: false,
92 });
93 const inputs = secretRequestInputs(item, m);
94 const multiple = item.fields !== undefined;
95 const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
96 // The server accepts a reference answer only with this scope; without it the card is typed.
97 const canUseReferences = useEnvironmentScope(props.environmentId, AuthProvidersManageScope);
98 // A reference answers one value, so a card with fields is always typed.
99 const sources =
100 multiple || !canUseReferences
101 ? NO_SOURCES
102 : secretRequestSources(config, config?.settings.secretProviders ?? {}, m);
103 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
104 const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
105 const [values, setValues] = useState<Readonly<Record<string, string>>>({});
106 const [reference, setReference] = useState("");
107 const [submitting, setSubmitting] = useState(false);
108 const [error, setError] = useState<string | null>(null);
109 // Submit then a tap can both run before a re-render; this guard is synchronous.
110 const inFlight = useRef(false);
111 const inputRefs = useRef<Array<SecretTextInputHandle | null>>([]);
112​
113 const send = async (reply: SecretRequestReply) => {
114 const input = secretRequestAnswerInput(item, reply);
115 if (input === null || inFlight.current) return;
116 inFlight.current = true;
117 setSubmitting(true);
118 setError(null);
119 // iOS offers to save a masked field that leaves the screen with text in it as a login
120 // password, so the card is emptied before it closes; a failed answer puts the values back.
121 const typed = reply.type === "save" ? reply.values : values;
122 setValues({});
123 const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
124 inFlight.current = false;
125 setSubmitting(false);
126 });
127 if (result._tag === "Success") {
128 setReference("");
129 return;
130 }
131 setValues(typed);
132 if (!isAtomCommandInterrupted(result)) {
133 setError(secretRequestFailureMessage(squashAtomCommandFailure(result), m));
134 }
135 };
136 const save = (typed: Readonly<Record<string, string>>) => {
137 if (source === null) {
138 void send({ type: "save", values: typed });
139 } else if (secretRequestReference(source, reference) === undefined) {
140 setError(source.invalidReferenceMessage);
141 } else {
142 void send({ type: "reference", source, reference });
143 }
144 };
145 const canSave =
146 source === null
147 ? secretRequestAnswerInput(item, { type: "save", values }) !== null
148 : reference.trim().length > 0;
149 const link = secretRequestLink(item);
150​
151 return (
152 <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
153 <View className="gap-1">
154 <Text className="font-t3-bold text-base text-foreground">{item.label}</Text>
155 {item.reason.trim() ? (
156 <Text className="font-sans text-sm leading-5 text-foreground-muted" selectable>
157 {item.reason}
158 </Text>
159 ) : null}
160 </View>
161 {link !== null ? (
162 <View className="gap-1.5">
163 <Button
164 label={gt("Open {host}", { host: link.host })}
165 tone="secondary"
166 fullWidth
167 onPress={() => void tryOpenExternalUrl(link.href, "secret-request")}
168 />
169 {/* A link found in the reason is already shown there. */}
170 {item.url !== undefined ? (
171 <Text selectable className="font-mono text-xs text-foreground-muted">
172 {item.url}
173 </Text>
174 ) : null}
175 </View>
176 ) : null}
177 {sources.length > 0 ? (
178 <View className="flex-row flex-wrap gap-2">
179 <Chip
180 label={gt("Value", { $context: "noun, enter the secret value directly" })}
181 size="small"
182 selected={source === null}
183 disabled={submitting}
184 onPress={() => {
185 setSourceId(null);
186 setError(null);
187 }}
188 />
189 {sources.map((candidate) => (
190 <Chip
191 key={candidate.id}
192 label={candidate.label}
193 size="small"
194 selected={candidate.id === source?.id}
195 disabled={submitting}
196 onPress={() => {
197 setSourceId(candidate.id);
198 setError(null);
199 }}
200 />
201 ))}
202 </View>
203 ) : null}
204 {source === null ? (
205 inputs.map((input, index) => {
206 const last = index === inputs.length - 1;
207 const field = (
208 <SecretTextInput
209 key={input.key}
210 // A single input is labelled by the card title.
211 accessibilityLabel={multiple ? input.label : item.label}
212 secret={input.secret}
213 onMount={(handle) => {
214 inputRefs.current[index] = handle;
215 }}
216 placeholder={input.placeholder}
217 value={secretRequestValue(values, input.key)}
218 onChangeText={(value) => setValues((current) => ({ ...current, [input.key]: value }))}
219 editable={!submitting}
220 returnKeyType={last ? "done" : "next"}
221 onSubmitEditing={(value) =>
222 last
223 ? save({ ...values, [input.key]: value })
224 : inputRefs.current[index + 1]?.focus()
225 }
226 />
227 );
228 return multiple ? (
229 <View key={input.key} className="gap-1.5">
230 <Text className="font-t3-medium text-sm text-foreground-muted">{input.label}</Text>
231 {field}
232 </View>
233 ) : (
234 field
235 );
236 })
237 ) : (
238 <TextInput
239 key={source.id}
240 accessibilityLabel={gt("{label} reference in {source}", {
241 label: item.label,
242 source: source.label,
243 })}
244 placeholder={source.referencePlaceholder}
245 value={reference}
246 onChangeText={(next) => {
247 setReference(next);
248 setError(null);
249 }}
250 editable={!submitting}
251 autoCorrect={false}
252 autoCapitalize="none"
253 autoComplete="off"
254 textContentType="none"
255 importantForAutofill="no"
256 spellCheck={false}
257 returnKeyType="done"
258 onSubmitEditing={() => save(values)}
259 />
260 )}
261 {error !== null ? (
262 <Text
263 accessibilityRole="alert"
264 accessibilityLiveRegion="polite"
265 className="font-sans text-sm text-danger-foreground"
266 >
267 {error}
268 </Text>
269 ) : null}
270 <Button
271 label={gt("Save securely")}
272 tone="primary"
273 fullWidth
274 disabled={submitting || !canSave}
275 onPress={() => save(values)}
276 />
277 <View className="flex-row items-center justify-between gap-2">
278 <View className="flex-1 flex-row items-center gap-1.5">
279 <SymbolView
280 name={PRIVATE_SYMBOL}
281 size={13}
282 tintColor={props.iconColor}
283 type="monochrome"
284 />
285 <Text className="flex-1 font-sans text-xs text-foreground-muted">
286 {secretRequestPrivacyNote(item, m)}
287 </Text>
288 </View>
289 <Button
290 label={gt("Decline", { $context: "verb, refuses the secret request" })}
291 tone="text"
292 disabled={submitting}
293 onPress={() => void send({ type: "decline" })}
294 />
295 </View>
296 </View>
297 );