@marktiderman/genesis-chat 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +132 -3
  2. package/dist/{chunk-GBJ3YI4E.js → chunk-5XYDVUPS.js} +6 -3
  3. package/dist/chunk-5XYDVUPS.js.map +1 -0
  4. package/dist/{chunk-XQ2ULNHV.js → chunk-D4RPOYB7.js} +4 -4
  5. package/dist/chunk-D4RPOYB7.js.map +1 -0
  6. package/dist/{chunk-RYD6WJE5.js → chunk-O2QSBRSH.js} +3 -3
  7. package/dist/{chunk-RYD6WJE5.js.map → chunk-O2QSBRSH.js.map} +1 -1
  8. package/dist/{chunk-A4YJX7KT.js → chunk-ZQFREERR.js} +3 -3
  9. package/dist/{chunk-A4YJX7KT.js.map → chunk-ZQFREERR.js.map} +1 -1
  10. package/dist/{client-DUIG1hum.d.ts → client-DP7rhJ1U.d.ts} +17 -6
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +2 -2
  13. package/dist/native.d.ts +31 -15
  14. package/dist/native.js +74 -328
  15. package/dist/native.js.map +1 -1
  16. package/dist/{outbox-B9NAWQ58.d.ts → outbox-C4LnqpKT.d.ts} +1 -1
  17. package/dist/push.d.ts +2 -2
  18. package/dist/react.d.ts +4 -8
  19. package/dist/react.js +3 -3
  20. package/dist/server.d.ts +1 -1
  21. package/dist/server.js +1 -1
  22. package/dist/{thread-oPra7pkW.d.ts → thread-CSzdqNR_.d.ts} +1 -1
  23. package/dist/web.d.ts +205 -8
  24. package/dist/web.js +582 -71
  25. package/dist/web.js.map +1 -1
  26. package/migrations/0004_genesis_chat_tenants.sql +716 -0
  27. package/migrations/tests/0001_genesis_chat.test.sql +10 -2
  28. package/migrations/tests/0002_genesis_chat_coaching.test.sql +8 -0
  29. package/migrations/tests/0003_genesis_chat_search_threads.test.sql +8 -0
  30. package/migrations/tests/0004_genesis_chat_tenants.test.sql +259 -0
  31. package/package.json +19 -8
  32. package/src/__tests__/core.test.ts +12 -0
  33. package/src/__tests__/web-dock.test.tsx +465 -0
  34. package/src/__tests__/web-format.test.ts +28 -0
  35. package/src/__tests__/web-photo-viewer.test.tsx +43 -0
  36. package/src/__tests__/web.test.tsx +26 -0
  37. package/src/core/client.ts +5 -1
  38. package/src/core/types.ts +16 -0
  39. package/src/native/__tests__/photo-viewer.test.tsx +24 -5
  40. package/src/native/photo-viewer.tsx +109 -422
  41. package/src/native/thread-screen.tsx +14 -5
  42. package/src/native/use-jump.ts +3 -0
  43. package/src/react/index.tsx +2 -1
  44. package/src/web/attachments.tsx +39 -55
  45. package/src/web/composer.tsx +5 -0
  46. package/src/web/dock.tsx +889 -0
  47. package/src/web/format.ts +6 -15
  48. package/src/web/inbox.tsx +5 -0
  49. package/src/web/index.ts +23 -0
  50. package/src/web/memory-client.ts +1 -1
  51. package/src/web/thread.tsx +42 -3
  52. package/dist/chunk-GBJ3YI4E.js.map +0 -1
  53. package/dist/chunk-XQ2ULNHV.js.map +0 -1
@@ -97,11 +97,13 @@ describe("ChatPhotoViewer", () => {
97
97
  const modal = screen.getByTestId("v");
98
98
  expect(modal.getAttribute("data-presentation-style")).toBe("overFullScreen");
99
99
  expect(modal.getAttribute("data-presentation-style")).not.toBe("pageSheet");
100
- expect(screen.getByTestId("v-counter").textContent).toBe("Photo 2 of 2");
101
- const pager = screen.getByTestId("v-pager");
100
+ // genesis-ui-native's NativeLightbox: a "2 / 2" counter for the eye, and the pager reads chat's words.
101
+ expect(screen.getByTestId("v-counter").textContent).toBe("2 / 2");
102
+ const pager = screen.getByTestId("v-pager-a11y");
102
103
  expect(pager.getAttribute("aria-label")).toBe("Photo, b.jpg");
103
- expect(screen.getByTestId("v-photo-0")).toBeTruthy();
104
- expect(screen.getByTestId("v-photo-1")).toBeTruthy();
104
+ expect(pager.getAttribute("aria-valuetext")).toBe("Photo 2 of 2");
105
+ expect(screen.getByTestId("v-photo-a")).toBeTruthy();
106
+ expect(screen.getByTestId("v-photo-b")).toBeTruthy();
105
107
  });
