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