@marktiderman/genesis-native 0.12.0 → 0.13.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.
@@ -10,6 +10,8 @@
10
10
  * app's flags;
11
11
  * - the recent breadcrumbs and errors (the observability block's, scrubbed);
12
12
  * - the server's base URL;
13
+ * - the health checks (`checks`: genesis-support's `healthChecks` registry), run when the sheet
14
+ * opens and again on "Run checks", each in words (`checkLabels`) with its own "Try again";
13
15
  * - "Copy debug info", "Crash test", "Clear cache" and "Sign out";
14
16
  * - the `devtoolsFeedback` slot, which the support block fills with
15
17
  * "Send feedback", and the `devtoolsDiagnostics` slot beside "Copy debug
@@ -23,11 +25,21 @@
23
25
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ComponentType, type ReactNode } from "react";
24
26
  import type { ResolvedSettings } from "@marktiderman/genesis-config/settings";
25
27
  import { devtoolsSettingValues } from "./settings";
26
- import { Alert, Modal, ScrollView, Share, View, type GestureResponderEvent } from "react-native";
28
+ import { Alert, Share, View, type GestureResponderEvent } from "react-native";
27
29
  import { useQueryClient } from "@tanstack/react-query";
28
30
  import { renderSlot } from "@marktiderman/genesis-core/slots";
29
- import { NativeButton, NativeInput, NativeText } from "@marktiderman/genesis-ui-native/components";
30
- import { useThemeRoles } from "@marktiderman/genesis-ui-native/hooks";
31
+ import {
32
+ Box,
33
+ Inline,
34
+ NativeButton,
35
+ NativeInput,
36
+ NativeSectionListHeader,
37
+ NativeSettingsRow,
38
+ NativeSheet,
39
+ NativeSheetScrollView,
40
+ NativeText,
41
+ Stack,
42
+ } from "@marktiderman/genesis-ui-native/components";
31
43
  import { defineBlock } from "@marktiderman/genesis-config/blocks";
32
44
  import { useSession } from "../auth";
33
45
  import { useBlocks, type NativeBlock, type NativeBlockRootProps } from "../blocks";
@@ -48,6 +60,42 @@ export interface DevSettingsLike {
48
60
  addMenuItem(title: string, handler: () => void): void;
49
61
  }
50
62
 
63
+ /** One health check's result, as genesis-support's `healthChecks` gives it. */
64
+ export interface DevtoolsCheckResult {
65
+ name: string;
66
+ status: "ok" | "warn" | "fail";
67
+ message: string | null;
68
+ ms: number;
69
+ }
70
+
71
+ /** A health-check registry (genesis-support's `healthChecks`): the overlay runs it and shows the results. */
72
+ export interface DevtoolsChecksLike {
73
+ list(): readonly unknown[];
74
+ run(): Promise<readonly DevtoolsCheckResult[]>;
75
+ latest(): readonly DevtoolsCheckResult[];
76
+ /** Run one check again (a check's "Try again"); null when none has that name. Without it, no check has "Try again". */
77
+ runCheck?(name: string): Promise<DevtoolsCheckResult | null>;
78
+ }
79
+
80
+ /** The health checks' words: each status, and the actions. */
81
+ export interface DevtoolsCheckLabels {
82
+ ok: string;
83
+ warn: string;
84
+ fail: string;
85
+ /** Run one check again. */
86
+ retry: string;
87
+ /** Run every check. */
88
+ runAll: string;
89
+ }
90
+
91
+ export const DEFAULT_DEVTOOLS_CHECK_LABELS: DevtoolsCheckLabels = {
92
+ ok: "Working",
93
+ warn: "Needs a look",
94
+ fail: "Not working",
95
+ retry: "Try again",
96
+ runAll: "Run checks",
97
+ };
98
+
51
99
  export interface DevtoolsOptions {
52
100
  /**
53
101
  * Must be explicitly true: `__DEV__` or a fact of the binary (a `.dev` or
@@ -64,6 +112,10 @@ export interface DevtoolsOptions {
64
112
  baseUrl?: string;
65
113
  /** The app's switches and flags, shown by name and value. */
66
114
  flags?: Readonly<Record<string, unknown>>;
115
+ /** The health checks to run and show (genesis-support's `healthChecks`). */
116
+ checks?: DevtoolsChecksLike;
117
+ /** The health checks' words, in English by default. */
118
+ checkLabels?: Partial<DevtoolsCheckLabels>;
67
119
  /** `Accelerometer` from expo-sensors: shake to open. Without it, the hold and the dev menu still work. */
68
120
  accelerometer?: AccelerometerLike;
69
121
  /** `DevSettings` from react-native: "Open devtools" in the dev menu (development builds). */
@@ -306,34 +358,82 @@ interface SheetProps {
306
358
  onCrash: () => void;
307
359
  }
308
360
 
309
- // Layout by `style`, not `className`: this package is compiled before the app's NativeWind
310
- // transform runs, so a class on React Native's own View would do nothing.
361
+ /** A label and its value, as a settings row: the value wraps whole and can be selected (an id, a URL). */
311
362
  function Row({ label, value, testID }: { label: string; value: string; testID?: string }) {
312
- return (
313
- <View style={{ flexDirection: "row", justifyContent: "space-between", gap: 12, paddingVertical: 4 }} testID={testID}>
314
- <NativeText preset="label">{label}</NativeText>
315
- <NativeText preset="body-sm" className="text-right text-muted-foreground" style={{ flex: 1 }} selectable>
316
- {value}
317
- </NativeText>
318
- </View>
319
- );
363
+ return <NativeSettingsRow label={label} description={value} descriptionLines={null} selectable {...(testID ? { testID } : {})} />;
320
364
  }
321
365
 
322
366
  function Section({ title, children }: { title: string; children: ReactNode }) {
323
- const roles = useThemeRoles();
324
367
  return (
325
- <View style={{ gap: 4, borderTopWidth: 1, borderTopColor: roles.separator, paddingTop: 12 }}>
326
- <NativeText preset="label" accessibilityRole="header">
327
- {title}
328
- </NativeText>
368
+ <Stack gap="xs">
369
+ <NativeSectionListHeader title={title} />
329
370
  {children}
330
- </View>
371
+ </Stack>
372
+ );
373
+ }
374
+
375
+ function HealthChecksSection({ checks, labels }: { checks: DevtoolsChecksLike; labels: DevtoolsCheckLabels }) {
376
+ const [results, setResults] = useState<readonly DevtoolsCheckResult[]>(() => checks.latest());
377
+ const [running, setRunning] = useState(false);
378
+ const [retrying, setRetrying] = useState<string | null>(null);
379
+ const run = () => {
380
+ setRunning(true);
381
+ checks
382
+ .run()
383
+ .then(setResults, () => undefined)
384
+ .finally(() => setRunning(false));
385
+ };
386
+ const runCheck = checks.runCheck?.bind(checks);
387
+ const retry = (again: NonNullable<typeof runCheck>, name: string) => {
388
+ setRetrying(name);
389
+ again(name)
390
+ .then((next) => {
391
+ if (next) setResults((all) => all.map((r) => (r.name === name ? next : r)));
392
+ }, () => undefined)
393
+ .finally(() => setRetrying(null));
394
+ };
395
+ // Run when the sheet opens.
396
+ useEffect(run, [checks]);
397
+ const failed = results.filter((r) => r.status === "fail").length;
398
+ const warned = results.filter((r) => r.status === "warn").length;
399
+ const verdict = running ? "running" : !results.length ? "not run" : failed ? `${failed} failed` : warned ? `${warned} warnings` : "all good";
400
+ const word: Record<DevtoolsCheckResult["status"], string> = { ok: labels.ok, warn: labels.warn, fail: labels.fail };
401
+ return (
402
+ <Section title={`Health checks (${verdict})`}>
403
+ {checks.list().length === 0 ? <NativeText preset="body-sm">None registered</NativeText> : null}
404
+ {results.map((r) => (
405
+ <NativeSettingsRow
406
+ key={r.name}
407
+ label={r.name}
408
+ description={`${word[r.status]}${r.message ? ` · ${r.message}` : ""} · ${r.ms} ms`}
409
+ descriptionLines={null}
410
+ selectable
411
+ testID={`genesis-devtools-check-${r.name}`}
412
+ >
413
+ {runCheck ? (
414
+ <NativeButton
415
+ size="sm"
416
+ variant="ghost"
417
+ onPress={() => retry(runCheck, r.name)}
418
+ disabled={running || retrying !== null}
419
+ loading={retrying === r.name}
420
+ accessibilityLabel={`${labels.retry}: ${r.name}`}
421
+ testID={`genesis-devtools-check-${r.name}-retry`}
422
+ >
423
+ {labels.retry}
424
+ </NativeButton>
425
+ ) : null}
426
+ </NativeSettingsRow>
427
+ ))}
428
+ <NativeButton size="sm" variant="outline" onPress={run} disabled={running} testID="genesis-devtools-run-checks">
429
+ {labels.runAll}
430
+ </NativeButton>
431
+ </Section>
331
432
  );
332
433
  }
333
434
 
334
435
  function DevtoolsSheet({ visible, onDismissed, block, Feedback, feedbackProps, Diagnostics, diagnosticsProps, onCrash }: SheetProps) {
335
436
  const { options } = block;
336
- const roles = useThemeRoles();
337
437
  const { userId } = useSession();
338
438
  const blocks = useBlocks();
339
439
  const recent = useRecentActivity(options.observability ?? null);
@@ -385,133 +485,133 @@ function DevtoolsSheet({ visible, onDismissed, block, Feedback, feedbackProps, D
385
485
 
386
486
  const flags = Object.entries(options.flags ?? {});
387
487
  return (
388
- // React Native's own modal, as a page sheet on iOS: it needs no provider above it (a bottom-sheet
389
- // library's modal does), so the overlay opens whatever the app has mounted.
390
- <Modal
391
- visible={visible}
392
- animationType="slide"
393
- presentationStyle="pageSheet"
394
- onRequestClose={() => void close()}
395
- onDismiss={onDismissed}
396
- testID="genesis-devtools"
397
- >
398
- <ScrollView style={{ flex: 1, backgroundColor: roles.background }} contentContainerStyle={{ gap: 12, padding: 16, paddingBottom: 48 }}>
399
- <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
400
- <NativeText preset="h3" accessibilityRole="header">
401
- Devtools
402
- </NativeText>
403
- <NativeButton variant="ghost" size="sm" onPress={() => void close()} testID="genesis-devtools-close">
404
- Close
405
- </NativeButton>
406
- </View>
407
- {status ? (
408
- <NativeText preset="body-sm" testID="genesis-devtools-status">
409
- {status}
410
- </NativeText>
411
- ) : null}
412
-
413
- <Section title="Build">
414
- <NativeText preset="body-sm" selectable testID="genesis-devtools-signature">
415
- {signature?.text ?? "Version unknown (no updates block)"}
416
- </NativeText>
417
- </Section>
418
-
419
- {channels ? (
420
- <Section title="Update channel">
421
- <Row label="Channel" value={signature?.requestedChannel ?? signature?.channel ?? "none"} testID="genesis-devtools-channel" />
422
- {channels.enabled ? (
423
- <>
424
- <NativeInput
425
- value={channel}
426
- onChangeText={setChannel}
427
- placeholder="pr-42"
428
- autoCapitalize="none"
429
- autoCorrect={false}
430
- accessibilityLabel="Channel to switch to"
431
- testID="genesis-devtools-channel-input"
432
- />
433
- <NativeButton size="sm" onPress={switchChannel} disabled={!channel.trim()} testID="genesis-devtools-channel-switch">
434
- Switch and reload
435
- </NativeButton>
436
- </>
437
- ) : (
438
- <NativeText preset="body-sm" className="text-muted-foreground">
439
- Switching is off in this build.
440
- </NativeText>
441
- )}
442
- <NativeButton size="sm" variant="ghost" onPress={resetChannel} testID="genesis-devtools-channel-reset">
443
- Back to the build's channel
444
- </NativeButton>
445
- </Section>
446
- ) : null}
447
-
448
- <Section title="Session">
449
- <Row label="User id" value={userId ?? "signed out"} testID="genesis-devtools-user" />
450
- <Row label="Server" value={options.baseUrl ? scrubUrl(options.baseUrl) : "unknown"} testID="genesis-devtools-server" />
451
- </Section>
452
-
453
- <Section title="Blocks and flags">
454
- <Row label="Blocks" value={blocks.ids.size > 0 ? [...blocks.ids].join(", ") : "none"} testID="genesis-devtools-blocks" />
455
- {flags.map(([name, value]) => (
456
- <Row key={name} label={name} value={typeof value === "string" ? scrubString(value) : String(value)} testID={`genesis-devtools-flag-${name}`} />
457
- ))}
458
- </Section>
459
-
460
- <Section title={`Errors (${recent.errors.length})`}>
461
- {recent.errors.length === 0 ? <NativeText preset="body-sm">None</NativeText> : null}
462
- {recent.errors
463
- .slice(-10)
464
- .reverse()
465
- .map((e) => (
466
- <NativeText key={`${e.at}-${e.message}`} preset="body-sm" testID="genesis-devtools-error">
467
- {`${e.fatal ? "fatal " : ""}${e.source} · ${e.name}: ${e.message}`}
488
+ // The sheet primitive: a page sheet on iOS (React Native's modal, needing no provider above it),
489
+ // or the bottom-sheet library's under NativeSheetProvider; it brings the escape gesture, reduced
490
+ // motion and the safe area.
491
+ <NativeSheet open={visible} onOpenChange={(open) => (open ? undefined : void close())} onDismissed={onDismissed} testID="genesis-devtools">
492
+ <NativeSheetScrollView>
493
+ <Box p="lg" pb="3xl">
494
+ <Stack gap="md">
495
+ <Inline justify="between">
496
+ <NativeText preset="h3" accessibilityRole="header">
497
+ Devtools
468
498
  </NativeText>
469
- ))}
470
- </Section>
471
-
472
- <Section title={`Breadcrumbs (${recent.breadcrumbs.length})`}>
473
- {recent.breadcrumbs.length === 0 ? <NativeText preset="body-sm">None</NativeText> : null}
474
- {recent.breadcrumbs
475
- .slice(-15)
476
- .reverse()
477
- .map((c, i) => (
478
- <NativeText key={`${c.timestamp ?? 0}-${i}`} preset="body-sm" testID="genesis-devtools-breadcrumb">
479
- {`${c.category} · ${c.message ?? ""}`}
499
+ <NativeButton variant="ghost" size="sm" onPress={() => void close()} testID="genesis-devtools-close">
500
+ Close
501
+ </NativeButton>
502
+ </Inline>
503
+ {status ? (
504
+ <NativeText preset="body-sm" testID="genesis-devtools-status">
505
+ {status}
480
506
  </NativeText>
481
- ))}
482
- </Section>
507
+ ) : null}
483
508
 
484
- <Section title="Actions">
485
- <View style={{ gap: 8 }}>
486
- <NativeButton size="sm" variant="outline" onPress={copy} testID="genesis-devtools-copy">
487
- Copy debug info
488
- </NativeButton>
489
- {renderSlot(NoDiagnostics, Diagnostics, { debugInfo: info(), close, copy: copyText }, diagnosticsProps)}
490
- {renderSlot(NoFeedback, Feedback, { debugInfo: info(), close }, feedbackProps)}
491
- <NativeButton size="sm" variant="outline" onPress={clearCache} testID="genesis-devtools-clear-cache">
492
- Clear cache
493
- </NativeButton>
494
- <NativeButton
495
- size="sm"
496
- variant="outline"
497
- onPress={() => confirm("Crash test", "This throws a render error: the fatal screen shows and the error is reported.", "Crash", onCrash)}
498
- testID="genesis-devtools-crash"
499
- >
500
- Crash test
501
- </NativeButton>
502
- {options.signOut ? (
503
- <NativeButton
504
- size="sm"
505
- variant="destructive"
506
- onPress={() => confirm("Sign out", "Sign out of this device?", "Sign out", () => run("Sign out", options.signOut as () => unknown))}
507
- testID="genesis-devtools-sign-out"
508
- >
509
- Sign out
510
- </NativeButton>
509
+ <Section title="Build">
510
+ <NativeText preset="body-sm" selectable testID="genesis-devtools-signature">
511
+ {signature?.text ?? "Version unknown (no updates block)"}
512
+ </NativeText>
513
+ </Section>
514
+
515
+ {channels ? (
516
+ <Section title="Update channel">
517
+ <Row label="Channel" value={signature?.requestedChannel ?? signature?.channel ?? "none"} testID="genesis-devtools-channel" />
518
+ {channels.enabled ? (
519
+ <>
520
+ <NativeInput
521
+ value={channel}
522
+ onChangeText={setChannel}
523
+ placeholder="pr-42"
524
+ autoCapitalize="none"
525
+ autoCorrect={false}
526
+ accessibilityLabel="Channel to switch to"
527
+ testID="genesis-devtools-channel-input"
528
+ />
529
+ <NativeButton size="sm" onPress={switchChannel} disabled={!channel.trim()} testID="genesis-devtools-channel-switch">
530
+ Switch and reload
531
+ </NativeButton>
532
+ </>
533
+ ) : (
534
+ <NativeText preset="body-sm" className="text-muted-foreground">
535
+ Switching is off in this build.
536
+ </NativeText>
537
+ )}
538
+ <NativeButton size="sm" variant="ghost" onPress={resetChannel} testID="genesis-devtools-channel-reset">
539
+ Back to the build's channel
540
+ </NativeButton>
541
+ </Section>
511
542
  ) : null}
512
- </View>
513
- </Section>
514
- </ScrollView>
515
- </Modal>
543
+
544
+ <Section title="Session">
545
+ <Row label="User id" value={userId ?? "signed out"} testID="genesis-devtools-user" />
546
+ <Row label="Server" value={options.baseUrl ? scrubUrl(options.baseUrl) : "unknown"} testID="genesis-devtools-server" />
547
+ </Section>
548
+
549
+ {options.checks ? <HealthChecksSection checks={options.checks} labels={{ ...DEFAULT_DEVTOOLS_CHECK_LABELS, ...options.checkLabels }} /> : null}
550
+
551
+ <Section title="Blocks and flags">
552
+ <Row label="Blocks" value={blocks.ids.size > 0 ? [...blocks.ids].join(", ") : "none"} testID="genesis-devtools-blocks" />
553
+ {flags.map(([name, value]) => (
554
+ <Row key={name} label={name} value={typeof value === "string" ? scrubString(value) : String(value)} testID={`genesis-devtools-flag-${name}`} />
555
+ ))}
556
+ </Section>
557
+
558
+ <Section title={`Errors (${recent.errors.length})`}>
559
+ {recent.errors.length === 0 ? <NativeText preset="body-sm">None</NativeText> : null}
560
+ {recent.errors
561
+ .slice(-10)
562
+ .reverse()
563
+ .map((e) => (
564
+ <NativeText key={`${e.at}-${e.message}`} preset="body-sm" testID="genesis-devtools-error">
565
+ {`${e.fatal ? "fatal " : ""}${e.source} · ${e.name}: ${e.message}`}
566
+ </NativeText>
567
+ ))}
568
+ </Section>
569
+
570
+ <Section title={`Breadcrumbs (${recent.breadcrumbs.length})`}>
571
+ {recent.breadcrumbs.length === 0 ? <NativeText preset="body-sm">None</NativeText> : null}
572
+ {recent.breadcrumbs
573
+ .slice(-15)
574
+ .reverse()
575
+ .map((c, i) => (
576
+ <NativeText key={`${c.timestamp ?? 0}-${i}`} preset="body-sm" testID="genesis-devtools-breadcrumb">
577
+ {`${c.category} · ${c.message ?? ""}`}
578
+ </NativeText>
579
+ ))}
580
+ </Section>
581
+
582
+ <Section title="Actions">
583
+ <Stack gap="sm">
584
+ <NativeButton size="sm" variant="outline" onPress={copy} testID="genesis-devtools-copy">
585
+ Copy debug info
586
+ </NativeButton>
587
+ {renderSlot(NoDiagnostics, Diagnostics, { debugInfo: info(), close, copy: copyText }, diagnosticsProps)}
588
+ {renderSlot(NoFeedback, Feedback, { debugInfo: info(), close }, feedbackProps)}
589
+ <NativeButton size="sm" variant="outline" onPress={clearCache} testID="genesis-devtools-clear-cache">
590
+ Clear cache
591
+ </NativeButton>
592
+ <NativeButton
593
+ size="sm"
594
+ variant="outline"
595
+ onPress={() => confirm("Crash test", "This throws a render error: the fatal screen shows and the error is reported.", "Crash", onCrash)}
596
+ testID="genesis-devtools-crash"
597
+ >
598
+ Crash test
599
+ </NativeButton>
600
+ {options.signOut ? (
601
+ <NativeButton
602
+ size="sm"
603
+ variant="destructive"
604
+ onPress={() => confirm("Sign out", "Sign out of this device?", "Sign out", () => run("Sign out", options.signOut as () => unknown))}
605
+ testID="genesis-devtools-sign-out"
606
+ >
607
+ Sign out
608
+ </NativeButton>
609
+ ) : null}
610
+ </Stack>
611
+ </Section>
612
+ </Stack>
613
+ </Box>
614
+ </NativeSheetScrollView>
615
+ </NativeSheet>
516
616
  );
517
617
  }
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * @stability Beta
18
18
  */
19
- export { createDevtools, DEVTOOLS_BLOCK_ID, type DevSettingsLike, type DevtoolsBlock, type DevtoolsOptions, type DevtoolsState } from "./block";
19
+ export { createDevtools, DEFAULT_DEVTOOLS_CHECK_LABELS, DEVTOOLS_BLOCK_ID, type DevSettingsLike, type DevtoolsCheckLabels, type DevtoolsCheckResult, type DevtoolsChecksLike, type DevtoolsBlock, type DevtoolsOptions, type DevtoolsState } from "./block";
20
20
  export { createHoldDetector, createShakeDetector, type AccelerometerLike, type HoldDetector, type HoldDetectorOptions, type ShakeDetector, type ShakeDetectorOptions } from "./gestures";
21
21
  export { buildDebugInfo, type DebugInfoInput } from "./info";
22
22
  export type { DevtoolsDiagnosticsProps, DevtoolsFeedbackProps, DevtoolsSlots } from "./slots";
package/src/errors.tsx CHANGED
@@ -6,10 +6,11 @@
6
6
  * tree with fresh state.
7
7
  */
8
8
  import { Component, type ComponentType, type ErrorInfo, type ReactNode } from "react";
9
- import { Pressable, Text, View } from "react-native";
10
- import { NativeButton, NativeEmptyState } from "@marktiderman/genesis-ui-native/components";
9
+ import { Linking, Pressable, Text, View } from "react-native";
10
+ import { Inline, NativeButton, NativeEmptyState } from "@marktiderman/genesis-ui-native/components";
11
11
  import { classifyError, reportError } from "@marktiderman/genesis-core/errors";
12
12
  import { toError } from "./boot";
13
+ import { useOptionalBlocks, type NativeBlock } from "./blocks";
13
14
 
14
15
  declare const __DEV__: boolean | undefined;
15
16
 
@@ -45,8 +46,94 @@ export interface FatalScreenViewProps {
45
46
  * could not start, or when the `fatal` slot threw.
46
47
  */
47
48
  kind?: FatalScreenKind;
49
+ /**
50
+ * Where people can write when the app can't help (support's `contactEmail` / `contactUrl`
51
+ * settings: `support.contact()`): a "Contact support" button under "Try again". Left out, none.
52
+ */
53
+ contact?: FatalScreenContact | null;
54
+ /**
55
+ * "Report this": opens the support block's feedback form with the error attached. Left out, the
56
+ * block's (when the support block is on and feedback with it); `null` for none.
57
+ */
58
+ onReport?: ((error: Error, where: { kind: "app" | "screen" }) => void) | null;
59
+ /** The screen's words, in English by default. */
60
+ labels?: Partial<FatalScreenLabels>;
61
+ }
62
+
63
+ /** The fatal and screen error screens' words. */
64
+ export interface FatalScreenLabels {
65
+ /** The app's fatal screen. */
66
+ title: string;
67
+ body: string;
68
+ /** One screen failed. */
69
+ screenTitle: string;
70
+ screenBody: string;
71
+ /** The plain screen's line when the error has nothing safe to say. */
72
+ plainBody: string;
73
+ retry: string;
74
+ contact: string;
75
+ report: string;
76
+ }
77
+
78
+ export const DEFAULT_FATAL_SCREEN_LABELS: FatalScreenLabels = {
79
+ title: "Something went wrong",
80
+ body: "The app hit a problem. Try again, and if it keeps happening, close and reopen the app.",
81
+ screenTitle: "This screen hit a problem",
82
+ screenBody: "The rest of the app still works. Try again, or go back.",
83
+ plainBody: "Try again, and if it keeps happening, close and reopen the app.",
84
+ retry: "Try again",
85
+ contact: "Contact support",
86
+ report: "Report this",
87
+ };
88
+
89
+ /** A support contact for the fatal screens: an email address, a support page, or both. */
90
+ export interface FatalScreenContact {
91
+ email?: string | null;
92
+ url?: string | null;
93
+ }
94
+
95
+ /** An https page with a host (`https://acme.test/help`), else null. */
96
+ function httpsPage(text: string | null | undefined): string | null {
97
+ const t = text?.trim();
98
+ if (!t || t.length > 2048 || !/^https:\/\//i.test(t)) return null;
99
+ try {
100
+ const u = new URL(t);
101
+ return u.protocol === "https:" && u.hostname ? t : null;
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ /** One address, checked in one pass (no backtracking): one "@", no spaces or brackets, a dot in the domain, not at its ends. */
108
+ function looksLikeEmail(text: string): boolean {
109
+ if (text.length > 254) return false;
110
+ let at = -1;
111
+ for (let i = 0; i < text.length; i++) {
112
+ const c = text.charCodeAt(i);
113
+ if (c <= 0x20 || c === 0x3c || c === 0x3e || c === 0x7f) return false;
114
+ if (c === 0x40) {
115
+ if (at !== -1) return false;
116
+ at = i;
117
+ }
118
+ }
119
+ const dot = text.lastIndexOf(".");
120
+ return at > 0 && dot > at + 1 && dot < text.length - 1;
48
121
  }
49
122
 
123
+ /** The link a contact opens: the support page, else a mailto. Null with neither (or one that isn't safe). */
124
+ export function contactHref(contact: FatalScreenContact | null | undefined): string | null {
125
+ const url = httpsPage(contact?.url);
126
+ if (url) return url;
127
+ const email = contact?.email?.trim();
128
+ // RFC 6068: "?", "#", "%", "&" and "/" in the mailbox are encoded, so they don't start a query.
129
+ if (email && looksLikeEmail(email)) return `mailto:${email.replace(/[%?#&/]/g, (c) => encodeURIComponent(c))}`;
130
+ return null;
131
+ }
132
+
133
+ const openContact = (href: string) => () => {
134
+ void Linking.openURL(href).catch((e: unknown) => reportError(e, "native:contact"));
135
+ };
136
+
50
137
  const runRetry = (retry: FatalScreenViewProps["retry"], source: string) => () => {
51
138
  void Promise.resolve(retry()).catch((e: unknown) => reportError(e, source));
52
139
  };
@@ -55,44 +142,88 @@ const runRetry = (retry: FatalScreenViewProps["retry"], source: string) => () =>
55
142
  * The fatal screen: what went wrong and "Try again", for the whole app, one screen, or (with
56
143
  * `kind="plain"`) the last resort that needs nothing above it.
57
144
  */
58
- export function FatalScreen({ error, retry, kind = "app" }: FatalScreenViewProps) {
145
+ export function FatalScreen({ error, retry, kind = "app", contact, onReport, labels: given }: FatalScreenViewProps) {
146
+ const blocks = useOptionalBlocks();
147
+ const labels = { ...DEFAULT_FATAL_SCREEN_LABELS, ...given };
148
+ const href = contactHref(contact);
59
149
  if (kind === "plain") {
60
150
  return (
61
151
  <View testID="genesis-fatal-plain" style={{ flex: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 12 }}>
62
152
  <Text accessibilityRole="header" style={{ fontSize: 17, fontWeight: "600" }}>
63
- Something went wrong
153
+ {labels.title}
64
154
  </Text>
65
- <Text style={{ textAlign: "center" }}>{errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app."}</Text>
155
+ <Text style={{ textAlign: "center" }}>{errorDetails(error) ?? labels.plainBody}</Text>
66
156
  <Pressable accessibilityRole="button" onPress={() => void retry()} testID="genesis-fatal-plain-retry" style={{ padding: 12 }}>
67
- <Text style={{ fontSize: 17 }}>Try again</Text>
157
+ <Text style={{ fontSize: 17 }}>{labels.retry}</Text>
68
158
  </Pressable>
159
+ {href ? (
160
+ <Pressable accessibilityRole="link" onPress={openContact(href)} testID="genesis-fatal-plain-contact" style={{ padding: 12 }}>
161
+ <Text style={{ fontSize: 15 }}>{labels.contact}</Text>
162
+ </Pressable>
163
+ ) : null}
69
164
  </View>
70
165
  );
71
166
  }
72
167
  const screen = kind === "screen";
168
+ const report = onReport === undefined ? blockReporter(blocks?.blocks) : onReport;
169
+ const onReportPress = report
170
+ ? () => {
171
+ // The app's screens are gone behind the fatal screen: bring them back, then open the form.
172
+ if (!screen) void Promise.resolve(retry()).catch((e: unknown) => reportError(e, "native:fatal-retry"));
173
+ try {
174
+ report(error, { kind: screen ? "screen" : "app" });
175
+ } catch (e) {
176
+ reportError(e, "native:report-problem");
177
+ }
178
+ }
179
+ : null;
180
+ const secondary =
181
+ href || onReportPress ? (
182
+ <Inline gap="sm" wrap justify="center">
183
+ {onReportPress ? (
184
+ <NativeButton variant="outline" onPress={onReportPress} testID={screen ? "genesis-screen-error-report" : "genesis-fatal-report"}>
185
+ {labels.report}
186
+ </NativeButton>
187
+ ) : null}
188
+ {href ? (
189
+ <NativeButton variant="outline" onPress={openContact(href)} testID={screen ? "genesis-screen-error-contact" : "genesis-fatal-contact"}>
190
+ {labels.contact}
191
+ </NativeButton>
192
+ ) : null}
193
+ </Inline>
194
+ ) : null;
73
195
  return (
74
196
  <NativeEmptyState
75
197
  variant="error"
76
- title={screen ? "This screen hit a problem" : "Something went wrong"}
77
- body={
78
- screen
79
- ? "The rest of the app still works. Try again, or go back."
80
- : "The app hit a problem. Try again, and if it keeps happening, close and reopen the app."
81
- }
198
+ title={screen ? labels.screenTitle : labels.title}
199
+ body={screen ? labels.screenBody : labels.body}
82
200
  details={errorDetails(error)}
83
201
  primaryAction={
84
202
  <NativeButton
85
203
  onPress={screen ? runRetry(retry, "native:screen-retry") : () => void retry()}
86
204
  testID={screen ? "genesis-screen-error-retry" : "genesis-fatal-retry"}
87
205
  >
88
- Try again
206
+ {labels.retry}
89
207
  </NativeButton>
90
208
  }
209
+ {...(secondary ? { secondaryAction: secondary } : {})}
91
210
  testID={screen ? "genesis-screen-error" : "genesis-fatal"}
92
211
  />
93
212
  );
94
213
  }
95
214
 
215
+ /**
216
+ * The first block that takes a problem report (the support block's "Report this"), read now: the
217
+ * function itself is kept, so a setting that changes before the press can't leave it undefined.
218
+ */
219
+ function blockReporter(blocks: readonly NativeBlock[] | undefined): FatalScreenViewProps["onReport"] {
220
+ for (const block of blocks ?? []) {
221
+ const report = block.reportProblem;
222
+ if (report) return report;
223
+ }
224
+ return null;
225
+ }
226
+
96
227
  /**
97
228
  * The last-resort fatal screen.
98
229
  *