@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 875 lines 30 KB
Raw
1 import { msg, useMessages } from "gt-react-native";
2
3 import { SymbolView } from "../../components/ui/AppSymbol";
4 import { Menu } from "../../components/ui/Menu";
5 import type { MenuAction } from "@react-native-menu/menu";
6 import * as Haptics from "expo-haptics";
7 import {
8 createContext,
9 use,
10 useCallback,
11 useEffect,
12 useLayoutEffect,
13 useMemo,
14 useRef,
15 useState,
16 type ComponentProps,
17 type ReactNode,
18 } from "react";
19 import type {
20 ColorValue,
21 NativeScrollEvent,
22 NativeSyntheticEvent,
23 StyleProp,
24 ViewStyle,
25 } from "react-native";
26 import { Platform, Pressable, View, useWindowDimensions } from "react-native";
27 import ReanimatedSwipeable, {
28 type SwipeableMethods,
29 } from "react-native-gesture-handler/ReanimatedSwipeable";
30 import Animated, {
31 cancelAnimation,
32 Easing,
33 Extrapolation,
34 ReduceMotion,
35 interpolate,
36 runOnJS,
37 runOnUI,
38 type SharedValue,
39 useAnimatedReaction,
40 useAnimatedStyle,
41 useSharedValue,
42 withTiming,
43 } from "react-native-reanimated";
44
45 import { AppText as Text } from "../../components/ui/AppText";
46 import type { MessageResolver } from "../../i18n/messages";
47 import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
48 import { SwipeRowActivationContext, type SwipeRowActivation } from "./swipe-row-activation";
49 import { registerThreadDismissal } from "./thread-dismissal";
50
51 const ACTION_ITEM_WIDTH = 58;
52 const ACTION_CIRCLE_SIZE = 36;
53 const ACTION_ICON_SIZE = 15;
54 const COMPACT_ACTION_CIRCLE_SIZE = 28;
55 const COMPACT_ACTION_ICON_SIZE = 13;
56 // At the default app text size, "Unarchive", the longest label, fills its slot at about 1.12x.
57 const ACTION_LABEL_MAX_FONT_SCALE = 1.1;
58 const ACTION_LABEL_MIN_HEIGHT = 14;
59 const ACTION_LABEL_OFFSET = 2;
60
61 const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2;
62 const THREAD_SWIPE_SPRING = {
63 damping: 26,
64 mass: 0.7,
65 overshootClamping: true,
66 stiffness: 330,
67 };
68
69 interface ThreadSwipeAction {
70 readonly accessibilityLabel: string;
71 readonly icon: ComponentProps<typeof SymbolView>["name"];
72 readonly label: string;
73 readonly destructive?: boolean;
74 readonly menu?: {
75 readonly actions: MenuAction[];
76 readonly onPressAction: NonNullable<ComponentProps<typeof Menu>["onPressAction"]>;
77 readonly title?: string;
78 };
79 readonly onPress: () => void;
80 }
81
82 interface ThreadSwipeSecondaryAction extends ThreadSwipeAction {
83 readonly tone: "primary" | "secondary" | "danger";
84 }
85
86 function swipeActionsWidth(hasSecondaryAction: boolean) {
87 return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH;
88 }
89
90 function fullActionStackHeight(labelLineHeight: number, fontScale: number) {
91 const labelHeight = labelLineHeight * Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE);
92 // The offset shifts the label after centering, so it needs room on both sides.
93 return (
94 ACTION_CIRCLE_SIZE + ACTION_LABEL_OFFSET * 2 + Math.max(ACTION_LABEL_MIN_HEIGHT, labelHeight)
95 );
96 }
97
98 function resolveSecondaryAction(input: {
99 readonly close: () => void;
100 readonly onDelete: () => void;
101 readonly secondaryAction: ThreadSwipeAction | null | undefined;
102 readonly threadTitle: string;
103 readonly resolve: MessageResolver;
104 }): ThreadSwipeSecondaryAction | null {
105 if (input.secondaryAction === null) return null;
106 if (input.secondaryAction === undefined) {
107 return {
108 accessibilityLabel: input.resolve(msg("Delete {title}", { title: input.threadTitle })),
109 tone: "danger",
110 icon: "trash",
111 label: input.resolve(msg("Delete", { $context: "verb, swipe action that deletes a thread" })),
112 onPress: () => {
113 input.close();
114 input.onDelete();
115 },
116 };
117 }
118 const action = input.secondaryAction;
119 return {
120 ...action,
121 tone: "secondary",
122 menu:
123 action.menu === undefined
124 ? undefined
125 : {
126 ...action.menu,
127 onPressAction: (event) => {
128 input.close();
129 action.menu?.onPressAction(event);
130 },
131 },
132 onPress: () => {
133 input.close();
134 action.onPress();
135 },
136 };
137 }
138
139 /** Keep the scroll gate in context so scroll start cannot re-render every row and its subscriptions. */
140 const SwipeableScrollGateContext = createContext(true);
141 // Swipeable rebuilds its native pan gesture whenever its config changes identity, so the props
142 // that feed it stay stable across row re-renders such as selection.
143 const FAIL_OFFSET_Y: [number, number] = [-10, 10];
144
145 export function SwipeableScrollGateProvider(props: {
146 readonly enabled: boolean;
147 readonly activation?: SwipeRowActivation;
148 readonly children: ReactNode;
149 }) {
150 return (
151 <SwipeableScrollGateContext.Provider value={props.enabled}>
152 <SwipeRowActivationContext value={props.activation ?? null}>
153 {props.children}
154 </SwipeRowActivationContext>
155 </SwipeableScrollGateContext.Provider>
156 );
157 }
158
159 /** Trackpads can start pans mid-momentum, bypassing failOffsetY; disable swipes during vertical scrolls. */
160 export function useSwipeableScrollGate(options?: {
161 readonly onScroll?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
162 readonly onScrollBeginDrag?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void;
163 }) {
164 const [gateActive, setGateActive] = useState(false);
165 const gateActiveRef = useRef(false);
166 const draggingRef = useRef(false);
167 const dragStartYRef = useRef(0);
168 const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
169 const externalOnScroll = options?.onScroll;
170 const externalOnScrollBeginDrag = options?.onScrollBeginDrag;
171
172 const update = useCallback((next: boolean) => {
173 if (gateActiveRef.current !== next) {
174 gateActiveRef.current = next;
175 setGateActive(next);
176 }
177 }, []);
178 const clearSettle = useCallback(() => {
179 if (settleTimerRef.current !== null) {
180 clearTimeout(settleTimerRef.current);
181 settleTimerRef.current = null;
182 }
183 }, []);
184 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the scroll settle timer on unmount
185 useEffect(() => clearSettle, [clearSettle]);
186
187 const onScrollBeginDrag = useCallback(
188 (event: NativeSyntheticEvent<NativeScrollEvent>) => {
189 draggingRef.current = true;
190 dragStartYRef.current = event.nativeEvent.contentOffset.y;
191 clearSettle();
192 externalOnScrollBeginDrag?.(event);
193 },
194 [clearSettle, externalOnScrollBeginDrag],
195 );
196 const onScroll = useCallback(
197 (event: NativeSyntheticEvent<NativeScrollEvent>) => {
198 if (
199 draggingRef.current &&
200 !gateActiveRef.current &&
201 Math.abs(event.nativeEvent.contentOffset.y - dragStartYRef.current) > 4
202 ) {
203 update(true);
204 }
205 externalOnScroll?.(event);
206 },
207 [externalOnScroll, update],
208 );
209 const onScrollEndDrag = useCallback(() => {
210 draggingRef.current = false;
211 clearSettle();
212 settleTimerRef.current = setTimeout(() => update(false), 160);
213 }, [clearSettle, update]);
214 const onMomentumScrollBegin = useCallback(() => {
215 clearSettle();
216 }, [clearSettle]);
217 const onMomentumScrollEnd = useCallback(() => {
218 update(false);
219 }, [update]);
220
221 return {
222 swipeEnabled: !gateActive,
223 scrollGateHandlers: {
224 onScroll,
225 onScrollBeginDrag,
226 onScrollEndDrag,
227 onMomentumScrollBegin,
228 onMomentumScrollEnd,
229 },
230 };
231 }
232
233 interface ThreadSwipeableProps {
234 readonly backgroundColor: ColorValue;
235 readonly children: (close: () => void) => ReactNode;
236 readonly compactActions?: boolean;
237 readonly containerStyle?: StyleProp<ViewStyle>;
238 readonly enabled?: boolean;
239 readonly enableTrackpadSwipe?: boolean;
240 /** Omitted uses Delete only with the built-in Delete secondary action; otherwise it uses primary. */
241 readonly fullSwipeAction?: "delete" | "primary";
242 readonly fullSwipeWidth: number;
243 /** The list animates item layout; collapse in one step so its transition moves siblings once. */
244 readonly listAnimatesLayout?: boolean;
245 readonly onDelete: () => void;
246 readonly onSwipeableClose?: (methods: SwipeableMethods) => void;
247 readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void;
248 readonly primaryAction: ThreadSwipeAction;
249 readonly threadKey: string;
250 /** Omitted defaults to Delete; null removes it so gated Snooze cannot fall back to Delete. */
251 readonly secondaryAction?: ThreadSwipeAction | null;
252 readonly resetKey?: string;
253 readonly dormant?: boolean;
254 readonly simultaneousWith?: ComponentProps<typeof ReanimatedSwipeable>["simultaneousWith"];
255 readonly threadTitle: string;
256 }
257
258 const COLLAPSED_ROW_STYLE = { height: 0, overflow: "hidden" } as const;
259
260 export function ThreadSwipeable(props: ThreadSwipeableProps) {
261 const m = useMessages();
262 const swipeableRef = useRef<SwipeableMethods | null>(null);
263 const hasSecondaryAction = props.secondaryAction !== null;
264 const actionsWidth = swipeActionsWidth(hasSecondaryAction);
265 const fullSwipeThreshold = Math.max(actionsWidth + 44, props.fullSwipeWidth * 0.58);
266 const fullSwipeAction =
267 props.fullSwipeAction ?? (props.secondaryAction === undefined ? "delete" : "primary");
268 const close = useCallback(() => swipeableRef.current?.close(), []);
269 const gateEnabled = use(SwipeableScrollGateContext);
270 const mountedRef = useRef(true);
271 const dismissalRef = useRef<{ finished: Promise<void>; restore: () => void } | null>(null);
272 const pendingDismissRef = useRef<{ id: number; resolve: () => void } | null>(null);
273 const dismissalIdRef = useRef(0);
274 const activeTranslationRef = useRef<SharedValue<number> | null>(null);
275 const content = useMemo(
276 () => ({ resetKey: props.resetKey, threadKey: props.threadKey }),
277 [props.resetKey, props.threadKey],
278 );
279 const contentRef = useRef(content);
280 const [isDismissing, setIsDismissing] = useState(false);
281 const [collapsedInList, setCollapsedInList] = useState(false);
282 const dismissing = useSharedValue(false);
283 const rowHeight = useSharedValue(0);
284 const rowWidth = useSharedValue(props.fullSwipeWidth);
285 const collapse = useSharedValue(0);
286 const fallbackTranslation = useSharedValue(0);
287 const actionOpacity = useSharedValue(1);
288 const primaryAction = props.primaryAction;
289 const onDelete = props.onDelete;
290 const onSwipeableClose = props.onSwipeableClose;
291 const listAnimatesLayout = props.listAnimatesLayout === true;
292
293 const restoreRow = useCallback(() => {
294 if (!mountedRef.current) return;
295 dismissalRef.current = null;
296 // RN-to-UI jobs run in order, so this also resets a queued dismissal.
297 runOnUI((methods: SwipeableMethods | null) => {
298 "worklet";
299 methods?.reset();
300 // RNGH reset() leaves tap-to-close enabled; close() clears it.
301 methods?.close();
302 fallbackTranslation.set(0);
303 collapse.set(0);
304 actionOpacity.set(1);
305 dismissing.set(false);
306 })(swipeableRef.current);
307 setIsDismissing(false);
308 setCollapsedInList(false);
309 }, [actionOpacity, collapse, dismissing, fallbackTranslation]);
310
311 const finishDismiss = useCallback((id?: number) => {
312 const pending = pendingDismissRef.current;
313 if (!pending || (id !== undefined && pending.id !== id)) return;
314 pendingDismissRef.current = null;
315 pending.resolve();
316 }, []);
317 const collapseInList = useCallback(
318 (id: number) => {
319 if (!mountedRef.current || pendingDismissRef.current?.id !== id) return;
320 setCollapsedInList(true);
321 finishDismiss(id);
322 },
323 [finishDismiss],
324 );
325
326 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the row's Reanimated animations and settles a pending dismissal on unmount
327 useLayoutEffect(() => {
328 mountedRef.current = true;
329 return () => {
330 mountedRef.current = false;
331 cancelAnimation(collapse);
332 cancelAnimation(actionOpacity);
333 cancelAnimation(fallbackTranslation);
334 if (activeTranslationRef.current) cancelAnimation(activeTranslationRef.current);
335 finishDismiss();
336 };
337 }, [actionOpacity, collapse, fallbackTranslation, finishDismiss]);
338
339 // Reset recycled rows in place so their child views stay mounted.
340 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resets the swipeable and its shared values when the list recycles this row for new content
341 useLayoutEffect(() => {
342 if (contentRef.current === content) return;
343 contentRef.current = content;
344 finishDismiss();
345 restoreRow();
346 }, [content, finishDismiss, restoreRow]);
347
348 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the open swipeable and resets its shared values when the row goes dormant
349 useLayoutEffect(() => {
350 if (props.dormant && activeTranslationRef.current && dismissalRef.current === null) {
351 restoreRow();
352 }
353 }, [props.dormant, restoreRow]);
354
355 const dismiss = useCallback(
356 (translation: SharedValue<number>, id: number) => {
357 "worklet";
358 if (dismissing.value) return;
359 dismissing.set(true);
360 const timing = {
361 duration: 220,
362 easing: Easing.out(Easing.cubic),
363 reduceMotion: ReduceMotion.System,
364 };
365 actionOpacity.set(withTiming(0, timing));
366 translation.set(
367 withTiming(Math.min(translation.value, -rowWidth.value), timing, (finished) => {
368 if (!finished) return;
369 // LegendList re-measures rows only on React commits, so a UI-thread height animation
370 // reaches it in late jumps. Collapse through React and let its transition move rows.
371 if (listAnimatesLayout) {
372 runOnJS(collapseInList)(id);
373 return;
374 }
375 collapse.set(
376 withTiming(1, { ...timing, duration: 180 }, (collapsed) => {
377 if (collapsed) runOnJS(finishDismiss)(id);
378 }),
379 );
380 }),
381 );
382 },
383 [
384 actionOpacity,
385 collapse,
386 collapseInList,
387 dismissing,
388 finishDismiss,
389 listAnimatesLayout,
390 rowWidth,
391 ],
392 );
393 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this row's animated dismissal in the module-level thread dismissal registry
394 useLayoutEffect(
395 () =>
396 props.dormant
397 ? undefined
398 : registerThreadDismissal(props.threadKey, () => {
399 if (dismissalRef.current) return dismissalRef.current;
400 const id = ++dismissalIdRef.current;
401 const finished = new Promise<void>((resolve) => {
402 pendingDismissRef.current = { id, resolve };
403 });
404 setIsDismissing(true);
405 if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current);
406 runOnUI(dismiss)(activeTranslationRef.current ?? fallbackTranslation, id);
407 const dismissal = {
408 finished,
409 restore: () => {
410 if (dismissalRef.current === dismissal) restoreRow();
411 },
412 };
413 dismissalRef.current = dismissal;
414 return dismissal;
415 }),
416 [dismiss, fallbackTranslation, onSwipeableClose, props.dormant, props.threadKey, restoreRow],
417 );
418 const dismissStyle = useAnimatedStyle(() => ({
419 // Native prop updates omit undefined, leaving a collapsed height in place.
420 height: dismissing.value ? rowHeight.value * (1 - collapse.value) : "auto",
421 pointerEvents: dismissing.value ? "none" : "auto",
422 overflow: "hidden",
423 transform: [{ translateX: fallbackTranslation.value }],
424 }));
425 const actionStyle = useAnimatedStyle(() => ({ opacity: actionOpacity.value, height: "100%" }));
426 const commitPrimaryAction = useCallback(() => {
427 if (!mountedRef.current || contentRef.current !== content) return;
428 primaryAction.onPress();
429 if (!pendingDismissRef.current) swipeableRef.current?.close();
430 }, [content, primaryAction]);
431 // RNGH lifecycle events call the latest handler, so commit from this release.
432 const commitFullSwipe = useCallback(() => {
433 if (!mountedRef.current || contentRef.current !== content) return;
434 if (fullSwipeAction === "primary") commitPrimaryAction();
435 else {
436 swipeableRef.current?.close();
437 onDelete();
438 }
439 }, [commitPrimaryAction, content, fullSwipeAction, onDelete]);
440 const handleRelease = useCallback(
441 (translation: SharedValue<number>, canceled: boolean) => {
442 "worklet";
443 if (dismissing.value) return true;
444 if (!canceled && -translation.value >= fullSwipeThreshold) {
445 runOnJS(commitFullSwipe)();
446 return true;
447 }
448 return false;
449 },
450 [commitFullSwipe, dismissing, fullSwipeThreshold],
451 );
452 const handleFullSwipeArmedChange = useCallback(
453 (armed: boolean) => {
454 if (mountedRef.current && contentRef.current === content && armed) {
455 void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
456 }
457 },
458 [content],
459 );
460 const { dormant, onSwipeableWillOpen, backgroundColor, containerStyle } = props;
461 const handleWillOpen = useCallback(() => {
462 if (!dormant && !dismissalRef.current && swipeableRef.current) {
463 onSwipeableWillOpen?.(swipeableRef.current);
464 }
465 }, [dormant, onSwipeableWillOpen]);
466 const handleSwipeableClose = useCallback(() => {
467 if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current);
468 }, [onSwipeableClose]);
469 const { fontScale } = useWindowDimensions();
470 const fullActionsHeight = fullActionStackHeight(useScaledTextRole("micro").lineHeight, fontScale);
471 const [measuredRowHeight, setMeasuredRowHeight] = useState(0);
472 const compactActions =
473 props.compactActions === true ||
474 (measuredRowHeight > 0 && measuredRowHeight < fullActionsHeight);
475 const { secondaryAction, threadTitle } = props;
476 // Swipeable calls this on every render; returning the previous element while nothing it shows
477 // changed keeps a selection change from re-rendering the hidden actions.
478 const rightActions = useRef<{ deps: readonly unknown[]; element: ReactNode } | null>(null);
479 const renderRightActions = (
480 _progress: SharedValue<number>,
481 translation: SharedValue<number>,
482 methods: SwipeableMethods,
483 ) => {
484 const deps = [
485 dormant,
486 translation,
487 methods,
488 actionStyle,
489 backgroundColor,
490 compactActions,
491 measuredRowHeight,
492 fullSwipeAction,
493 fullSwipeThreshold,
494 handleFullSwipeArmedChange,
495 primaryAction,
496 commitPrimaryAction,
497 onDelete,
498 secondaryAction,
499 threadTitle,
500 ];
501 const cached = rightActions.current;
502 if (cached && deps.every((dep, index) => Object.is(dep, cached.deps[index]))) {
503 return cached.element;
504 }
505 const element = dormant ? null : (
506 <Animated.View
507 ref={() => {
508 activeTranslationRef.current = translation;
509 }}
510 style={actionStyle}
511 >
512 <ThreadSwipeActions
513 backgroundColor={backgroundColor}
514 compact={compactActions}
515 rowHeight={measuredRowHeight}
516 fullSwipeAction={fullSwipeAction}
517 fullSwipeThreshold={fullSwipeThreshold}
518 onFullSwipeArmedChange={handleFullSwipeArmedChange}
519 primaryAction={{ ...primaryAction, onPress: commitPrimaryAction }}
520 secondaryAction={resolveSecondaryAction({
521 close: () => methods.close(),
522 onDelete,
523 secondaryAction,
524 threadTitle,
525 resolve: m,
526 })}
527 translation={translation}
528 />
529 </Animated.View>
530 );
531 rightActions.current = { deps, element };
532 return element;
533 };
534 const childrenContainerStyle = useMemo(() => ({ backgroundColor }), [backgroundColor]);
535 const swipeableContainerStyle = useMemo(
536 () => [{ backgroundColor }, containerStyle],
537 [backgroundColor, containerStyle],
538 );
539
540 return (
541 <View style={collapsedInList ? COLLAPSED_ROW_STYLE : undefined}>
542 <Animated.View style={dismissStyle}>
543 <View
544 onLayout={({ nativeEvent: { layout } }) => {
545 rowHeight.set(layout.height);
546 setMeasuredRowHeight(layout.height);
547 rowWidth.set(layout.width);
548 }}
549 >
550 <ReanimatedSwipeable
551 ref={swipeableRef}
552 animationOptions={THREAD_SWIPE_SPRING}
553 childrenContainerStyle={childrenContainerStyle}
554 containerStyle={swipeableContainerStyle}
555 dragOffsetFromRight={-8}
556 enabled={!props.dormant && !isDismissing && props.enabled !== false && gateEnabled}
557 enableTrackpadTwoFingerGesture={props.enableTrackpadSwipe ?? true}
558 // Reject vertical pans via patched RNGH failOffsetY; simultaneous trackpad scrolls otherwise open rows on horizontal drift.
559 failOffsetY={FAIL_OFFSET_Y}
560 friction={1}
561 onSwipeableClose={handleSwipeableClose}
562 onSwipeableRelease={handleRelease}
563 onSwipeableOpenStartDrag={handleWillOpen}
564 onSwipeableWillOpen={handleWillOpen}
565 overshootFriction={1}
566 overshootRight
567 renderRightActions={renderRightActions}
568 rightThreshold={actionsWidth * 0.42}
569 // Only iPad trackpad pans need rows to swipe while the list scrolls; on Android touch it
570 // lets a diagonal swipe scroll the list, which the scroll gate turns into a closed row.
571 simultaneousWith={Platform.OS === "ios" ? props.simultaneousWith : undefined}
572 >
573 {
574 /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */
575 props.children(close)
576 /* oxlint-enable react/refs */
577 }
578 </ReanimatedSwipeable>
579 </View>
580 </Animated.View>
581 </View>
582 );
583 }
584
585 function SwipeActionButton(props: {
586 readonly accessibilityLabel: string;
587 readonly actionsWidth: number;
588 readonly tone: "primary" | "secondary" | "danger";
589 readonly compact: boolean;
590 readonly entryRange: readonly [number, number];
591 readonly fullSwipeThreshold: number;
592 readonly icon: ComponentProps<typeof SymbolView>["name"];
593 readonly label: string;
594 readonly menu?: ThreadSwipeAction["menu"];
595 readonly onPress: () => void;
596 readonly rowHeight: number;
597 readonly stretchesOnFullSwipe: boolean;
598 readonly translation: SharedValue<number>;
599 }) {
600 const {
601 actionsWidth,
602 entryRange: [entryRangeStart, entryRangeEnd],
603 fullSwipeThreshold,
604 stretchesOnFullSwipe,
605 translation,
606 } = props;
607 const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE;
608 const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE;
609 const { fontScale } = useWindowDimensions();
610 // Even compact actions can outgrow a short row at large app text sizes; shrink the label's
611 // leading to the room left under the circle.
612 const labelRoom =
613 props.compact && props.rowHeight > 0
614 ? (props.rowHeight - circleSize) / Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE)
615 : Infinity;
616 const labelLineHeight = Math.min(useScaledTextRole("micro").lineHeight, labelRoom);
617 // Android scales lineHeight by the full font scale, past maxFontSizeMultiplier.
618 const labelTextStyle = {
619 lineHeight:
620 Platform.OS === "android" && fontScale > ACTION_LABEL_MAX_FONT_SCALE
621 ? (labelLineHeight * ACTION_LABEL_MAX_FONT_SCALE) / fontScale
622 : labelLineHeight,
623 };
624 const actionStyle = useAnimatedStyle(() => {
625 const reveal = Math.max(-translation.value, 0);
626 const entryProgress = interpolate(
627 reveal,
628 [entryRangeStart, entryRangeEnd],
629 [0, 1],
630 Extrapolation.CLAMP,
631 );
632 const stretch = Math.max(reveal - actionsWidth, 0);
633 const fullSwipeProgress = interpolate(
634 reveal,
635 [actionsWidth, fullSwipeThreshold + 20],
636 [0, 1],
637 Extrapolation.CLAMP,
638 );
639
640 return {
641 opacity: stretchesOnFullSwipe ? entryProgress : entryProgress * (1 - fullSwipeProgress),
642 transform: [
643 {
644 translateX:
645 interpolate(entryProgress, [0, 1], [22, 0]) - (stretchesOnFullSwipe ? 0 : stretch),
646 },
647 { scale: interpolate(entryProgress, [0, 1], [0.78, 1]) },
648 ],
649 };
650 });
651 const circleStyle = useAnimatedStyle(() => {
652 const reveal = Math.max(-translation.value, 0);
653 const stretch = stretchesOnFullSwipe ? Math.max(reveal - actionsWidth, 0) : 0;
654
655 return {
656 transform: [{ translateX: -stretch }],
657 width: circleSize + stretch,
658 };
659 });
660 const iconStyle = useAnimatedStyle(() => {
661 const reveal = Math.max(-translation.value, 0);
662 const stretch = stretchesOnFullSwipe ? Math.max(reveal - actionsWidth, 0) : 0;
663 const armedProgress = interpolate(
664 reveal,
665 [fullSwipeThreshold, fullSwipeThreshold + 20],
666 [0, 1],
667 Extrapolation.CLAMP,
668 );
669
670 return {
671 transform: [{ translateX: -stretch * (0.5 + armedProgress * 0.5) }],
672 };
673 });
674 const labelStyle = useAnimatedStyle(() => {
675 if (!stretchesOnFullSwipe) {
676 return { opacity: 1 };
677 }
678
679 const reveal = Math.max(-translation.value, 0);
680 const stretch = Math.max(reveal - actionsWidth, 0);
681 return {
682 opacity: interpolate(
683 reveal,
684 [fullSwipeThreshold - 24, fullSwipeThreshold],
685 [1, 0],
686 Extrapolation.CLAMP,
687 ),
688 transform: [{ translateX: -stretch * 0.5 }],
689 };
690 });
691
692 const button = (
693 <Pressable
694 accessibilityLabel={props.accessibilityLabel}
695 accessibilityRole="button"
696 onPress={props.menu === undefined ? props.onPress : undefined}
697 style={({ pressed }) => ({
698 alignItems: "center",
699 height: "100%",
700 justifyContent: "center",
701 opacity: pressed ? 0.72 : 1,
702 width: "100%",
703 })}
704 >
705 <View style={{ height: circleSize, width: circleSize }}>
706 <Animated.View
707 className={
708 props.tone === "danger"
709 ? "bg-danger"
710 : props.tone === "secondary"
711 ? "bg-secondary"
712 : "bg-primary"
713 }
714 style={[
715 {
716 borderRadius: 999,
717 height: circleSize,
718 left: 0,
719 position: "absolute",
720 top: 0,
721 },
722 circleStyle,
723 ]}
724 />
725 <Animated.View
726 style={[
727 {
728 alignItems: "center",
729 height: circleSize,
730 justifyContent: "center",
731 left: 0,
732 position: "absolute",
733 top: 0,
734 width: circleSize,
735 },
736 iconStyle,
737 ]}
738 >
739 <SymbolView
740 name={props.icon}
741 size={iconSize}
742 tintColorClassName={
743 props.tone === "danger"
744 ? "accent-danger-foreground"
745 : props.tone === "secondary"
746 ? "accent-secondary-foreground"
747 : "accent-primary-foreground"
748 }
749 type="monochrome"
750 />
751 </Animated.View>
752 </View>
753 {/* An offset, not padding: padding would grow the box and move the circle at 1x. */}
754 <Animated.View
755 style={[
756 {
757 justifyContent: "center",
758 minHeight: ACTION_LABEL_MIN_HEIGHT,
759 top: props.compact ? 0 : ACTION_LABEL_OFFSET,
760 },
761 labelStyle,
762 ]}
763 >
764 <Text
765 className="text-3xs font-t3-medium text-foreground-muted"
766 maxFontSizeMultiplier={ACTION_LABEL_MAX_FONT_SCALE}
767 numberOfLines={1}
768 style={labelTextStyle}
769 >
770 {props.label}
771 </Text>
772 </Animated.View>
773 </Pressable>
774 );
775
776 return (
777 <Animated.View
778 style={[
779 {
780 alignItems: "center",
781 height: "100%",
782 justifyContent: "center",
783 width: ACTION_ITEM_WIDTH,
784 zIndex: props.stretchesOnFullSwipe ? 2 : 1,
785 },
786 actionStyle,
787 ]}
788 >
789 {props.menu === undefined ? (
790 button
791 ) : (
792 <Menu
793 actions={props.menu.actions}
794 onPressAction={props.menu.onPressAction}
795 title={props.menu.title}
796 style={{ height: "100%", width: "100%" }}
797 >
798 {button}
799 </Menu>
800 )}
801 </Animated.View>
802 );
803 }
804
805 function ThreadSwipeActions(props: {
806 readonly backgroundColor: ColorValue;
807 readonly compact: boolean;
808 readonly fullSwipeAction?: "delete" | "primary";
809 readonly fullSwipeThreshold: number;
810 readonly onFullSwipeArmedChange: (armed: boolean) => void;
811 readonly primaryAction: ThreadSwipeAction;
812 readonly rowHeight: number;
813 readonly secondaryAction: ThreadSwipeSecondaryAction | null;
814 readonly translation: SharedValue<number>;
815 }) {
816 const { fullSwipeThreshold, onFullSwipeArmedChange, secondaryAction, translation } = props;
817 const fullSwipeIsPrimary = props.fullSwipeAction === "primary" || secondaryAction === null;
818 const actionsWidth = swipeActionsWidth(secondaryAction !== null);
819 useAnimatedReaction(
820 () => -translation.value >= fullSwipeThreshold,
821 (armed, previous) => {
822 if (armed !== previous) {
823 runOnJS(onFullSwipeArmedChange)(armed);
824 }
825 },
826 [fullSwipeThreshold, onFullSwipeArmedChange, translation],
827 );
828
829 return (
830 <View
831 style={{
832 backgroundColor: props.backgroundColor,
833 flexDirection: "row",
834 height: "100%",
835 width: actionsWidth,
836 }}
837 >
838 <SwipeActionButton
839 accessibilityLabel={props.primaryAction.accessibilityLabel}
840 actionsWidth={actionsWidth}
841 tone={props.primaryAction.destructive === true ? "danger" : "primary"}
842 compact={props.compact}
843 entryRange={
844 secondaryAction === null
845 ? [8, ACTION_ITEM_WIDTH * 0.72]
846 : [ACTION_ITEM_WIDTH * 0.55, THREAD_SWIPE_ACTIONS_WIDTH * 0.85]
847 }
848 fullSwipeThreshold={props.fullSwipeThreshold}
849 icon={props.primaryAction.icon}
850 label={props.primaryAction.label}
851 onPress={props.primaryAction.onPress}
852 rowHeight={props.rowHeight}
853 stretchesOnFullSwipe={fullSwipeIsPrimary}
854 translation={props.translation}
855 />
856 {secondaryAction === null ? null : (
857 <SwipeActionButton
858 accessibilityLabel={secondaryAction.accessibilityLabel}
859 actionsWidth={actionsWidth}
860 tone={secondaryAction.tone}
861 compact={props.compact}
862 entryRange={[8, ACTION_ITEM_WIDTH * 0.72]}
863 fullSwipeThreshold={props.fullSwipeThreshold}
864 icon={secondaryAction.icon}
865 label={secondaryAction.label}
866 menu={secondaryAction.menu}
867 onPress={secondaryAction.onPress}
868 rowHeight={props.rowHeight}
869 stretchesOnFullSwipe={!fullSwipeIsPrimary}
870 translation={props.translation}
871 />
872 )}
873 </View>
874 );
875 }