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

IssueCommentComposer.tsx

368 lines14.1 KB

1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import {
3 beginIssueCommentPost,
4 editIssueCommentDraft,
5 finishIssueCommentPost,
6 issueCommentDraftAtom,
7} from "@t3tools/client-runtime/state/issues";
8import type { EnvironmentId, IssueCommentAudience } from "@t3tools/contracts";
9import { useGT } from "gt-react-native";
10import { useContext, useRef, useState } from "react";
11import { Platform, View } from "react-native";
12import Animated from "react-native-reanimated";
13​
14import {
15 ComposerEditor,
16 type ComposerEditorHandle,
17 type ComposerEditorSelection,
18} from "../../components/ComposerEditor";
19import {
20 COMPOSER_BOTTOM_GUTTER,
21 ComposerSurface,
22 INLINE_EDITOR_MIN_WIDTH,
23 useCompactComposerEditor,
24 useComposerChrome,
25 useComposerTextStyle,
26} from "../../components/ComposerSurface";
27import {
28 ComposerActionButton,
29 ComposerInlineControl,
30 ComposerToolbarRow,
31} from "../../components/ComposerToolbar";
32import { AppText as Text } from "../../components/ui/AppText";
33import { Menu } from "../../components/ui/Menu";
34import { useComposerTextRole } from "../settings/appearance/useScaledTextRole";
35import {
36 ComposerDictationCancelAction,
37 ComposerDictationDraftContent,
38 ComposerDictationError,
39 ComposerDictationPrimaryAction,
40 ComposerDictationStartAction,
41 ComposerDictationStatus,
42 ComposerDictationToolbar,
43 useDictationAccessibilityFocus,
44} from "../voice-input/ComposerDictationControl";
45import { useVoiceInputController } from "../voice-input/useVoiceInputController";
46import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
47​
48// The thread composer's editor starts after its attachment button; this keeps the same text inset.
49const EDITOR_LEADING_INSET = 14;
50​
51/**
52 * The comment box at the foot of an issue, in the thread composer's chrome: one row that grows
53 * with the draft, dictation, and a round send button. With audiences, the editor gets its own two
54 * lines above the audience menu and send. `blocked` replaces the editor with the reason.
55 */
56export function IssueCommentComposer(props: {
57 /** Names this draft to dictation, so a recording started here lands here. */
58 readonly ownerKey: string;
59 readonly environmentId: EnvironmentId;
60 readonly issueUrl: string;
61 readonly label: string;
62 readonly blocked: string | null;
63 /** Each comment is an internal note unless the viewer picks a reply to the customer. */
64 readonly audiences: boolean;
65 readonly bottomInset: number;
66 readonly contentMaxWidth?: number;
67 /** Resolves true once the comment is posted, which clears the draft. */
68 readonly onSubmit: (body: string, audience?: IssueCommentAudience) => Promise<boolean>;
69 readonly onHeightChange: (height: number) => void;
70 readonly onFocusChange: (focused: boolean) => void;
71}) {
72 const gt = useGT();
73 const registry = useContext(RegistryContext);
74 const draftAtom = issueCommentDraftAtom(props.environmentId, props.issueUrl);
75 const { audience, body: draft, posting } = useAtomValue(draftAtom);
76 const editorRef = useRef<ComposerEditorHandle>(null);
77 const changeDraft = (body: string) => editIssueCommentDraft(registry, draftAtom, { body });
78 const [selection, setSelection] = useState<ComposerEditorSelection>({ start: 0, end: 0 });
79 const bodyText = useComposerTextRole();
80 const textStyle = useComposerTextStyle(bodyText);
81 const chrome = useComposerChrome();
82 const [focused, setFocused] = useState(false);
83 // Animate only while typing, as the thread composer does; a restored draft lands in place.
84 const compactEditor = useCompactComposerEditor(bodyText, draft, Platform.OS === "ios" && focused);
85 const [contentHeight, setContentHeight] = useState(0);
86 const twoLineEditorHeight = Math.max(
87 bodyText.lineHeight * 2,
88 Math.min(bodyText.lineHeight * 4, draft.length === 0 ? 0 : contentHeight),
89 );
90 const voiceInput = useVoiceInputController({
91 ownerKey: props.ownerKey,
92 label: props.label,
93 readDraftMessage: () => registry.get(draftAtom).body,
94 selection,
95 disabled: props.blocked !== null,
96 hidden: props.blocked !== null,
97 onChangeDraftMessage: changeDraft,
98 onChangeSelection: setSelection,
99 });
100 const voicePresentation = resolveVoiceComposerPresentation(
101 voiceInput.state,
102 voiceInput.elapsedSeconds,
103 );
104 const dictating = voicePresentation.statusKind === "active";
105 const {
106 startRef: dictationStartRef,
107 finishRef: dictationFinishRef,
108 focusStart,
109 focusFinish,
110 } = useDictationAccessibilityFocus();
111 const locked = posting || voiceInput.blocksSubmission;
112 const canSend = props.blocked === null && !locked && draft.trim().length > 0;
113​
114 const sending = useRef(false);
115 const flushAndSubmit = async () => {
116 await editorRef.current?.flushPendingInput();
117 const pending = beginIssueCommentPost(registry, draftAtom);
118 if (pending === null) return;
119 const sent = await props.onSubmit(pending.body, props.audiences ? pending.audience : undefined);
120 finishIssueCommentPost(registry, draftAtom, pending, sent);
121 };
122 const send = () => {
123 if (!canSend || sending.current) return Promise.resolve();
124 sending.current = true;
125 // `finally` on the promise: the React Compiler does not compile a `try` without a `catch`.
126 return flushAndSubmit().finally(() => {
127 sending.current = false;
128 });
129 };
130 const sendButton = (
131 <ComposerActionButton
132 size={chrome.controlSize}
133 accessibilityLabel={posting ? gt`Posting comment` : gt`Post comment`}
134 icon="arrow.up"
135 variant="primary"
136 disabled={!canSend}
137 onPress={() => void send()}
138 />
139 );
140 const editor = (
141 <ComposerEditor
142 ref={editorRef}
143 multiline
144 value={draft}
145 readOnly={locked}
146 selection={selection}
147 onChangeText={(text) => {
148 if (!locked) changeDraft(text);
149 }}
150 onSelectionChange={setSelection}
151 placeholder={gt`Leave a comment`}
152 onFocus={() => {
153 setFocused(true);
154 props.onFocusChange(true);
155 }}
156 onBlur={() => {
157 setFocused(false);
158 props.onFocusChange(false);
159 }}
160 onSubmit={() => void send()}
161 submitTitle={gt({ context: "verb, posts the comment" })`Comment`}
162 {...(props.audiences
163 ? {
164 singleLineCentered: false,
165 contentInsetVertical: 0,
166 scrollEnabled: Platform.OS === "android" || contentHeight >= bodyText.lineHeight * 4,
167 onContentSizeChange: ({ height }: { height: number }) => setContentHeight(height),
168 style: { height: twoLineEditorHeight },
169 }
170 : compactEditor.editorProps)}
171 textStyle={textStyle}
172 />
173 );
174 const audienceMenu = props.audiences ? (
175 <Menu
176 title={gt`Comment audience`}
177 style={{ flexShrink: 1, minWidth: 0 }}
178 actions={[
179 {
180 id: "internal",
181 title: gt`Internal note`,
182 state: audience === "internal" ? "on" : "off",
183 attributes: { disabled: locked },
184 },
185 {
186 id: "public",
187 title: gt`Reply to customer`,
188 state: audience === "public" ? "on" : "off",
189 attributes: { disabled: locked },
190 },
191 ]}
192 onPressAction={({ nativeEvent }) => {
193 if (nativeEvent.event === "internal" || nativeEvent.event === "public") {
194 editIssueCommentDraft(registry, draftAtom, { audience: nativeEvent.event });
195 }
196 }}
197 >
198 <View pointerEvents="none">
199 <ComposerInlineControl
200 size={chrome.controlSize}
201 label={audience === "internal" ? gt`Internal note` : gt`Reply to customer`}
202 />
203 </View>
204 </Menu>
205 ) : null;
206 const dictationStart = (
207 <ComposerDictationStartAction
208 ref={dictationStartRef}
209 size={chrome.controlSize}
210 state={voiceInput.state}
211 isAvailable={voiceInput.isAvailable}
212 disabled={locked}
213 onStart={voiceInput.start}
214 onCancel={voiceInput.cancel}
215 />
216 );
217​
218 return (
219 <Animated.View
220 onLayout={(event) => props.onHeightChange(event.nativeEvent.layout.height)}
221 className={Platform.OS === "android" ? "bg-screen px-[12px]" : "px-[12px]"}
222 style={{ paddingTop: 6, paddingBottom: props.bottomInset + COMPOSER_BOTTOM_GUTTER }}
223 >
224 <View
225 className={
226 Platform.OS === "android"
227 ? "hidden"
228 : "absolute inset-0 bg-linear-to-b from-screen/0 via-screen/60 to-screen/90"
229 }
230 pointerEvents="none"
231 />
232 <View className="w-full self-center" style={{ maxWidth: props.contentMaxWidth }}>
233 <ComposerSurface
234 animateLayout={false}
235 tone={props.audiences && audience === "internal" ? "warning" : undefined}
236 style={{
237 borderRadius: chrome.borderRadius,
238 borderCurve: "circular",
239 overflow: "hidden",
240 paddingVertical: chrome.paddingVertical,
241 }}
242 >
243 {props.blocked !== null ? (
244 <View className="h-[44px] flex-row items-center">
245 <Text
246 className="min-w-0 flex-1 text-base text-foreground-muted"
247 style={{ paddingLeft: EDITOR_LEADING_INSET }}
248 numberOfLines={1}
249 ellipsizeMode="tail"
250 >
251 {props.blocked}
252 </Text>
253 {sendButton}
254 </View>
255 ) : (
256 <>
257 <ComposerDictationError
258 error={voiceInput.state.phase === "error" ? voiceInput.state.error : null}
259 onDismiss={voiceInput.cancel}
260 />
261 {props.audiences ? (
262 <ComposerDictationDraftContent compact hidden={dictating}>
263 <View className="px-3.5 pt-3 pb-1">{editor}</View>
264 {/* Send stays where the one-row composer and the dictation toolbar put it. */}
265 <View
266 className="flex-row items-center"
267 style={{ paddingLeft: EDITOR_LEADING_INSET - 8 }}
268 >
269 <View className="min-w-0 flex-1 items-start">{audienceMenu}</View>
270 {dictationStart}
271 {sendButton}
272 </View>
273 </ComposerDictationDraftContent>
274 ) : (
275 <View onLayout={compactEditor.onRowLayout}>
276 <ComposerDictationDraftContent
277 className="flex-row items-end"
278 compact
279 hidden={dictating}
280 >
281 <View style={{ width: EDITOR_LEADING_INSET - 8 }} />
282 <Animated.View
283 className="min-w-0 flex-1"
284 onLayout={compactEditor.onEditorLayout}
285 style={[
286 { minWidth: compactEditor.isExpanded ? 0 : INLINE_EDITOR_MIN_WIDTH },
287 compactEditor.containerStyle,
288 compactEditor.isExpanded ? { flex: 0, width: 0 } : undefined,
289 ]}
290 />
291 {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */}
292 <Animated.View
293 style={[
294 compactEditor.editorStyle,
295 // iOS destroys a view under display: none; the editor would lose its focus and caret.
296 Platform.OS === "android" && dictating ? { display: "none" } : undefined,
297 ]}
298 >
299 {editor}
300 </Animated.View>
301 <View
302 className="min-w-0 shrink flex-row items-center"
303 style={
304 compactEditor.isExpanded
305 ? { flex: 1, justifyContent: "flex-end" }
306 : undefined
307 }
308 >
309 {dictationStart}
310 {sendButton}
311 </View>
312 </ComposerDictationDraftContent>
313 </View>
314 )}
315 <Animated.View
316 accessibilityElementsHidden={!dictating}
317 collapsable={false}
318 importantForAccessibility={dictating ? "auto" : "no-hide-descendants"}
319 pointerEvents={dictating ? "auto" : "none"}
320 style={{ position: "absolute", bottom: chrome.paddingVertical, left: 0, right: 0 }}
321 >
322 <ComposerDictationToolbar
323 showsDictation={dictating}
324 onShown={focusFinish}
325 onHidden={focusStart}
326 visible={dictating}
327 >
328 <ComposerToolbarRow
329 paddingBottom={0}
330 paddingHorizontal={0}
331 paddingTop={0}
332 style={{ gap: 0 }}
333 >
334 <ComposerDictationCancelAction
335 size={chrome.controlSize}
336 presentation={voicePresentation}
337 onCancel={voiceInput.cancel}
338 />
339 <ComposerDictationStatus
340 audioLevels={voiceInput.audioLevels}
341 elapsedSeconds={voiceInput.elapsedSeconds}
342 phase={voiceInput.state.phase}
343 presentation={voicePresentation}
344 />
345 <View className="shrink-0 flex-row items-center">
346 <ComposerDictationPrimaryAction
347 ref={dictationFinishRef}
348 size={chrome.controlSize}
349 state={voiceInput.state}
350 presentation={voicePresentation}
351 isAvailable={voiceInput.isAvailable}
352 disabled={locked}
353 onStart={voiceInput.start}
354 onConfirm={voiceInput.stop}
355 onCancel={voiceInput.cancel}
356 />
357 {voicePresentation.showsSend ? sendButton : null}
358 </View>
359 </ComposerToolbarRow>
360 </ComposerDictationToolbar>
361 </Animated.View>
362 </>
363 )}
364 </ComposerSurface>
365 </View>
366 </Animated.View>
367 );