@marktiderman/genesis-support 0.0.0-stage → 0.2.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.
package/dist/native.js ADDED
@@ -0,0 +1,722 @@
1
+ import { supportPaths, createSupportClient, defineSupportBlock, SupportError } from './chunk-4VFYVQUF.js';
2
+ import { resolveSupportCopy, createContextCollector, composeCollectors, fill, FEEDBACK_TYPES } from './chunk-ZV4KJBUF.js';
3
+ import { createContext, useContext, useSyncExternalStore, useRef, useState, useEffect, useMemo } from 'react';
4
+ import { Platform, Dimensions, PanResponder, View, Image, Modal, Alert } from 'react-native';
5
+ import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
6
+ import { NativeText, NativeSegmentedControl, NativeButton, NativeLabel, NativeTextarea, NativeSwitch, NativeInput } from '@marktiderman/genesis-ui-native/components';
7
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
8
+ import { SafeAreaView } from 'react-native-safe-area-context';
9
+ import { useThemeRoles } from '@marktiderman/genesis-ui-native/hooks';
10
+
11
+ // src/native/modules.ts
12
+ function listenForShake(accelerometer, onShake, options = {}) {
13
+ const { threshold = 2.3, jolts = 2, windowMs = 1e3, cooldownMs = 3e3, intervalMs = 100, now = Date.now } = options;
14
+ const recent = [];
15
+ let quietUntil = 0;
16
+ accelerometer.setUpdateInterval?.(intervalMs);
17
+ const subscription = accelerometer.addListener(({ x, y, z }) => {
18
+ const t = now();
19
+ if (t < quietUntil) return;
20
+ if (Math.sqrt(x * x + y * y + z * z) < threshold) return;
21
+ recent.push(t);
22
+ while (recent.length && t - recent[0] > windowMs) recent.shift();
23
+ if (recent.length >= jolts) {
24
+ recent.length = 0;
25
+ quietUntil = t + cooldownMs;
26
+ onShake();
27
+ }
28
+ });
29
+ return () => subscription.remove();
30
+ }
31
+ var SupportContext = createContext(null);
32
+ var LEGACY_CLOSE_MS = 400;
33
+ function useSupport() {
34
+ const block = useContext(SupportContext);
35
+ if (!block) throw new Error("useSupport: no support block. Pass `blocks={[createSupport(\u2026)]}` to GenesisNativeApp, or wrap in <SupportProvider>.");
36
+ return block;
37
+ }
38
+ function useOptionalSupport() {
39
+ return useContext(SupportContext);
40
+ }
41
+ function SupportProvider({ block, children }) {
42
+ return /* @__PURE__ */ jsx(SupportContext.Provider, { value: block, children });
43
+ }
44
+ var SUPPORT_QUERY_ROOT = "genesis-support";
45
+ function useUnreadReplies() {
46
+ const block = useSupport();
47
+ const { data } = useQuery({ queryKey: [SUPPORT_QUERY_ROOT, "reports"], queryFn: () => block.client.myReports(), staleTime: 6e4 });
48
+ return (data ?? []).filter((r) => r.unread).length;
49
+ }
50
+ function createSupport(options) {
51
+ const copy = resolveSupportCopy(options.copy);
52
+ const paths = supportPaths(options.basePath);
53
+ const client = createSupportClient(options.supabase);
54
+ const platform = options.platform ?? Platform.OS;
55
+ let route = null;
56
+ let pending = null;
57
+ const listeners = /* @__PURE__ */ new Set();
58
+ const setPending = (next) => {
59
+ pending = next;
60
+ for (const l of listeners) l();
61
+ };
62
+ const defaults = createContextCollector({
63
+ platform,
64
+ appVersion: typeof options.appVersion === "function" ? options.appVersion : () => options.appVersion,
65
+ route: () => route ?? void 0,
66
+ device: () => {
67
+ const screen = Dimensions.get("screen");
68
+ return { os: platform, osVersion: String(Platform.Version), screen: { width: Math.round(screen.width), height: Math.round(screen.height), scale: screen.scale } };
69
+ }
70
+ });
71
+ const collector = options.collector ? composeCollectors(defaults, options.collector) : defaults;
72
+ const declaration = defineSupportBlock({
73
+ basePath: options.basePath,
74
+ copy: options.copy,
75
+ settings: options.settings,
76
+ ideas: options.ideas,
77
+ useHelpSubtitle: () => {
78
+ const unread = useUnreadReplies();
79
+ return unread ? fill(copy.settings.unreadReplies, { count: unread }) : null;
80
+ }
81
+ });
82
+ const report = (error, where) => {
83
+ try {
84
+ options.onError?.(error instanceof Error ? error : new Error(String(error)), where);
85
+ } catch {
86
+ }
87
+ };
88
+ let opening = false;
89
+ function DevtoolsFeedback({ debugInfo, close }) {
90
+ return /* @__PURE__ */ jsx(
91
+ NativeButton,
92
+ {
93
+ variant: "outline",
94
+ testID: "genesis-support-devtools-feedback",
95
+ onPress: async () => {
96
+ const closed = close();
97
+ await (closed instanceof Promise ? closed : new Promise((resolve) => setTimeout(resolve, LEGACY_CLOSE_MS)));
98
+ void block.openFeedback({ extra: { debugInfo: debugInfo.slice(0, 8e3) } });
99
+ },
100
+ children: copy.settings.sendFeedback
101
+ }
102
+ );
103
+ }
104
+ const block = {
105
+ ...declaration,
106
+ contributes: { ...declaration.contributes, slots: { devtoolsFeedback: DevtoolsFeedback } },
107
+ platforms: ["native"],
108
+ options,
109
+ client,
110
+ copy,
111
+ paths,
112
+ collector,
113
+ async openFeedback({ screenshot = true, extra, delayMs = 0 } = {}) {
114
+ if (opening) return;
115
+ opening = true;
116
+ try {
117
+ if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
118
+ let shot = null;
119
+ if (screenshot && options.viewShot) {
120
+ try {
121
+ const uri = await options.viewShot.captureScreen({ format: "jpg", quality: 0.8, result: "data-uri" });
122
+ const window = Dimensions.get("window");
123
+ const scale = Dimensions.get("screen").scale || 1;
124
+ shot = { uri, contentType: "image/jpeg", width: Math.round(window.width * scale), height: Math.round(window.height * scale) };
125
+ } catch (error) {
126
+ report(error, "capture");
127
+ }
128
+ }
129
+ setPending({ route, screenshot: shot, extra });
130
+ options.navigate(paths.feedback);
131
+ } finally {
132
+ opening = false;
133
+ }
134
+ },
135
+ takePending() {
136
+ const p = pending;
137
+ if (p) setPending(null);
138
+ return p;
139
+ },
140
+ peekPending: () => pending,
141
+ subscribePending(listener) {
142
+ listeners.add(listener);
143
+ return () => listeners.delete(listener);
144
+ },
145
+ currentRoute: () => route,
146
+ Root: function SupportRoot({ children }) {
147
+ const current = (options.useCurrentRoute ?? noRoute)();
148
+ useEffect(() => {
149
+ if (current) route = current;
150
+ }, [current]);
151
+ useEffect(() => {
152
+ if (!options.accelerometer || options.shake === false) return;
153
+ try {
154
+ return listenForShake(
155
+ options.accelerometer,
156
+ () => {
157
+ if (route && route.startsWith(paths.inbox)) return;
158
+ void block.openFeedback();
159
+ },
160
+ options.shake || {}
161
+ );
162
+ } catch (error) {
163
+ report(error, "shake");
164
+ return void 0;
165
+ }
166
+ }, []);
167
+ return /* @__PURE__ */ jsx(SupportProvider, { block, children });
168
+ }
169
+ };
170
+ return block;
171
+ }
172
+ function noRoute() {
173
+ return "";
174
+ }
175
+ function usePendingFeedback() {
176
+ const block = useSupport();
177
+ return useSyncExternalStore(block.subscribePending, block.peekPending, block.peekPending);
178
+ }
179
+ var DOT = 6;
180
+ var MAX_DOTS = 3e3;
181
+ function strokeDots(points, spacing = DOT / 2) {
182
+ const dots = [];
183
+ for (let i = 0; i < points.length; i++) {
184
+ const p = points[i];
185
+ const prev = points[i - 1];
186
+ if (prev) {
187
+ const dist = Math.hypot(p.x - prev.x, p.y - prev.y);
188
+ for (let d = spacing; d < dist; d += spacing) dots.push({ x: prev.x + (p.x - prev.x) * d / dist, y: prev.y + (p.y - prev.y) * d / dist });
189
+ }
190
+ dots.push(p);
191
+ }
192
+ return dots;
193
+ }
194
+ function clamp(p, size) {
195
+ const fix = (v, max) => Number.isFinite(v) ? Math.min(Math.max(v, 0), max || v) : 0;
196
+ return { x: fix(p.x, size.width), y: fix(p.y, size.height) };
197
+ }
198
+ function boxOf(from, to) {
199
+ return { left: Math.min(from.x, to.x), top: Math.min(from.y, to.y), width: Math.abs(to.x - from.x), height: Math.abs(to.y - from.y) };
200
+ }
201
+ function ScreenshotAnnotator({ screenshot, viewShot, copy, onDone, onCancel, testID = "genesis-support-annotator" }) {
202
+ const colors = useThemeRoles();
203
+ const surface = useRef(null);
204
+ const setSurface = useRef((node) => {
205
+ surface.current = node;
206
+ }).current;
207
+ const [tool, setTool] = useState("pen");
208
+ const [marks, setMarks] = useState([]);
209
+ const [draft, setDraft] = useState(null);
210
+ const [width, setWidth] = useState(0);
211
+ const [saving, setSaving] = useState(false);
212
+ const [failed, setFailed] = useState(false);
213
+ const toolRef = useRef(tool);
214
+ toolRef.current = tool;
215
+ const draftRef = useRef(null);
216
+ const ratio = screenshot.width / Math.max(1, screenshot.height);
217
+ const maxHeight = Math.round(Dimensions.get("window").height * 0.55);
218
+ const fitWidth = width ? Math.min(width, Math.round(maxHeight * ratio)) : 0;
219
+ const height = fitWidth ? Math.round(fitWidth / ratio) : 0;
220
+ const size = useRef({ width: 0, height: 0 });
221
+ size.current = { width: fitWidth, height };
222
+ const start = useRef({ x: 0, y: 0 });
223
+ const responder = useRef(
224
+ PanResponder.create({
225
+ onStartShouldSetPanResponder: () => true,
226
+ onMoveShouldSetPanResponder: () => true,
227
+ // Drawing inside a scroll view: keep the touch, don't hand it to the scroll.
228
+ onPanResponderTerminationRequest: () => false,
229
+ onPanResponderGrant: (event) => {
230
+ const p = clamp({ x: event.nativeEvent.locationX, y: event.nativeEvent.locationY }, size.current);
231
+ start.current = p;
232
+ draftRef.current = toolRef.current === "pen" ? { kind: "pen", points: [p] } : { kind: "hide", from: p, to: p };
233
+ setDraft(draftRef.current);
234
+ },
235
+ onPanResponderMove: (_event, gesture) => {
236
+ const p = clamp({ x: start.current.x + gesture.dx, y: start.current.y + gesture.dy }, size.current);
237
+ const d = draftRef.current;
238
+ if (!d) return;
239
+ draftRef.current = d.kind === "pen" ? { kind: "pen", points: [...d.points, p] } : { ...d, to: p };
240
+ setDraft(draftRef.current);
241
+ },
242
+ onPanResponderRelease: () => {
243
+ const d = draftRef.current;
244
+ draftRef.current = null;
245
+ setDraft(null);
246
+ if (d) setMarks((all2) => [...all2, d]);
247
+ },
248
+ // A scroll view above can still take the touch (iOS's own pan): keep what was drawn so far.
249
+ onPanResponderTerminate: () => {
250
+ const d = draftRef.current;
251
+ draftRef.current = null;
252
+ setDraft(null);
253
+ if (d) setMarks((all2) => [...all2, d]);
254
+ }
255
+ })
256
+ ).current;
257
+ const done = async () => {
258
+ if (!marks.length) {
259
+ onDone(screenshot, false);
260
+ return;
261
+ }
262
+ setSaving(true);
263
+ setFailed(false);
264
+ try {
265
+ const uri = await viewShot.captureRef(surface.current, { format: "jpg", quality: 0.85, result: "data-uri" });
266
+ setSaving(false);
267
+ onDone({ ...screenshot, uri, contentType: "image/jpeg" }, true);
268
+ } catch {
269
+ setSaving(false);
270
+ setFailed(true);
271
+ }
272
+ };
273
+ let dots = 0;
274
+ const all = draft ? [...marks, draft] : marks;
275
+ return /* @__PURE__ */ jsxs(View, { testID, style: { gap: 12 }, children: [
276
+ /* @__PURE__ */ jsx(NativeText, { style: { color: colors.secondaryLabel, fontSize: 13, lineHeight: 18 }, children: copy.hint }),
277
+ /* @__PURE__ */ jsx(
278
+ NativeSegmentedControl,
279
+ {
280
+ testID: `${testID}-tool`,
281
+ options: [
282
+ { value: "pen", label: copy.pen },
283
+ { value: "hide", label: copy.hide }
284
+ ],
285
+ value: tool,
286
+ onChange: (v) => setTool(v)
287
+ }
288
+ ),
289
+ /* @__PURE__ */ jsx(View, { onLayout: (e) => setWidth(e.nativeEvent.layout.width), style: { width: "100%" }, children: /* @__PURE__ */ jsxs(View, { ref: setSurface, collapsable: false, testID: `${testID}-surface`, style: { alignSelf: "center", width: fitWidth || "100%", height: height || 320, overflow: "hidden", borderRadius: 12 }, ...responder.panHandlers, children: [
290
+ /* @__PURE__ */ jsx(Image, { source: { uri: screenshot.uri }, style: { width: "100%", height: "100%" }, resizeMode: "stretch", accessibilityIgnoresInvertColors: true }),
291
+ all.map((mark, i) => {
292
+ if (mark.kind === "hide") {
293
+ const box = boxOf(mark.from, mark.to);
294
+ return /* @__PURE__ */ jsx(View, { testID: `${testID}-hide-${i}`, pointerEvents: "none", style: { position: "absolute", ...box, backgroundColor: colors.label } }, i);
295
+ }
296
+ return strokeDots(mark.points).map((p, j) => {
297
+ if (dots++ > MAX_DOTS) return null;
298
+ return /* @__PURE__ */ jsx(
299
+ View,
300
+ {
301
+ pointerEvents: "none",
302
+ style: { position: "absolute", left: p.x - DOT / 2, top: p.y - DOT / 2, width: DOT, height: DOT, borderRadius: DOT / 2, backgroundColor: colors.destructive }
303
+ },
304
+ `${i}-${j}`
305
+ );
306
+ });
307
+ })
308
+ ] }) }),
309
+ failed ? /* @__PURE__ */ jsx(NativeText, { testID: `${testID}-failed`, accessibilityLiveRegion: "polite", style: { color: colors.destructive, fontSize: 13, lineHeight: 18 }, children: copy.failed }) : null,
310
+ /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", gap: 8 }, children: [
311
+ /* @__PURE__ */ jsx(NativeButton, { variant: "ghost", onPress: () => onCancel(marks.length > 0 || draft !== null), testID: `${testID}-cancel`, children: copy.cancel }),
312
+ /* @__PURE__ */ jsx(NativeButton, { variant: "outline", onPress: () => setMarks((m) => m.slice(0, -1)), disabled: !marks.length, testID: `${testID}-undo`, children: copy.undo }),
313
+ /* @__PURE__ */ jsx(View, { style: { flex: 1 } }),
314
+ /* @__PURE__ */ jsx(NativeButton, { onPress: () => void done(), loading: saving, testID: `${testID}-done`, children: copy.done })
315
+ ] })
316
+ ] });
317
+ }
318
+ function FeedbackForm({ defaultType = "bug", onSent, sentAlert = true, testID = "genesis-support-feedback" }) {
319
+ const block = useSupport();
320
+ const { copy } = block;
321
+ const colors = useThemeRoles();
322
+ const queryClient = useQueryClient();
323
+ const [origin] = useState(() => block.peekPending());
324
+ useEffect(() => {
325
+ block.takePending();
326
+ }, [block]);
327
+ const [type, setType] = useState(defaultType);
328
+ const [message, setMessage] = useState("");
329
+ const [screenshot, setScreenshot] = useState(origin?.screenshot ?? null);
330
+ const [include, setInclude] = useState(false);
331
+ const [annotating, setAnnotating] = useState(false);
332
+ const [sending, setSending] = useState(false);
333
+ const [error, setError] = useState(null);
334
+ useEffect(() => setError(null), [message]);
335
+ const send = async () => {
336
+ if (!message.trim()) {
337
+ setError(copy.feedback.messageRequired);
338
+ return;
339
+ }
340
+ setSending(true);
341
+ try {
342
+ const context = await block.collector.collect();
343
+ const route = origin?.route && !origin.route.startsWith(block.paths.inbox) ? origin.route : void 0;
344
+ if (route) context.route = route;
345
+ else delete context.route;
346
+ if (origin?.extra) context.extra = { ...context.extra, ...origin.extra };
347
+ const delivery = await block.client.submit({
348
+ type,
349
+ message: message.trim(),
350
+ context,
351
+ attachments: screenshot && include ? [{ kind: "screenshot", contentType: screenshot.contentType, base64: screenshot.uri, width: screenshot.width, height: screenshot.height }] : []
352
+ });
353
+ void queryClient.invalidateQueries({ queryKey: [SUPPORT_QUERY_ROOT, "reports"] });
354
+ setMessage("");
355
+ setScreenshot(null);
356
+ if (sentAlert) Alert.alert(copy.feedback.sentTitle, delivery.attachmentsDropped ? copy.feedback.sentWithoutScreenshot : copy.feedback.sentBody);
357
+ onSent?.(delivery);
358
+ } catch (e) {
359
+ const err = e instanceof SupportError ? e : null;
360
+ setError(err?.rateLimited ? copy.feedback.rateLimited : err?.code === "42501" ? copy.feedback.signInFirst : copy.feedback.failedBody);
361
+ } finally {
362
+ setSending(false);
363
+ }
364
+ };
365
+ return /* @__PURE__ */ jsxs(View, { testID, style: { gap: 16 }, children: [
366
+ /* @__PURE__ */ jsxs(View, { style: { gap: 8 }, children: [
367
+ /* @__PURE__ */ jsx(NativeLabel, { children: copy.feedback.typeLabel }),
368
+ /* @__PURE__ */ jsx(
369
+ NativeSegmentedControl,
370
+ {
371
+ testID: `${testID}-type`,
372
+ options: FEEDBACK_TYPES.map((t) => ({ value: t, label: copy.feedback.types[t] })),
373
+ value: type,
374
+ onChange: (v) => setType(v)
375
+ }
376
+ )
377
+ ] }),
378
+ /* @__PURE__ */ jsx(
379
+ NativeTextarea,
380
+ {
381
+ testID: `${testID}-message`,
382
+ label: copy.feedback.messageLabel,
383
+ placeholder: copy.feedback.messagePlaceholder,
384
+ value: message,
385
+ onChangeText: setMessage,
386
+ maxLength: 2e4,
387
+ rows: 6,
388
+ error: error ?? void 0
389
+ }
390
+ ),
391
+ screenshot ? /* @__PURE__ */ jsxs(View, { testID: `${testID}-screenshot`, style: { gap: 8 }, children: [
392
+ /* @__PURE__ */ jsx(NativeLabel, { children: copy.feedback.screenshotLabel }),
393
+ /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", gap: 12, alignItems: "flex-start" }, children: [
394
+ /* @__PURE__ */ jsx(
395
+ Image,
396
+ {
397
+ source: { uri: screenshot.uri },
398
+ accessibilityLabel: copy.feedback.screenshotLabel,
399
+ style: { width: 96, height: Math.round(96 * screenshot.height / Math.max(1, screenshot.width)), borderRadius: 8, backgroundColor: colors.fill }
400
+ }
401
+ ),
402
+ /* @__PURE__ */ jsxs(View, { style: { flex: 1, gap: 8 }, children: [
403
+ /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 8 }, children: [
404
+ /* @__PURE__ */ jsx(NativeText, { style: { flex: 1, color: colors.label, fontSize: 15, lineHeight: 20 }, children: copy.feedback.includeScreenshot }),
405
+ /* @__PURE__ */ jsx(
406
+ NativeSwitch,
407
+ {
408
+ testID: `${testID}-include-screenshot`,
409
+ accessibilityLabel: copy.feedback.includeScreenshot,
410
+ checked: include,
411
+ onCheckedChange: setInclude
412
+ }
413
+ )
414
+ ] }),
415
+ /* @__PURE__ */ jsx(NativeText, { style: { color: colors.secondaryLabel, fontSize: 13, lineHeight: 18 }, children: copy.feedback.screenshotHint }),
416
+ block.options.viewShot ? /* @__PURE__ */ jsx(NativeButton, { variant: "outline", size: "sm", onPress: () => setAnnotating(true), testID: `${testID}-annotate`, children: copy.feedback.annotate }) : null,
417
+ /* @__PURE__ */ jsx(
418
+ NativeButton,
419
+ {
420
+ variant: "ghost",
421
+ size: "sm",
422
+ onPress: () => {
423
+ setScreenshot(null);
424
+ setInclude(false);
425
+ },
426
+ testID: `${testID}-remove-screenshot`,
427
+ children: copy.feedback.removeScreenshot
428
+ }
429
+ )
430
+ ] })
431
+ ] })
432
+ ] }) : null,
433
+ annotating && screenshot && block.options.viewShot ? /* @__PURE__ */ jsx(Modal, { visible: true, animationType: "slide", presentationStyle: "fullScreen", onRequestClose: () => {
434
+ setInclude(false);
435
+ setAnnotating(false);
436
+ }, children: /* @__PURE__ */ jsx(SafeAreaView, { style: { flex: 1, backgroundColor: colors.background }, children: /* @__PURE__ */ jsx(View, { style: { flex: 1, padding: 16, justifyContent: "center" }, children: /* @__PURE__ */ jsx(
437
+ ScreenshotAnnotator,
438
+ {
439
+ screenshot,
440
+ viewShot: block.options.viewShot,
441
+ copy: copy.annotate,
442
+ onCancel: (hadMarks) => {
443
+ if (hadMarks) setInclude(false);
444
+ setAnnotating(false);
445
+ },
446
+ onDone: (next, marked) => {
447
+ setScreenshot(next);
448
+ if (marked) setInclude(true);
449
+ setAnnotating(false);
450
+ },
451
+ testID: `${testID}-annotator`
452
+ }
453
+ ) }) }) }) : null,
454
+ /* @__PURE__ */ jsx(NativeButton, { onPress: () => void send(), loading: sending, disabled: sending, testID: `${testID}-send`, children: sending ? copy.feedback.sending : copy.feedback.send })
455
+ ] });
456
+ }
457
+ var key = (...parts) => [SUPPORT_QUERY_ROOT, ...parts];
458
+ function useSupportInbox() {
459
+ const block = useSupport();
460
+ const { copy, paths, client } = block;
461
+ const queryClient = useQueryClient();
462
+ const query = useQuery({ queryKey: key("reports"), queryFn: () => client.myReports() });
463
+ const navigate = block.options.navigate;
464
+ const confirmDelete = (report) => Alert.alert(copy.inbox.deleteConfirmTitle, copy.inbox.deleteConfirmBody, [
465
+ { text: copy.inbox.cancel, style: "cancel" },
466
+ {
467
+ text: copy.inbox.delete,
468
+ style: "destructive",
469
+ onPress: () => {
470
+ void client.deleteReport(report.id).then(() => queryClient.invalidateQueries({ queryKey: key("reports") })).catch(() => Alert.alert(copy.feedback.failedTitle, copy.feedback.failedBody));
471
+ }
472
+ }
473
+ ]);
474
+ const items = (query.data ?? []).map((report) => ({
475
+ id: report.id,
476
+ title: report.title || firstLine(report.message),
477
+ preview: report.title ? firstLine(report.message) : void 0,
478
+ timestamp: report.lastStaffReplyAt ?? report.createdAt,
479
+ unread: report.unread,
480
+ meta: `${copy.feedback.types[report.type]} \xB7 ${copy.status[report.status]}`,
481
+ onPress: () => navigate(paths.thread(report.id)),
482
+ swipeActions: [{ id: "delete", label: copy.inbox.delete, destructive: true, onPress: () => confirmDelete(report) }],
483
+ testID: `genesis-support-report-${report.id}`
484
+ }));
485
+ const header = /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", flexWrap: "wrap", gap: 8, paddingHorizontal: 16, paddingBottom: 8 }, children: [
486
+ /* @__PURE__ */ jsx(NativeButton, { size: "sm", onPress: () => void block.openFeedback({ screenshot: false }), testID: "genesis-support-inbox-new", children: copy.inbox.sendFeedback }),
487
+ block.options.ideas === false ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
488
+ /* @__PURE__ */ jsx(NativeButton, { size: "sm", variant: "outline", onPress: () => navigate(paths.ideas), testID: "genesis-support-inbox-ideas", children: copy.inbox.ideaBoard }),
489
+ /* @__PURE__ */ jsx(NativeButton, { size: "sm", variant: "outline", onPress: () => navigate(paths.shipped), testID: "genesis-support-inbox-shipped", children: copy.inbox.shipped })
490
+ ] })
491
+ ] });
492
+ return {
493
+ testID: "genesis-support-inbox",
494
+ headerTitle: copy.inbox.title,
495
+ items,
496
+ loading: query.isPending,
497
+ error: query.isError,
498
+ refreshing: query.isRefetching,
499
+ onRefresh: async () => {
500
+ await query.refetch();
501
+ },
502
+ sectionTitle: items.length ? copy.inbox.sectionTitle : void 0,
503
+ header,
504
+ emptyTitle: copy.inbox.emptyTitle,
505
+ emptyBody: copy.inbox.emptyBody,
506
+ errorTitle: copy.inbox.errorTitle,
507
+ errorBody: copy.inbox.errorBody
508
+ };
509
+ }
510
+ function firstLine(text) {
511
+ const line = text.split("\n").find((l) => l.trim()) ?? "";
512
+ return line.length > 120 ? `${line.slice(0, 119)}\u2026` : line;
513
+ }
514
+ var CLOSED = /* @__PURE__ */ new Set(["addressed", "wont_fix"]);
515
+ function useSupportThread(reportId, options = {}) {
516
+ const block = useSupport();
517
+ const { copy, client } = block;
518
+ const queryClient = useQueryClient();
519
+ const poll = options.pollMs ?? 3e4;
520
+ const report = useQuery({ queryKey: key("report", reportId), queryFn: () => client.report(reportId), refetchInterval: poll });
521
+ const replies = useQuery({ queryKey: key("replies", reportId), queryFn: () => client.replies(reportId), refetchInterval: poll });
522
+ const attachments = useQuery({ queryKey: key("attachments", reportId), queryFn: () => client.attachments(reportId), staleTime: 50 * 6e4 });
523
+ const [draft, setDraft] = useState("");
524
+ const [failed, setFailed] = useState([]);
525
+ const lastStaff = report.data?.lastStaffReplyAt ?? null;
526
+ useEffect(() => {
527
+ if (!report.data) return;
528
+ void client.markRead(reportId).then(() => queryClient.invalidateQueries({ queryKey: key("reports") })).catch(() => void 0);
529
+ }, [client, reportId, lastStaff, Boolean(report.data), queryClient]);
530
+ const send = useMutation({
531
+ mutationFn: (body) => client.reply(reportId, body),
532
+ onSuccess: () => {
533
+ void queryClient.invalidateQueries({ queryKey: key("replies", reportId) });
534
+ void queryClient.invalidateQueries({ queryKey: key("report", reportId) });
535
+ },
536
+ onError: (_error, body) => setFailed((f) => [...f, { id: `failed-${Date.now()}`, body, at: (/* @__PURE__ */ new Date()).toISOString() }])
537
+ });
538
+ const r = report.data ?? null;
539
+ const messages = useMemo(() => {
540
+ if (!r) return [];
541
+ const first = {
542
+ id: r.id,
543
+ body: r.message,
544
+ mine: true,
545
+ timestamp: r.createdAt,
546
+ attachments: (attachments.data ?? []).filter((a) => a.url).map((a) => ({ id: a.id, uri: a.url, width: a.width ?? void 0, height: a.height ?? void 0, accessibilityLabel: copy.thread.screenshot }))
547
+ };
548
+ const rest = (replies.data ?? []).map((reply) => ({
549
+ id: reply.id,
550
+ body: reply.body,
551
+ mine: reply.mine,
552
+ authorName: reply.fromStaff ? copy.thread.support : void 0,
553
+ timestamp: reply.createdAt
554
+ }));
555
+ const pending = send.isPending && send.variables ? [{ id: "sending", body: send.variables, mine: true, timestamp: (/* @__PURE__ */ new Date()).toISOString(), status: "sending" }] : [];
556
+ const failedMessages = failed.map((f) => ({
557
+ id: f.id,
558
+ body: f.body,
559
+ mine: true,
560
+ timestamp: f.at,
561
+ status: "failed",
562
+ onRetry: () => {
563
+ setFailed((all) => all.filter((x) => x.id !== f.id));
564
+ send.mutate(f.body);
565
+ }
566
+ }));
567
+ return [first, ...rest, ...pending, ...failedMessages];
568
+ }, [r, replies.data, attachments.data, send.isPending, send.variables, failed, copy, send]);
569
+ const closed = r ? CLOSED.has(r.status) : false;
570
+ return {
571
+ testID: "genesis-support-thread",
572
+ headerTitle: r ? r.title || copy.feedback.types[r.type] : copy.thread.title,
573
+ report: r,
574
+ loading: report.isPending,
575
+ notFound: report.isSuccess && r === null,
576
+ labels: { you: copy.thread.you, sending: copy.thread.sending, notSent: copy.thread.notSent, retryHint: copy.thread.retryHint },
577
+ messages,
578
+ readAt: r?.staffReadAt ?? null,
579
+ readLabel: copy.thread.read,
580
+ emptyTitle: copy.thread.emptyTitle,
581
+ emptyBody: copy.thread.emptyBody,
582
+ closedNotice: copy.thread.closed,
583
+ composer: closed ? null : {
584
+ value: draft,
585
+ onChangeText: setDraft,
586
+ placeholder: copy.thread.placeholder,
587
+ sendLabel: copy.thread.send,
588
+ sending: send.isPending,
589
+ maxLength: 1e4,
590
+ onSend: () => {
591
+ const body = draft.trim();
592
+ if (!body || send.isPending) return;
593
+ setDraft("");
594
+ send.mutate(body);
595
+ }
596
+ }
597
+ };
598
+ }
599
+ function VoteButton({ idea, onToggle, testID }) {
600
+ const { copy } = useSupport();
601
+ const count = idea.voteCount === 1 ? copy.ideas.oneVote : fill(copy.ideas.votes, { count: idea.voteCount });
602
+ const open = idea.status === "open" || idea.status === "planned" || idea.status === "in_progress";
603
+ return /* @__PURE__ */ jsx(View, { accessibilityLabel: `${idea.voted ? copy.ideas.voted : copy.ideas.vote}, ${count}`, children: /* @__PURE__ */ jsx(NativeButton, { size: "sm", variant: idea.voted ? "default" : "outline", onPress: onToggle, disabled: !open && !idea.voted, testID, children: `\u25B2 ${idea.voteCount}` }) });
604
+ }
605
+ function useIdeaBoard() {
606
+ const block = useSupport();
607
+ const { copy, client } = block;
608
+ const queryClient = useQueryClient();
609
+ const query = useQuery({ queryKey: key("ideas"), queryFn: () => client.ideas() });
610
+ const [title, setTitle] = useState("");
611
+ const toggle = useMutation({
612
+ mutationFn: (idea) => idea.voted ? client.unvote(idea.id) : client.vote(idea.id),
613
+ onMutate: async (idea) => {
614
+ await queryClient.cancelQueries({ queryKey: key("ideas") });
615
+ const before = queryClient.getQueryData(key("ideas"));
616
+ queryClient.setQueryData(
617
+ key("ideas"),
618
+ (list) => list?.map((i) => i.id === idea.id ? { ...i, voted: !i.voted, voteCount: Math.max(0, i.voteCount + (i.voted ? -1 : 1)) } : i)
619
+ );
620
+ return { before };
621
+ },
622
+ onError: (_e, _idea, context) => {
623
+ if (context?.before) queryClient.setQueryData(key("ideas"), context.before);
624
+ },
625
+ onSettled: () => void queryClient.invalidateQueries({ queryKey: key("ideas") })
626
+ });
627
+ const suggest = useMutation({
628
+ mutationFn: (t) => client.suggestIdea({ title: t }),
629
+ onSuccess: () => {
630
+ setTitle("");
631
+ void queryClient.invalidateQueries({ queryKey: key("ideas") });
632
+ },
633
+ onError: (e) => Alert.alert(copy.feedback.failedTitle, e.code === "GS429" ? copy.feedback.rateLimited : copy.feedback.failedBody)
634
+ });
635
+ const items = (query.data ?? []).map((idea) => ({
636
+ id: idea.id,
637
+ title: idea.title,
638
+ preview: idea.body ?? void 0,
639
+ meta: copy.ideas.statuses[idea.status],
640
+ // Swipe or long press: the same vote, for people who don't see the button.
641
+ swipeActions: [{ id: "vote", label: idea.voted ? copy.ideas.voted : copy.ideas.vote, onPress: () => toggle.mutate(idea) }],
642
+ leading: /* @__PURE__ */ jsx(View, {}),
643
+ trailing: /* @__PURE__ */ jsx(VoteButton, { idea, onToggle: () => toggle.mutate(idea), testID: `genesis-support-vote-${idea.id}` }),
644
+ testID: `genesis-support-idea-${idea.id}`
645
+ }));
646
+ const header = /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", gap: 8, alignItems: "flex-end", paddingHorizontal: 16, paddingBottom: 12 }, children: [
647
+ /* @__PURE__ */ jsx(View, { style: { flex: 1 }, children: /* @__PURE__ */ jsx(
648
+ NativeInput,
649
+ {
650
+ testID: "genesis-support-idea-title",
651
+ label: copy.ideas.titleLabel,
652
+ placeholder: copy.ideas.titlePlaceholder,
653
+ value: title,
654
+ onChangeText: setTitle,
655
+ maxLength: 140
656
+ }
657
+ ) }),
658
+ /* @__PURE__ */ jsx(
659
+ NativeButton,
660
+ {
661
+ onPress: () => title.trim().length >= 3 && suggest.mutate(title.trim()),
662
+ disabled: title.trim().length < 3,
663
+ loading: suggest.isPending,
664
+ testID: "genesis-support-idea-submit",
665
+ children: copy.ideas.submit
666
+ }
667
+ )
668
+ ] });
669
+ return {
670
+ testID: "genesis-support-ideas",
671
+ headerTitle: copy.ideas.title,
672
+ items,
673
+ refreshing: query.isRefetching,
674
+ onRefresh: async () => {
675
+ await query.refetch();
676
+ },
677
+ header,
678
+ loading: query.isPending,
679
+ error: query.isError,
680
+ errorTitle: copy.inbox.errorTitle,
681
+ errorBody: copy.inbox.errorBody,
682
+ emptyTitle: copy.ideas.emptyTitle,
683
+ emptyBody: copy.ideas.emptyBody
684
+ };
685
+ }
686
+ function useShippedIdeas() {
687
+ const { copy, client } = useSupport();
688
+ const query = useQuery({ queryKey: key("shipped"), queryFn: () => client.shippedForMe() });
689
+ const items = (query.data ?? []).map((idea) => ({
690
+ id: idea.id,
691
+ title: idea.title,
692
+ preview: idea.body ?? void 0,
693
+ timestamp: idea.shippedAt ?? void 0,
694
+ meta: idea.featureId ? fill(copy.shipped.shippedAs, { feature: idea.featureId }) : copy.ideas.statuses.shipped,
695
+ leading: /* @__PURE__ */ jsx(View, {}),
696
+ testID: `genesis-support-shipped-${idea.id}`
697
+ }));
698
+ return {
699
+ testID: "genesis-support-shipped",
700
+ headerTitle: copy.shipped.title,
701
+ items,
702
+ refreshing: query.isRefetching,
703
+ onRefresh: async () => {
704
+ await query.refetch();
705
+ },
706
+ loading: query.isPending,
707
+ error: query.isError,
708
+ errorTitle: copy.inbox.errorTitle,
709
+ errorBody: copy.inbox.errorBody,
710
+ emptyTitle: copy.shipped.emptyTitle,
711
+ emptyBody: copy.shipped.emptyBody
712
+ };
713
+ }
714
+ function SendFeedbackButton({ testID = "genesis-support-send-feedback-button", screenshot = true }) {
715
+ const block = useOptionalSupport();
716
+ if (!block) return null;
717
+ return /* @__PURE__ */ jsx(NativeButton, { variant: "outline", onPress: () => void block.openFeedback({ screenshot }), testID, children: block.copy.settings.sendFeedback });
718
+ }
719
+
720
+ export { FeedbackForm, SUPPORT_QUERY_ROOT, ScreenshotAnnotator, SendFeedbackButton, SupportProvider, VoteButton, boxOf, createSupport, listenForShake, strokeDots, useIdeaBoard, useOptionalSupport, usePendingFeedback, useShippedIdeas, useSupport, useSupportInbox, useSupportThread, useUnreadReplies };
721
+ //# sourceMappingURL=native.js.map
722
+ //# sourceMappingURL=native.js.map