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

ThreadRowLayoutLanes.tsx

448 lines17.4 KB

1import {
2 SIDEBAR_ROW_ITEMS,
3 findSidebarRowToken,
4 moveSidebarRowToken,
5 type SidebarRowLayout,
6 type SidebarRowLine,
7 type SidebarRowToken,
8} from "@t3tools/client-runtime/thread-row-layout";
9import * as Haptics from "expo-haptics";
10import { useGT, useMessages } from "gt-react-native";
11import { useEffectEvent, useRef, useState, type ComponentRef, type ReactNode } from "react";
12import { View } from "react-native";
13import { Gesture, GestureDetector } from "react-native-gesture-handler";
14import Reanimated, { useAnimatedStyle, useSharedValue } from "react-native-reanimated";
15​
16import { SymbolView } from "../../components/ui/AppSymbol";
17import { AppText as Text } from "../../components/ui/AppText";
18import { cn } from "../../lib/cn";
19import { threadRowItemNode, type ThreadRowItemContent } from "../threads/thread-list-v2-items";
20​
21const LINES = ["top", "middle", "bottom", "hidden"] as const;
22// How far past the first or last line a drop still lands on it.
23const DROP_SLOP = 48;
24​
25type ViewRef = ComponentRef<typeof View>;
26​
27interface Rect {
28 readonly x: number;
29 readonly y: number;
30 readonly width: number;
31 readonly height: number;
33​
34interface DropTarget {
35 readonly line: SidebarRowLine;
36 /** The item the dragged one goes before, or null for the end of the line. */
37 readonly beforeKey: string | null;
38 readonly index: number;
40​
41function measure(view: ViewRef | undefined) {
42 return new Promise<Rect | null>((resolve) => {
43 if (!view) return resolve(null);
44 view.measureInWindow((x, y, width, height) => resolve({ x, y, width, height }));
45 });
47​
48/**
49 * The thread row lines as lanes of chips. Touch and hold a chip to drag it to another line or
50 * position; screen readers get the same moves as actions on each chip.
51 */
52export function ThreadRowLayoutLanes(props: {
53 readonly layout: SidebarRowLayout;
54 readonly disabled: boolean;
55 readonly edit: (change: (current: SidebarRowLayout) => SidebarRowLayout) => void;
56 /** The sample thread each chip shows its item from. */
57 readonly sample: ThreadRowItemContent;
58 readonly onDragActiveChange: (active: boolean) => void;
59 /** Opens the Icon only or Icon and name choice for an item that has one. */
60 readonly onChooseForm: (token: SidebarRowToken) => void;
61}) {
62 const gt = useGT();
63 const m = useMessages();
64 const { layout, edit } = props;
65 const lineLabels: Record<SidebarRowLine, string> = {
66 top: gt({ context: "thread row line" })`Top`,
67 middle: gt({ context: "thread row line" })`Middle`,
68 bottom: gt({ context: "thread row line" })`Bottom`,
69 hidden: gt({ context: "thread row item that is not shown" })`Hidden`,
70 };
71 const itemLabel = (token: SidebarRowToken) =>
72 m(SIDEBAR_ROW_ITEMS.find((item) => item.id === token.id)?.label ?? SIDEBAR_ROW_ITEMS[0].label);
73 // The thread list does not track terminals.
74 const shown = (line: SidebarRowLine) => layout[line].filter((token) => token.id !== "terminals");
75​
76 const container = useRef<ViewRef>(null);
77 const lanes = useRef(new Map<SidebarRowLine, ViewRef>());
78 const chips = useRef(new Map<string, ViewRef>());
79 // Measured once when a drag starts; the lanes keep their places until it ends.
80 const [rects, setRects] = useState<{
81 readonly container: Rect;
82 readonly lanes: ReadonlyArray<readonly [SidebarRowLine, Rect]>;
83 readonly chips: ReadonlyMap<string, Rect>;
84 } | null>(null);
85 const [drag, setDrag] = useState<{
86 readonly key: string;
87 readonly target: DropTarget | null;
88 } | null>(null);
89 const translateX = useSharedValue(0);
90 const translateY = useSharedValue(0);
91 const liftedStyle = useAnimatedStyle(() => ({
92 transform: [
93 { translateX: translateX.value },
94 { translateY: translateY.value },
95 { rotate: "-2deg" },
96 { scale: 1.05 },
97 ],
98 }));
99​
100 const dropTarget = (key: string, dx: number, dy: number): DropTarget | null => {
101 const measured = rects;
102 const start = measured?.chips.get(key);
103 const found = findSidebarRowToken(layout, key);
104 if (!measured || !start || !found) return null;
105 const point = { x: start.x + start.width / 2 + dx, y: start.y + start.height / 2 + dy };
106 let nearest: { line: SidebarRowLine; distance: number } | null = null;
107 for (const [line, rect] of measured.lanes) {
108 const distance = Math.max(0, rect.y - point.y, point.y - (rect.y + rect.height));
109 if (!nearest || distance < nearest.distance) nearest = { line, distance };
110 }
111 if (!nearest || nearest.distance > DROP_SLOP) return null;
112 const line = nearest.line;
113 if (line === "hidden" && found.token.id === "title") return null;
114 const others = shown(line).filter((token) => token.key !== key);
115 const index = others.filter((token) => {
116 const rect = measured.chips.get(token.key);
117 if (!rect) return false;
118 return (
119 rect.y + rect.height <= point.y || (point.y >= rect.y && rect.x + rect.width / 2 < point.x)
120 );
121 }).length;
122 return { line, index, beforeKey: others[index]?.key ?? null };
123 };
124​
125 const startDrag = (key: string) => {
126 if (props.disabled) return;
127 translateX.set(0);
128 translateY.set(0);
129 setRects(null);
130 setDrag({ key, target: null });
131 props.onDragActiveChange(true);
132 void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
133 void Promise.all([
134 measure(container.current ?? undefined),
135 Promise.all(
136 LINES.map(async (line) => [line, await measure(lanes.current.get(line))] as const),
137 ),
138 Promise.all(
139 [...chips.current].map(async ([chipKey, view]) => [chipKey, await measure(view)] as const),
140 ),
141 ]).then(([containerRect, laneRects, chipRects]) => {
142 if (!containerRect) return;
143 setRects({
144 container: containerRect,
145 lanes: laneRects.flatMap(([line, rect]) => (rect ? [[line, rect] as const] : [])),
146 chips: new Map(chipRects.flatMap(([chipKey, rect]) => (rect ? [[chipKey, rect]] : []))),
147 });
148 });
149 };
150 const moveDrag = (key: string, dx: number, dy: number) => {
151 translateX.set(dx);
152 translateY.set(dy);
153 const target = dropTarget(key, dx, dy);
154 setDrag((current) => {
155 if (current === null || current.key !== key) return current;
156 const previous = current.target;
157 const same =
158 previous === null || target === null
159 ? previous === target
160 : previous.line === target.line && previous.index === target.index;
161 return same ? current : { key, target };
162 });
163 };
164 const endDrag = (key: string, dx: number, dy: number, cancelled: boolean) => {
165 // A touch that never became a drag still finalizes.
166 if (drag?.key !== key) return;
167 const target = cancelled ? null : dropTarget(key, dx, dy);
168 setDrag(null);
169 setRects(null);
170 props.onDragActiveChange(false);
171 if (!target) return;
172 edit((current) => {
173 const others = current[target.line].filter((token) => token.key !== key);
174 const index =
175 target.beforeKey === null
176 ? others.length
177 : others.findIndex((token) => token.key === target.beforeKey);
178 return moveSidebarRowToken(current, key, target.line, index === -1 ? others.length : index);
179 });
180 };
181​
182 const dragged = drag ? findSidebarRowToken(layout, drag.key)?.token : undefined;
183 const draggedRect = drag ? rects?.chips.get(drag.key) : undefined;
184 // Drawn over the lanes rather than inside them: an extra child could wrap a full lane and move
185 // the lanes below away from the rectangles the drop is hit-tested against.
186 const insertion = (() => {
187 const target = drag?.target;
188 if (!target || !rects) return null;
189 const others = shown(target.line).filter((token) => token.key !== drag.key);
190 const before = target.beforeKey === null ? undefined : rects.chips.get(target.beforeKey);
191 const lastKey = others.at(-1)?.key;
192 const after = before || lastKey === undefined ? undefined : rects.chips.get(lastKey);
193 const rect = before ?? after;
194 // An empty lane shows its highlight alone.
195 if (!rect) return null;
196 return {
197 left: (before ? rect.x - 5 : rect.x + rect.width + 3) - rects.container.x,
198 top: rect.y - rects.container.y,
199 height: rect.height,
200 };
201 })();
202​
203 return (
204 <View ref={container}>
205 {LINES.map((line, lineIndex) => {
206 const tokens = shown(line);
207 const target = drag?.target?.line === line ? drag.target : null;
208 return (
209 <View
210 key={line}
211 ref={(view) => {
212 if (view) lanes.current.set(line, view);
213 else lanes.current.delete(line);
214 }}
215 className={cn(
216 "flex-row gap-2.5 py-3 pl-4 pr-3.5",
217 lineIndex > 0 && "border-t border-border-subtle",
218 target && "bg-primary/10",
219 )}
220 >
221 <Text className="w-[58px] pt-1.5 text-sm text-foreground-muted">
222 {lineLabels[line]}
223 </Text>
224 <View className="min-w-0 flex-1 flex-row flex-wrap gap-1.5">
225 {tokens.length === 0 ? (
226 <Text className="py-1.5 text-sm text-foreground-tertiary">
227 {line === "hidden"
228 ? gt`Drag an item here to hide it.`
229 : gt({ context: "empty thread row line" })`Drag an item here.`}
230 </Text>
231 ) : null}
232 {tokens.map((token) => {
233 const found = findSidebarRowToken(layout, token.key);
234 const index = found?.index ?? 0;
235 const label = itemLabel(token);
236 const lifted = drag?.key === token.key;
237 const lineMoves = (["top", "middle", "bottom"] as const).filter(
238 (other) => other !== line,
239 );
240 const canHide = line !== "hidden" && token.id !== "title";
241 return (
242 <LaneChip
243 key={token.key}
244 onView={(view) => {
245 if (view) chips.current.set(token.key, view);
246 else chips.current.delete(token.key);
247 }}
248 lifted={lifted}
249 accessibilityLabel={label}
250 accessibilityValue={lineLabels[line]}
251 accessibilityActions={[
252 ...(line !== "hidden" && index > 0
253 ? [{ name: "earlier", label: gt`Move ${{ item: label }} earlier` }]
254 : []),
255 ...(line !== "hidden" && index < layout[line].length - 1
256 ? [{ name: "later", label: gt`Move ${{ item: label }} later` }]
257 : []),
258 ...lineMoves.map((other) => ({
259 name: other,
260 label: gt`Move ${{ item: label }} to ${{ line: lineLabels[other] }}`,
261 })),
262 ...(token.form
263 ? [{ name: "form", label: gt`Show ${{ item: label }} as` }]
264 : []),
265 ...(canHide
266 ? [
267 {
268 name: "hidden",
269 label:
270 token.id === "spacer"
271 ? gt`Remove ${{ item: label }}`
272 : gt`Hide ${{ item: label }}`,
273 },
274 ]
275 : []),
276 ]}
277 onAccessibilityAction={(action) => {
278 if (props.disabled || !found) return;
279 if (action === "form") {
280 props.onChooseForm(token);
281 return;
282 }
283 if (action === "earlier" || action === "later") {
284 edit((current) =>
285 moveSidebarRowToken(
286 current,
287 token.key,
288 line,
289 index + (action === "earlier" ? -1 : 1),
290 ),
291 );
292 return;
293 }
294 if (LINES.some((other) => other === action)) {
295 edit((current) =>
296 moveSidebarRowToken(
297 current,
298 token.key,
299 action as SidebarRowLine,
300 Number.POSITIVE_INFINITY,
301 ),
302 );
303 }
304 }}
305 onPress={
306 token.form && !props.disabled ? () => props.onChooseForm(token) : undefined
307 }
308 onDragStart={() => startDrag(token.key)}
309 onDragMove={(dx, dy) => moveDrag(token.key, dx, dy)}
310 onDragEnd={(dx, dy, cancelled) => endDrag(token.key, dx, dy, cancelled)}
311 >
312 <LayoutChip token={token} content={props.sample} />
313 </LaneChip>
314 );
315 })}
316 </View>
317 </View>
318 );
319 })}
320 {insertion ? (
321 <View
322 pointerEvents="none"
323 className="absolute w-0.5 rounded-full bg-primary"
324 style={insertion}
325 />
326 ) : null}
327 {dragged && draggedRect && rects ? (
328 <Reanimated.View
329 pointerEvents="none"
330 className="absolute flex-row items-center gap-2"
331 style={[
332 {
333 left: draggedRect.x - rects.container.x,
334 top: draggedRect.y - rects.container.y,
335 },
336 liftedStyle,
337 ]}
338 >
339 <View className="rounded-full bg-grouped-card shadow-md">
340 <LayoutChip token={dragged} content={props.sample} />
341 </View>
342 <View className="rounded-full bg-foreground px-2.5 py-1 shadow-md">
343 <Text className="text-xs font-t3-bold text-screen">{itemLabel(dragged)}</Text>
344 </View>
345 </Reanimated.View>
346 ) : null}
347 </View>
348 );
350​
351function LaneChip(props: {
352 readonly onView: (view: ViewRef | null) => void;
353 readonly lifted: boolean;
354 readonly accessibilityLabel: string;
355 readonly accessibilityValue: string;
356 readonly accessibilityActions: ReadonlyArray<{ readonly name: string; readonly label: string }>;
357 readonly onAccessibilityAction: (action: string) => void;
358 readonly onPress: (() => void) | undefined;
359 readonly onDragStart: () => void;
360 readonly onDragMove: (dx: number, dy: number) => void;
361 readonly onDragEnd: (dx: number, dy: number, cancelled: boolean) => void;
362 readonly children: ReactNode;
363}) {
364 const { onView } = props;
365 const onTap = useEffectEvent(() => props.onPress?.());
366 const onStart = useEffectEvent(() => props.onDragStart());
367 const onMove = useEffectEvent((dx: number, dy: number) => props.onDragMove(dx, dy));
368 const onEnd = useEffectEvent((dx: number, dy: number, cancelled: boolean) =>
369 props.onDragEnd(dx, dy, cancelled),
370 );
371 // The worklets plugin copies the values these callbacks close over when the gesture is built,
372 // so the drop reads its translation from the final event rather than a tracked variable.
373 const [gesture] = useState(() =>
374 Gesture.Exclusive(
375 Gesture.Pan()
376 .activateAfterLongPress(300)
377 .shouldCancelWhenOutside(false)
378 .runOnJS(true)
379 .onStart(() => onStart())
380 .onUpdate((event) => onMove(event.translationX, event.translationY))
381 .onFinalize((event, success) => onEnd(event.translationX, event.translationY, !success)),
382 Gesture.Tap()
383 .runOnJS(true)
384 .onEnd(() => onTap()),
385 ),
386 );
387 return (
388 <GestureDetector gesture={gesture}>
389 <View
390 ref={onView}
391 collapsable={false}
392 accessible
393 accessibilityLabel={props.accessibilityLabel}
394 accessibilityValue={{ text: props.accessibilityValue }}
395 accessibilityActions={props.accessibilityActions}
396 onAccessibilityAction={({ nativeEvent }) =>
397 props.onAccessibilityAction(nativeEvent.actionName)
398 }
399 className={cn("rounded-full", props.lifted && "border border-dashed border-border")}
400 style={{ opacity: props.lifted ? 0.45 : 1 }}
401 >
402 {props.children}
403 </View>
404 </GestureDetector>
405 );
407​
408/** A small copy of what the item shows in the sample row. */
409function LayoutChip(props: {
410 readonly token: SidebarRowToken;
411 readonly content: ThreadRowItemContent;
412}) {
413 const gt = useGT();
414 const { token, content } = props;
415 if (token.id === "spacer") {
416 return (
417 <View className="h-[30px] flex-row items-center gap-1 rounded-full border border-dashed border-border px-3">
418 <SymbolView
419 name="arrow.left.arrow.right"
420 size={14}
421 tintColorClassName="accent-foreground-tertiary"
422 />
423 <Text className="text-sm text-foreground-muted">
424 {gt({ context: "flexible empty space in a layout" })`Spacer`}
425 </Text>
426 </View>
427 );
428 }
429 return (
430 <View className="h-[30px] min-w-10 items-center justify-center rounded-full bg-subtle px-3">
431 <View
432 className="flex-row items-center gap-1.5"
433 style={{ maxWidth: token.id === "title" ? 170 : 150 }}
434 >
435 {token.id === "title" ? (
436 <Text className="shrink font-t3-medium text-foreground" numberOfLines={1}>
437 {content.title}
438 </Text>
439 ) : (
440 threadRowItemNode(token, content)
441 )}
442 {token.form ? (
443 <SymbolView name="chevron.down" size={10} tintColorClassName="accent-foreground-muted" />
444 ) : null}
445 </View>
446 </View>
447 );