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

PullRequestReactions.tsx

219 lines8.5 KB

1import { useNavigation } from "@react-navigation/native";
2import {
3 applyPendingPullRequestReactions,
4 type PendingPullRequestReaction,
5 PULL_REQUEST_REACTION_ORDER,
6 pullRequestReactionEmoji,
7 pullRequestReactionName,
8 pullRequestReactionTooltip,
9 pullRequestReactionsSignature,
10 retainPendingPullRequestReactions,
11} from "@t3tools/client-runtime/pull-request-reactions";
12import type {
13 PullRequestComment,
14 PullRequestReaction,
15 PullRequestReactionContent,
16} from "@t3tools/contracts";
17import { AsyncResult } from "effect/reactivity";
18import { T, useGT, useLocale, useMessages } from "gt-react-native";
19import { useState } from "react";
20import { Pressable, View } from "react-native";
21import { SymbolView } from "../../components/ui/AppSymbol";
22import { AppText as Text } from "../../components/ui/AppText";
23import * as Dialog from "../../components/ui/Dialog";
24import { Menu } from "../../components/ui/Menu";
25import { cn } from "../../lib/cn";
26import { composerPullRequests } from "../../state/pull-requests";
27import { useEnvironmentQuery } from "../../state/query";
28import { useAtomCommand } from "../../state/use-atom-command";
29import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
30import { usePullRequestPermissions } from "./usePullRequestPermissions";
31​
32const EMPTY_PENDING: ReadonlyMap<PullRequestReactionContent, PendingPullRequestReaction> =
33 new Map();
34const PILL = "min-h-8 flex-row items-center gap-1 rounded-full border px-2.5 active:opacity-70";
35​
36/** Reaction pills for any subject; `onReact` resolves false when the host refused the change. */
37export function ReactionPills(props: {
38 readonly reactions: ReadonlyArray<PullRequestReaction>;
39 readonly canReact: boolean;
40 readonly onReact: (content: PullRequestReactionContent, reacted: boolean) => Promise<boolean>;
41 readonly onChanged?: () => void;
42}) {
43 // Keyed by what the host last reported, so a refresh that lands the change drops the overlay.
44 const gt = useGT();
45 const messages = useMessages();
46 const locale = useLocale();
47 const [pending, setPending] = useState({ signature: "", values: EMPTY_PENDING });
48 const signature = pullRequestReactionsSignature(props.reactions);
49 let values = pending.values;
50 if (pending.signature !== signature && values.size > 0) {
51 values = retainPendingPullRequestReactions(props.reactions, values);
52 setPending({ signature, values });
53 }
54 const shown = applyPendingPullRequestReactions(props.reactions, values);
55 const toggle = async (content: PullRequestReactionContent, reacted: boolean) => {
56 const entry: PendingPullRequestReaction = { reacted };
57 setPending({ signature, values: new Map([...values, [content, entry]]) });
58 const saved = await props.onReact(content, reacted);
59 setPending((current) => {
60 if (current.values.get(content) !== entry) return current;
61 const next = new Map(current.values);
62 if (saved) next.set(content, { ...entry, saved });
63 else next.delete(content);
64 return { signature: current.signature, values: next };
65 });
66 if (!saved) {
67 Dialog.alert(gt`Couldn't save the reaction`, gt`Try again in a moment.`);
68 return;
69 }
70 props.onChanged?.();
71 };
72 return (
73 <>
74 {shown.map((reaction) => (
75 <Pressable
76 key={reaction.content}
77 accessibilityRole="button"
78 accessibilityLabel={pullRequestReactionTooltip(reaction, messages, locale)}
79 accessibilityState={{ selected: reaction.viewerHasReacted, disabled: !props.canReact }}
80 disabled={!props.canReact}
81 onPress={() => void toggle(reaction.content, !reaction.viewerHasReacted)}
82 className={cn(
83 PILL,
84 reaction.viewerHasReacted
85 ? "border-primary bg-primary/10"
86 : "border-border-subtle bg-grouped-card",
87 )}
88 >
89 <Text className="text-sm">{pullRequestReactionEmoji(reaction.content)}</Text>
90 <Text className="text-xs font-t3-medium text-foreground-muted">{reaction.count}</Text>
91 </Pressable>
92 ))}
93 {props.canReact ? (
94 <Menu
95 accessibilityLabel={gt`Add a reaction`}
96 actions={PULL_REQUEST_REACTION_ORDER.map((content) => ({
97 id: content,
98 title: `${pullRequestReactionEmoji(content)} ${pullRequestReactionName(content, messages)}`,
99 state: shown.some(
100 (reaction) => reaction.content === content && reaction.viewerHasReacted,
101 )
102 ? ("on" as const)
103 : ("off" as const),
104 }))}
105 onPressAction={({ nativeEvent }) => {
106 const content = PULL_REQUEST_REACTION_ORDER.find((id) => id === nativeEvent.event);
107 if (!content) return;
108 const reacted = shown.some(
109 (reaction) => reaction.content === content && reaction.viewerHasReacted,
110 );
111 void toggle(content, !reacted);
112 }}
113 >
114 <View className={cn(PILL, "border-border-subtle")}>
115 <SymbolView name="face.smiling" size={15} tintColorClassName="accent-icon-muted" />
116 </View>
117 </Menu>
118 ) : null}
119 </>
120 );
122​
123function usePullRequestReact(params: PullRequestParams, subjectId?: string) {
124 const target = pullRequestTarget(params);
125 const setReaction = useAtomCommand(composerPullRequests.setReaction, { reportFailure: false });
126 return async (content: PullRequestReactionContent, reacted: boolean) =>
127 !AsyncResult.isFailure(
128 await setReaction({
129 ...target,
130 input: {
131 ...target.input,
132 ...(subjectId === undefined ? {} : { subjectId }),
133 content,
134 reacted,
135 },
136 }),
137 );
139​
140/** Reactions on the change request itself, which is where its description's reactions live. */
141export function PullRequestReactions(props: { readonly params: PullRequestParams }) {
142 const target = pullRequestTarget(props.params);
143 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
144 const activity = useEnvironmentQuery(composerPullRequests.activity(target));
145 const { canReact } = usePullRequestPermissions(props.params, detail.data);
146 const reactions = activity.data?.reactions ?? [];
147 const onReact = usePullRequestReact(props.params);
148 if (!activity.data || (reactions.length === 0 && !canReact)) return null;
149 return (
150 <View className="flex-row flex-wrap items-center gap-1.5">
151 <ReactionPills
152 reactions={reactions}
153 canReact={canReact}
154 onReact={onReact}
155 onChanged={activity.refresh}
156 />
157 </View>
158 );
160​
161export function PullRequestCommentFooter(props: {
162 readonly params: PullRequestParams;
163 readonly comment: Pick<
164 PullRequestComment,
165 "id" | "kind" | "body" | "author" | "canEdit" | "reactions"
166 >;
167 readonly permissions: Pick<
168 ReturnType<typeof usePullRequestPermissions>,
169 "canEditComment" | "canReactComment"
170 >;
171 readonly onChanged: () => void;
172 readonly onEdit?: () => void;
173}) {
174 const navigation = useNavigation();
175 const gt = useGT();
176 const { comment } = props;
177 const reactions = comment.reactions ?? [];
178 const editableKind = comment.kind === "review" ? null : comment.kind;
179 const canEdit = editableKind !== null && props.permissions.canEditComment(comment);
180 const canReact = props.permissions.canReactComment(comment);
181 const onReact = usePullRequestReact(props.params, comment.id);
182 if (reactions.length === 0 && !canReact && !canEdit) return null;
183 return (
184 <View className="flex-row flex-wrap items-center gap-1.5">
185 <ReactionPills
186 reactions={reactions}
187 canReact={canReact}
188 onReact={onReact}
189 onChanged={props.onChanged}
190 />
191 {canEdit && editableKind !== null ? (
192 <Pressable
193 accessibilityRole="button"
194 accessibilityLabel={gt`Edit comment`}
195 onPress={() => {
196 props.onEdit?.();
197 navigation.navigate("PullRequestEdit", {
198 ...props.params,
199 field: "comment",
200 comment: {
201 id: comment.id,
202 kind: editableKind,
203 body: comment.body,
204 author: comment.author,
205 ...(comment.canEdit === undefined ? {} : { canEdit: comment.canEdit }),
206 },
207 });
208 }}
209 className={cn(PILL, "ml-auto border-transparent")}
210 >
211 <SymbolView name="pencil" size={13} tintColorClassName="accent-icon-muted" />
212 <Text className="text-xs font-t3-medium text-foreground-muted">
213 <T context="verb, edit a comment">Edit</T>
214 </Text>
215 </Pressable>
216 ) : null}
217 </View>
218 );