106
108
 
107
109
  it("closes from its Close button", () => {
@@ -147,6 +149,22 @@ describe("ChatPhotoViewer", () => {
147
149
  expect(screen.getByTestId("v-notice").textContent).toMatch(/Settings/);
148
150
  });
149
151
 
152
+ it("opens again without the last opening's notice", async () => {
153
+ const modules = { mediaLibrary: { requestPermissionsAsync: async () => ({ granted: true }), saveToLibraryAsync: vi.fn(async () => undefined) }, downloadFile: async () => "file:///x.jpg" };
154
+ const photos = [{ key: "a", uri: "https://x.test/a.jpg", alt: "Photo, a.jpg" }];
155
+ const ui = (p: typeof photos | null) => (
156
+ <ChatNativeProvider modules={modules}>
157
+ <ChatPhotoViewer photos={p} onClose={vi.fn()} testID="v" />
158
+ </ChatNativeProvider>
159
+ );
160
+ const { rerender } = render(ui(photos));
161
+ await act(async () => fireEvent.click(screen.getByTestId("v-save")));
162
+ expect(screen.getByTestId("v-notice")).toBeTruthy();
163
+ rerender(ui(null));
164
+ rerender(ui([...photos]));
165
+ expect(screen.queryByTestId("v-notice")).toBeNull();
166
+ });
167
+
150
168
  it("ChatMediaViewer, for one picture, is the same full-screen viewer", () => {
151
169
  render(
152
170
  <ChatNativeProvider>
@@ -201,7 +219,8 @@ describe("ChatThreadScreen", () => {
201
219
  fireEvent.click(second);
202
220
  const modal = await screen.findByTestId("t-viewer");
203
221
  expect(modal.getAttribute("data-presentation-style")).toBe("overFullScreen");
204
- expect(screen.getByTestId("t-viewer-counter").textContent).toBe("Photo 2 of 3");
222
+ expect(screen.getByTestId("t-viewer-counter").textContent).toBe("2 / 3");
223
+ expect(screen.getByTestId("t-viewer-pager-a11y").getAttribute("aria-valuetext")).toBe("Photo 2 of 3");
205
224
  fireEvent.click(screen.getByTestId("t-viewer-close"));
206
225
  await waitFor(() => expect(screen.queryByTestId("t-viewer")).toBeNull());
207
226
  });
@@ -1,33 +1,29 @@
1
1
  /**
2
2
  * @feat:chat
3
- * The photo viewer: a message's photos full screen on black
4
- * (NativeFullScreenModal), swiped left and right, pinched or double-tapped
5
- * to zoom, swiped down (or Close) to leave. Share and Save show when the app
6
- * passed expo-sharing or expo-media-library (with `downloadFile` for photos
7
- * that are only a signed link).
8
- *
9
- * No gesture library: on iOS each photo is a zooming ScrollView (the
10
- * system's own pinch, and a pull down past the edge closes); on Android a
11
- * PanResponder pinches, pans and drags down. With VoiceOver or TalkBack the
12
- * pager is adjustable (swipe up or down for the next or previous photo).
3
+ * The photo viewer: a message's photos full screen in genesis-ui-native's
4
+ * `NativeLightbox` (swiped left and right, pinched or double-tapped to zoom,
5
+ * pulled down or Close to leave, an adjustable pager for VoiceOver and
6
+ * TalkBack). Chat adds its words, and Share and Save when the app passed
7
+ * expo-sharing or expo-media-library (with `downloadFile` for photos that are
8
+ * only a signed link).
13
9
  */
14
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
10
+ import { useCallback, useEffect, useMemo, useState } from "react";
11
+ import { Pressable, View } from "react-native";
15
12
  import {
16
- Animated,
17
- FlatList,
18
- PanResponder,
19
- Platform,
20
- Pressable,
21
- ScrollView,
22
- View,
23
- useWindowDimensions,
24
- type GestureResponderEvent,
25
- type NativeScrollEvent,
26
- type NativeSyntheticEvent,
27
- } from "react-native";
28
- import { useSafeAreaInsets } from "react-native-safe-area-context";
29
- import { FULL_SCREEN_DARK, NativeFullScreenModal, NativeIcon, NativeImage, NativeText, type NativeIconName } from "@marktiderman/genesis-ui-native/components";
30
- import { useReducedMotion } from "@marktiderman/genesis-ui-native/hooks";
13
+ NativeIcon,
14
+ NativeLightbox,
15
+ NativeText,
16
+ lightboxPanLimit,
17
+ lightboxPinchScale,
18
+ lightboxShouldDismiss,
19
+ lightboxTouchDistance,
20
+ LIGHTBOX_DISMISS_DISTANCE,
21
+ LIGHTBOX_DISMISS_VELOCITY,
22
+ LIGHTBOX_DOUBLE_TAP_MS,
23
+ LIGHTBOX_MAX_ZOOM,
24
+ type GalleryItem,
25
+ type NativeIconName,
26
+ } from "@marktiderman/genesis-ui-native/components";
31
27
  import type { ChatMessage } from "../core/types";
32
28
  import { fill } from "./copy";
33
29
  import { useChatNative } from "./context";
@@ -51,210 +47,122 @@ export interface ChatPhotoViewerProps {
51
47
  testID?: string;
52
48
  }
53
49
 
54
- /** Points pulled down (or dragged, on Android) that close the viewer on release. */
55
- export const DISMISS_DISTANCE = 110;
56
- /** Or a quick flick down, in points per millisecond. */
57
- export const DISMISS_VELOCITY = 1.1;
58
- export const MAX_ZOOM = 4;
59
-
60
- /** Whether a drag down that ended here closes the viewer. */
61
- export function shouldDismiss(dy: number, vy: number): boolean {
62
- return dy > DISMISS_DISTANCE || (dy > 24 && vy > DISMISS_VELOCITY);
63
- }
64
-
65
- /** The zoom a pinch has reached: from where it started, by how far the fingers spread. */
66
- export function pinchScale(startScale: number, startDistance: number, distance: number): number {
67
- if (startDistance <= 0) return startScale;
68
- return Math.min(MAX_ZOOM, Math.max(0.8, startScale * (distance / startDistance)));
69
- }
70
-
71
- /** Points between two touches. */
72
- export function touchDistance(touches: readonly { pageX: number; pageY: number }[]): number {
73
- const [a, b] = touches;
74
- if (!a || !b) return 0;
75
- return Math.hypot(a.pageX - b.pageX, a.pageY - b.pageY);
76
- }
77
-
78
- /** How far a zoomed photo may pan before an edge shows, per axis. */
79
- export function panLimit(scale: number, size: number): number {
80
- return Math.max(0, ((scale - 1) * size) / 2);
81
- }
82
-
83
- /** A file already on the phone, which shares and saves without a download. */
50
+ /** @deprecated Use `LIGHTBOX_DISMISS_DISTANCE` from `@marktiderman/genesis-ui-native/components`. */
51
+ export const DISMISS_DISTANCE = LIGHTBOX_DISMISS_DISTANCE;
52
+ /** @deprecated Use `LIGHTBOX_DISMISS_VELOCITY` from `@marktiderman/genesis-ui-native/components`. */
53
+ export const DISMISS_VELOCITY = LIGHTBOX_DISMISS_VELOCITY;
54
+ /** @deprecated Use `LIGHTBOX_MAX_ZOOM` from `@marktiderman/genesis-ui-native/components`. */
55
+ export const MAX_ZOOM = LIGHTBOX_MAX_ZOOM;
56
+ /** @deprecated Use `LIGHTBOX_DOUBLE_TAP_MS` from `@marktiderman/genesis-ui-native/components`. */
57
+ export const DOUBLE_TAP_MS = LIGHTBOX_DOUBLE_TAP_MS;
58
+ /** @deprecated Use `lightboxShouldDismiss` from `@marktiderman/genesis-ui-native/components`. */
59
+ export const shouldDismiss = lightboxShouldDismiss;
60
+ /** @deprecated Use `lightboxPinchScale` from `@marktiderman/genesis-ui-native/components`. */
61
+ export const pinchScale = lightboxPinchScale;
62
+ /** @deprecated Use `lightboxTouchDistance` from `@marktiderman/genesis-ui-native/components`. */
63
+ export const touchDistance = lightboxTouchDistance;
64
+ /** @deprecated Use `lightboxPanLimit` from `@marktiderman/genesis-ui-native/components`. */
65
+ export const panLimit = lightboxPanLimit;
66
+
67
+ /** A file on the phone (a photo still sending), not a link. */
84
68
  export function isLocalUri(uri: string): boolean {
85
69
  return /^(file|ph|content|assets-library):/.test(uri);
86
70
  }
87
71
 
88
- const clamp = (v: number, limit: number) => Math.max(-limit, Math.min(limit, v));
89
- // Between two `onPress`es (each fires on release): a quick double tap measured 330ms apart on iOS.
90
- export const DOUBLE_TAP_MS = 400;
91
-
72
+ /**
73
+ * Chat's photos full screen: genesis-ui-native's `NativeLightbox` (pinch and double-tap zoom, pull
74
+ * down to close, an adjustable pager), with chat's words and its Save and Share buttons when the
75
+ * app passes `mediaLibrary` and `sharing` to `ChatNativeProvider`.
76
+ */
92
77
  export function ChatPhotoViewer({ photos, initialIndex = 0, onClose, testID = "chat-photo-viewer" }: ChatPhotoViewerProps) {
93
- const open = photos !== null && photos.length > 0;
94
- return (
95
- <NativeFullScreenModal open={open} onOpenChange={(o) => (o ? undefined : onClose())} tone="none" testID={testID}>
96
- {open ? <ViewerBody photos={photos} initialIndex={Math.min(Math.max(0, initialIndex), photos.length - 1)} onClose={onClose} testID={testID} /> : null}
97
- </NativeFullScreenModal>
98
- );
99
- }
100
-
101
- function ViewerBody({ photos, initialIndex, onClose, testID }: { photos: readonly ChatPhoto[]; initialIndex: number; onClose: () => void; testID: string }) {
102
78
  const { copy, modules } = useChatNative();
103
- const { width, height } = useWindowDimensions();
104
- const insets = useSafeAreaInsets();
105
- const reducedMotion = useReducedMotion();
106
79
  const [index, setIndex] = useState(initialIndex);
107
- const [zoomed, setZoomed] = useState(false);
108
- const [chrome, setChrome] = useState(true);
109
80
  const [busy, setBusy] = useState(false);
110
81
  const [notice, setNotice] = useState<string | null>(null);
111
- const backdrop = useRef(new Animated.Value(1)).current;
112
- const listRef = useRef<FlatList<ChatPhoto> | null>(null);
113
- const photo = photos[index] ?? photos[0]!;
114
- const many = photos.length > 1;
82
+ const items = useMemo<GalleryItem[]>(() => (photos ?? []).map((p) => ({ id: p.key, src: p.uri, alt: p.alt })), [photos]);
115
83
 
84
+ // Each opening starts at its photo, with no notice or busy state left from the last one.
85
+ useEffect(() => {
86
+ if (!photos) return;
87
+ setIndex(initialIndex);
88
+ setNotice(null);
89
+ setBusy(false);
90
+ }, [photos, initialIndex]);
116
91
  useEffect(() => {
117
92
  if (!notice) return;
118
93
  const t = setTimeout(() => setNotice(null), 2500);
119
94
  return () => clearTimeout(t);
120
95
  }, [notice]);
121
96
 
122
- const goTo = useCallback(
123
- (i: number) => {
124
- if (i < 0 || i >= photos.length) return;
125
- setIndex(i);
126
- setZoomed(false);
127
- listRef.current?.scrollToIndex?.({ index: i, animated: !reducedMotion });
128
- },
129
- [photos.length, reducedMotion],
130
- );
131
-
132
- const onMomentumEnd = useCallback(
133
- (e: NativeSyntheticEvent<NativeScrollEvent>) => {
134
- const i = Math.round(e.nativeEvent.contentOffset.x / Math.max(1, width));
135
- if (i !== index && i >= 0 && i < photos.length) {
136
- setIndex(i);
137
- setZoomed(false);
138
- }
139
- },
140
- [width, index, photos.length],
141
- );
142
-
97
+ const list = photos ?? [];
143
98
  // A copy on the phone for sharing and saving: a local file as is, a signed link through downloadFile.
144
99
  const local = async (uri: string) => (isLocalUri(uri) ? uri : modules.downloadFile ? modules.downloadFile(uri) : null);
145
- const reachable = Boolean(modules.downloadFile) || photos.every((p) => isLocalUri(p.uri));
100
+ const reachable = Boolean(modules.downloadFile) || list.every((p) => isLocalUri(p.uri));
146
101
  const canShare = Boolean(modules.sharing) && reachable;
147
102
  const canSave = Boolean(modules.mediaLibrary) && reachable;
148
103
 
149
- const run = async (what: "share" | "save") => {
150
- if (busy) return;
151
- setBusy(true);
152
- try {
153
- if (what === "save") {
154
- const lib = modules.mediaLibrary!;
155
- const permission = await lib.requestPermissionsAsync(true);
156
- if (!permission.granted) {
157
- setNotice(copy.photosDenied);
158
- return;
104
+ const run = useCallback(
105
+ async (what: "share" | "save", uri: string) => {
106
+ if (busy) return;
107
+ setBusy(true);
108
+ try {
109
+ if (what === "save") {
110
+ const lib = modules.mediaLibrary!;
111
+ const permission = await lib.requestPermissionsAsync(true);
112
+ if (!permission.granted) {
113
+ setNotice(copy.photosDenied);
114
+ return;
115
+ }
116
+ const file = await local(uri);
117
+ if (!file) throw new Error("no copy on the phone");
118
+ await lib.saveToLibraryAsync(file);
119
+ haptic(modules.haptics, "send");
120
+ setNotice(copy.photoSaved);
121
+ } else {
122
+ const sharing = modules.sharing!;
123
+ if (!(await sharing.isAvailableAsync())) throw new Error("sharing unavailable");
124
+ const file = await local(uri);
125
+ if (!file) throw new Error("no copy on the phone");
126
+ await sharing.shareAsync(file, { dialogTitle: copy.sharePhoto });
159
127
  }
160
- const file = await local(photo.uri);
161
- if (!file) throw new Error("no copy on the phone");
162
- await lib.saveToLibraryAsync(file);
163
- haptic(modules.haptics, "send");
164
- setNotice(copy.photoSaved);
165
- } else {
166
- const sharing = modules.sharing!;
167
- if (!(await sharing.isAvailableAsync())) throw new Error("sharing unavailable");
168
- const file = await local(photo.uri);
169
- if (!file) throw new Error("no copy on the phone");
170
- await sharing.shareAsync(file, { dialogTitle: copy.sharePhoto });
128
+ } catch {
129
+ haptic(modules.haptics, "error");
130
+ setNotice(copy.actionFailed);
131
+ } finally {
132
+ setBusy(false);
171
133
  }
172
- } catch {
173
- haptic(modules.haptics, "error");
174
- setNotice(copy.actionFailed);
175
- } finally {
176
- setBusy(false);
177
- }
178
- };
179
-
180
- const toggleChrome = useCallback(() => setChrome((c) => !c), []);
181
- const onPull = useCallback((dy: number) => backdrop.setValue(Math.max(0.35, 1 - Math.max(0, dy) / 400)), [backdrop]);
182
- const renderItem = useCallback(
183
- ({ item, index: i }: { item: ChatPhoto; index: number }) => (
184
- <ZoomablePhoto
185
- photo={item}
186
- width={width}
187
- height={height}
188
- active={i === index}
189
- onZoomChange={setZoomed}
190
- onPull={onPull}
191
- onDismiss={onClose}
192
- onTap={toggleChrome}
193
- testID={`${testID}-photo-${i}`}
194
- />
195
- ),
196
- [width, height, index, onPull, onClose, toggleChrome, testID],
134
+ },
135
+ [busy, modules, copy],
197
136
  );
198
137
 
199
- const counter = many ? fill(copy.photoOf, { n: index + 1, count: photos.length }) : null;
200
138
  return (
201
- <View style={{ flex: 1 }}>
202
- <Animated.View pointerEvents="none" style={{ position: "absolute", top: 0, right: 0, bottom: 0, left: 0, backgroundColor: FULL_SCREEN_DARK, opacity: backdrop }} />
203
- <View
204
- style={{ flex: 1 }}
205
- accessible
206
- accessibilityRole="adjustable"
207
- accessibilityLabel={photo.alt}
208
- accessibilityValue={counter ? { text: counter } : undefined}
209
- accessibilityHint={many ? copy.viewerHint : undefined}
210
- accessibilityActions={many ? [{ name: "increment" }, { name: "decrement" }] : []}
211
- onAccessibilityAction={(e) => {
212
- if (e.nativeEvent.actionName === "increment") goTo(index + 1);
213
- if (e.nativeEvent.actionName === "decrement") goTo(index - 1);
214
- }}
215
- testID={`${testID}-pager`}
216
- >
217
- <FlatList
218
- ref={listRef}
219
- testID={`${testID}-list`}
220
- data={photos as ChatPhoto[]}
221
- horizontal
222
- pagingEnabled
223
- scrollEnabled={many && !zoomed}
224
- showsHorizontalScrollIndicator={false}
225
- initialScrollIndex={initialIndex}
226
- getItemLayout={(_d, i) => ({ length: width, offset: width * i, index: i })}
227
- keyExtractor={(p) => p.key}
228
- renderItem={renderItem}
229
- onMomentumScrollEnd={onMomentumEnd}
230
- extraData={index}
231
- windowSize={3}
232
- initialNumToRender={1}
233
- />
234
- </View>
235
- {chrome ? (
236
- <View pointerEvents="box-none" style={{ position: "absolute", top: insets.top, left: 0, right: 0, flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 8, minHeight: 52 }}>
237
- <ViewerButton icon="close" label={copy.closeViewer} onPress={onClose} testID={`${testID}-close`} />
238
- <View style={{ flex: 1, alignItems: "center" }}>
239
- {counter ? (
240
- <NativeText testID={`${testID}-counter`} accessibilityLiveRegion="polite" style={{ color: "#FFFFFF", fontWeight: "600", fontVariant: ["tabular-nums"] }}>
241
- {counter}
242
- </NativeText>
243
- ) : null}
244
- </View>
245
- {canSave ? <ViewerButton icon="download" label={copy.savePhoto} onPress={() => void run("save")} disabled={busy} testID={`${testID}-save`} /> : null}
246
- {canShare ? <ViewerButton icon="share" label={copy.sharePhoto} onPress={() => void run("share")} disabled={busy} testID={`${testID}-share`} /> : null}
247
- {!canSave && !canShare ? <View style={{ width: 44 }} /> : null}
139
+ <NativeLightbox
140
+ open={photos != null && photos.length > 0}
141
+ onOpenChange={(open) => !open && onClose()}
142
+ items={items}
143
+ index={index}
144
+ onIndexChange={setIndex}
145
+ labels={{
146
+ close: copy.closeViewer,
147
+ position: (n, count) => fill(copy.photoOf, { n, count }),
148
+ pagerHint: copy.viewerHint,
149
+ }}
150
+ renderActions={(item) => (
151
+ <View style={{ flexDirection: "row", gap: 8 }}>
152
+ {canSave ? <ViewerButton icon="download" label={copy.savePhoto} onPress={() => void run("save", item.src)} disabled={busy} testID={`${testID}-save`} /> : null}
153
+ {canShare ? <ViewerButton icon="share" label={copy.sharePhoto} onPress={() => void run("share", item.src)} disabled={busy} testID={`${testID}-share`} /> : null}
248
154
  </View>
249
- ) : null}
250
- {notice ? (
251
- <View pointerEvents="none" style={{ position: "absolute", left: 24, right: 24, bottom: insets.bottom + 24, alignItems: "center" }}>
252
- <View accessibilityLiveRegion="assertive" testID={`${testID}-notice`} style={{ backgroundColor: "rgba(40,40,40,0.92)", borderRadius: 14, paddingHorizontal: 16, paddingVertical: 10 }}>
155
+ )}
156
+ // The result of Save or Share shows where the caption goes.
157
+ renderCaption={() =>
158
+ notice ? (
159
+ <View accessibilityLiveRegion="assertive" testID={`${testID}-notice`} style={{ alignSelf: "center", backgroundColor: "rgba(40,40,40,0.92)", borderRadius: 14, paddingHorizontal: 16, paddingVertical: 10 }}>
253
160
  <NativeText style={{ color: "#FFFFFF", textAlign: "center" }}>{notice}</NativeText>
254
161
  </View>
255
- </View>
256
- ) : null}
257
- </View>
162
+ ) : null
163
+ }
164
+ testID={testID}
165
+ />
258
166
  );
259
167
  }
260
168
 
@@ -275,227 +183,6 @@ function ViewerButton({ icon, label, onPress, disabled = false, testID }: { icon
275
183
  );
276
184
  }
277
185
 
278
- interface ZoomableProps {
279
- photo: ChatPhoto;
280
- width: number;
281
- height: number;
282
- /** The page on screen: another page resets its zoom. */
283
- active: boolean;
284
- onZoomChange: (zoomed: boolean) => void;
285
- /** How far it's pulled down, for the backdrop's fade. */
286
- onPull: (dy: number) => void;
287
- onDismiss: () => void;
288
- onTap: () => void;
289
- testID: string;
290
- }
291
-
292
- function ZoomablePhoto(props: ZoomableProps) {
293
- return Platform.OS === "ios" ? <ZoomableIos {...props} /> : <ZoomablePan {...props} />;
294
- }
295
-
296
- /** The photo itself, contained, on a transparent background so the backdrop's fade shows. */
297
- function Photo({ photo, width, height, testID }: { photo: ChatPhoto; width: number; height: number; testID: string }) {
298
- return <NativeImage src={photo.uri} alt={photo.alt} width={width} height={height} contentFit="contain" className="bg-transparent" testID={testID} />;
299
- }
300
-
301
- /** A tap that waits to see whether it's the first half of a double tap. */
302
- function useTaps(onSingle: () => void, onDouble: (e: { locationX: number; locationY: number }) => void) {
303
- const last = useRef(0);
304
- const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
305
- useEffect(
306
- () => () => {
307
- if (timer.current) clearTimeout(timer.current);
308
- },
309
- [],
310
- );
311
- return (e: GestureResponderEvent) => {
312
- const now = Date.now();
313
- const at = { locationX: e.nativeEvent?.locationX ?? 0, locationY: e.nativeEvent?.locationY ?? 0 };
314
- if (now - last.current < DOUBLE_TAP_MS) {
315
- last.current = 0;
316
- if (timer.current) clearTimeout(timer.current);
317
- onDouble(at);
318
- return;
319
- }
320
- last.current = now;
321
- timer.current = setTimeout(onSingle, DOUBLE_TAP_MS);
322
- };
323
- }
324
-
325
- type ZoomRect = { x: number; y: number; width: number; height: number };
326
- type ZoomScrollView = ScrollView & { scrollResponderZoomTo?: (rect: ZoomRect & { animated?: boolean }, animated?: boolean) => void };
327
-
328
- /**
329
- * Zooms to a rect. React Native 0.88 drops `rect.animated` and animates per the deprecated second
330
- * argument (ScrollView.js `scrollResponderZoomTo`), so both are given: the rect's keeps it from
331
- * warning, the second is the one it uses.
332
- */
333
- function zoomTo(view: ZoomScrollView | null, rect: ZoomRect, animated: boolean) {
334
- view?.scrollResponderZoomTo?.({ ...rect, animated }, animated);
335
- }
336
-
337
- /** iOS: the system's zooming scroll view; at full size, a pull down past the top closes. */
338
- function ZoomableIos({ photo, width, height, active, onZoomChange, onPull, onDismiss, onTap, testID }: ZoomableProps) {
339
- const ref = useRef<ZoomScrollView | null>(null);
340
- const scale = useRef(1);
341
- const reducedMotion = useReducedMotion();
342
- useEffect(() => {
343
- if (!active && scale.current > 1.01) {
344
- zoomTo(ref.current, { x: 0, y: 0, width, height }, false);
345
- scale.current = 1;
346
- }
347
- }, [active, width, height]);
348
- const tap = useTaps(onTap, (at) => {
349
- if (scale.current > 1.01) return zoomTo(ref.current, { x: 0, y: 0, width, height }, !reducedMotion);
350
- const w = width / 2.5;
351
- const h = height / 2.5;
352
- zoomTo(ref.current, { x: at.locationX - w / 2, y: at.locationY - h / 2, width: w, height: h }, !reducedMotion);
353
- });
354
- return (
355
- <ScrollView
356
- ref={ref as never}
357
- testID={testID}
358
- style={{ width, height }}
359
- contentContainerStyle={{ width, height }}
360
- maximumZoomScale={MAX_ZOOM}
361
- minimumZoomScale={1}
362
- bouncesZoom
363
- centerContent
364
- alwaysBounceVertical
365
- showsHorizontalScrollIndicator={false}
366
- showsVerticalScrollIndicator={false}
367
- scrollEventThrottle={16}
368
- onScroll={(e) => {
369
- const z = e.nativeEvent.zoomScale ?? 1;
370
- if (z > 1.01 !== scale.current > 1.01) onZoomChange(z > 1.01);
371
- scale.current = z;
372
- if (z <= 1.01) onPull(-e.nativeEvent.contentOffset.y);
373
- }}
374
- onScrollEndDrag={(e) => {
375
- if (scale.current > 1.01) return;
376
- // iOS reports the release velocity in points per millisecond, negative while pulling down.
377
- if (shouldDismiss(-e.nativeEvent.contentOffset.y, -(e.nativeEvent.velocity?.y ?? 0))) onDismiss();
378
- else onPull(0);
379
- }}
380
- >
381
- <Pressable accessible={false} onPress={tap} style={{ width, height }}>
382
- <Photo photo={photo} width={width} height={height} testID={`${testID}-image`} />
383
- </Pressable>
384
- </ScrollView>
385
- );
386
- }
387
-
388
- /** Android (no zooming ScrollView): two fingers pinch, one pans a zoomed photo or drags it down to close. */
389
- function ZoomablePan({ photo, width, height, active, onZoomChange, onPull, onDismiss, onTap, testID }: ZoomableProps) {
390
- const reducedMotion = useReducedMotion();
391
- const scale = useRef(new Animated.Value(1)).current;
392
- const tx = useRef(new Animated.Value(0)).current;
393
- const ty = useRef(new Animated.Value(0)).current;
394
- const s = useRef({ scale: 1, x: 0, y: 0, startScale: 1, startDistance: 0, startX: 0, startY: 0, pinching: false, dragging: false });
395
-
396
- const settle = useCallback(
397
- (to: { scale: number; x: number; y: number }) => {
398
- s.current.scale = to.scale;
399
- s.current.x = to.x;
400
- s.current.y = to.y;
401
- onZoomChange(to.scale > 1.01);
402
- if (reducedMotion) {
403
- scale.setValue(to.scale);
404
- tx.setValue(to.x);
405
- ty.setValue(to.y);
406
- return;
407
- }
408
- Animated.parallel([
409
- Animated.spring(scale, { toValue: to.scale, useNativeDriver: true }),
410
- Animated.spring(tx, { toValue: to.x, useNativeDriver: true }),
411
- Animated.spring(ty, { toValue: to.y, useNativeDriver: true }),
412
- ]).start();
413
- },
414
- [reducedMotion, onZoomChange, scale, tx, ty],
415
- );
416
- useEffect(() => {
417
- if (!active && s.current.scale > 1.01) settle({ scale: 1, x: 0, y: 0 });
418
- }, [active, settle]);
419
-
420
- const tap = useTaps(onTap, (at) => {
421
- if (s.current.scale > 1.01) return settle({ scale: 1, x: 0, y: 0 });
422
- const z = 2.5;
423
- settle({ scale: z, x: clamp((width / 2 - at.locationX) * (z - 1), panLimit(z, width)), y: clamp((height / 2 - at.locationY) * (z - 1), panLimit(z, height)) });
424
- });
425
-
426
- const responder = useMemo(
427
- () =>
428
- PanResponder.create({
429
- onStartShouldSetPanResponder: () => false,
430
- onMoveShouldSetPanResponder: (e, g) => e.nativeEvent.touches.length >= 2 || s.current.scale > 1.01 || (g.dy > 8 && Math.abs(g.dy) > Math.abs(g.dx) * 1.5),
431
- onPanResponderTerminationRequest: () => false,
432
- onPanResponderGrant: (e) => {
433
- const st = s.current;
434
- st.pinching = e.nativeEvent.touches.length >= 2;
435
- st.dragging = !st.pinching && st.scale <= 1.01;
436
- st.startScale = st.scale;
437
- st.startDistance = touchDistance(e.nativeEvent.touches);
438
- st.startX = st.x;
439
- st.startY = st.y;
440
- },
441
- onPanResponderMove: (e, g) => {
442
- const st = s.current;
443
- const touches = e.nativeEvent.touches;
444
- if (touches.length >= 2) {
445
- if (!st.pinching) {
446
- st.pinching = true;
447
- st.dragging = false;
448
- st.startScale = st.scale;
449
- st.startDistance = touchDistance(touches);
450
- }
451
- st.scale = pinchScale(st.startScale, st.startDistance, touchDistance(touches));
452
- scale.setValue(st.scale);
453
- return;
454
- }
455
- if (st.dragging) {
456
- st.y = Math.max(0, g.dy);
457
- ty.setValue(st.y);
458
- onPull(st.y);
459
- return;
460
- }
461
- if (st.scale > 1.01) {
462
- st.x = clamp(st.startX + g.dx, panLimit(st.scale, width));
463
- st.y = clamp(st.startY + g.dy, panLimit(st.scale, height));
464
- tx.setValue(st.x);
465
- ty.setValue(st.y);
466
- }
467
- },
468
- onPanResponderRelease: (_e, g) => {
469
- const st = s.current;
470
- if (st.dragging) {
471
- st.dragging = false;
472
- if (shouldDismiss(g.dy, g.vy)) return onDismiss();
473
- onPull(0);
474
- return settle({ scale: 1, x: 0, y: 0 });
475
- }
476
- st.pinching = false;
477
- const z = Math.max(1, st.scale);
478
- settle({ scale: z, x: clamp(st.x, panLimit(z, width)), y: clamp(st.y, panLimit(z, height)) });
479
- },
480
- onPanResponderTerminate: () => {
481
- onPull(0);
482
- settle({ scale: Math.max(1, s.current.scale), x: 0, y: 0 });
483
- },
484
- }),
485
- [width, height, onPull, onDismiss, settle, scale, tx, ty],
486
- );
487
-
488
- return (
489
- <View testID={testID} style={{ width, height, overflow: "hidden" }} {...responder.panHandlers}>
490
- <Animated.View style={{ width, height, transform: [{ translateX: tx }, { translateY: ty }, { scale }] }}>
491
- <Pressable accessible={false} onPress={tap} style={{ width, height }}>
492
- <Photo photo={photo} width={width} height={height} testID={`${testID}-image`} />
493
- </Pressable>
494
- </Animated.View>
495
- </View>
496
- );
497
- }
498
-
499
186
  /**
500
187
  * The photos of the message a tapped photo belongs to, and where it is among them, for
501
188
  * `ChatPhotoViewer`: swiping goes through that message's photos. A photo in no message