All files / src/components ReportDialog.tsx

76.72% Statements 89/116
69.23% Branches 9/13
30% Functions 3/10
76.72% Lines 89/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 2091x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x                       1x 1x 1x   1x         1x         1x               1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x   1x 1x 1x       1x                   1x             1x 1x 1x 1x 1x 1x 1x     1x 1x 1x   1x         1x 1x 1x 1x 1x 1x 1x 1x       1x   1x                           1x 1x 1x 1x   1x   1x         1x 1x 1x 1x 1x   1x                     1x 1x 1x  
import {
  buildGithubUrl,
  buildGoogleFormUrl,
  collectDiagnostics,
  formatDiagnostics,
  openTab,
  type Diagnostics,
  type ReportContext,
} from '@/helpers/bugReport';
import { i18n } from '@/helpers/i18n';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import { createTheme, styled, ThemeProvider } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useMemo, useState } from 'react';
import { createRoot } from 'react-dom/client';
 
/** Which report path the user chose, or that they dismissed the dialog. */
export type ReportChoice = 'github' | 'google' | 'dismissed';
 
/**
 * Scrollable, monospaced block that shows the prefilled diagnostics text.
 * @category Components
 * @group Bug reporting
 */
const DiagnosticsBlock = styled('pre')(({ theme }) => ({
  maxHeight: 200,
  overflow: 'auto',
  margin: 0,
  padding: theme.spacing(1.25),
  borderRadius: theme.shape.borderRadius,
  backgroundColor: theme.palette.action.hover,
  fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
  fontSize: 12,
  lineHeight: 1.45,
  whiteSpace: 'pre-wrap',
  wordBreak: 'break-word',
}));
 
/** Props for {@link ReportDialog}. */
interface ReportDialogProps {
  /** Whether the dialog is open. */
  open: boolean;
  /** The full, formatted diagnostics text shown and copied. */
  fullText: string;
  /** Prefilled GitHub issue URL. */
  githubUrl: string;
  /** Prefilled Google Form URL, when a form is configured. */
  googleUrl?: string;
  /** Called with the user's choice when the dialog closes. */
  onClose: (choice: ReportChoice) => void;
}
 
/**
 * The bug-report review dialog. Shows the prefilled diagnostics and offers the
 * two credential-free submission paths (GitHub and Google) plus copy-to-clipboard.
 * Presentational only — URL building and diagnostics collection happen upstream.
 * @component
 * @category Components
 * @param props - See {@link ReportDialogProps}.
 * @example
 * ```tsx
 * <ReportDialog open fullText={text} githubUrl={gh} onClose={handleClose} />
 * ```
 * @source
 */
export function ReportDialog({ open, fullText, githubUrl, googleUrl, onClose }: ReportDialogProps) {
  const [copied, setCopied] = useState(false);
 
  const handleCopy = () => {
    void navigator.clipboard?.writeText(fullText);
    setCopied(true);
  };
 
  const handleGithub = () => {
    openTab(githubUrl);
    onClose('github');
  };
 
  const handleGoogle = () => {
    if (!googleUrl) return;
    // Long stacks are truncated in the URL, so also hand over the full text.
    void navigator.clipboard?.writeText(fullText);
    openTab(googleUrl);
    onClose('google');
  };
 
  return (
    <Dialog
      open={open}
      onClose={() => onClose('dismissed')}
      aria-labelledby="report-dialog-title"
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle id="report-dialog-title">{i18n('report_dialog_title')}</DialogTitle>
      <DialogContent>
        <DialogContentText sx={{ mb: 1.5 }}>{i18n('report_dialog_desc')}</DialogContentText>
        <DiagnosticsBlock>{fullText}</DiagnosticsBlock>
      </DialogContent>
      <DialogActions>
        <Button variant="contained" onClick={handleGithub}>
          {i18n('report_via_github')}
        </Button>
        {googleUrl ? <Button onClick={handleGoogle}>{i18n('report_via_google')}</Button> : null}
        <Button onClick={handleCopy}>{copied ? i18n('report_copied') : i18n('report_copy')}</Button>
        <Button onClick={() => onClose('dismissed')}>{i18n('report_close')}</Button>
      </DialogActions>
    </Dialog>
  );
}
 
/** Props for {@link ReportDialogHost}. */
interface ReportDialogHostProps {
  /** The assembled diagnostics snapshot to report. */
  diagnostics: Diagnostics;
  /** Called once the user resolves the dialog. */
  onDone: (choice: ReportChoice) => void;
}
 
/**
 * Stateful wrapper that owns the dialog's open state and a self-contained theme,
 * so {@link showReportDialog} can mount it into its own React root — independent
 * of the app tree, and therefore still functional when that tree has crashed.
 * @param props - See {@link ReportDialogHostProps}.
 * @returns The themed dialog.
 * @source
 */
function ReportDialogHost({ diagnostics, onDone }: ReportDialogHostProps) {
  const [open, setOpen] = useState(true);
  const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
  const theme = useMemo(
    () => createTheme({ palette: { mode: prefersDark ? 'dark' : 'light' } }),
    [prefersDark],
  );
 
  const githubUrl = useMemo(() => buildGithubUrl(diagnostics), [diagnostics]);
  const googleUrl = useMemo(() => buildGoogleFormUrl(diagnostics), [diagnostics]);
  const fullText = useMemo(() => formatDiagnostics(diagnostics), [diagnostics]);
 
  const handleClose = (choice: ReportChoice) => {
    setOpen(false);
    onDone(choice);
  };
 
  return (
    <ThemeProvider theme={theme}>
      <ReportDialog
        open={open}
        fullText={fullText}
        githubUrl={githubUrl}
        googleUrl={googleUrl}
        onClose={handleClose}
      />
    </ThemeProvider>
  );
}
 
/**
 * Collects diagnostics and shows the review dialog, resolving once the user
 * picks a report path or dismisses. Mounts the dialog into a throwaway React
 * root appended to `document.body`, so it works from any context — including the
 * class-based `ErrorBoundary` after a render crash. When no DOM is available it
 * opens the GitHub path directly.
 * @param error - The error that triggered the report, if any.
 * @param context - Optional page URL, action label, and extra payload.
 * @returns The user's choice.
 * @example
 * ```ts
 * await showReportDialog(err, { action: "render-crash" });
 * ```
 * @source
 */
export async function showReportDialog(
  error?: unknown,
  context?: ReportContext,
): Promise<ReportChoice> {
  const diagnostics = await collectDiagnostics(error, context);
 
  if (typeof document === 'undefined') {
    openTab(buildGithubUrl(diagnostics));
    return 'github';
  }
 
  return new Promise<ReportChoice>((resolve) => {
    const container = document.createElement('div');
    document.body.append(container);
    const root = createRoot(container);
    let settled = false;
 
    const finish = (choice: ReportChoice) => {
      if (settled) return;
      settled = true;
      resolve(choice);
      // Defer teardown so the dialog's close transition can finish.
      globalThis.setTimeout(() => {
        root.unmount();
        container.remove();
      }, 300);
    };
 
    root.render(<ReportDialogHost diagnostics={diagnostics} onDone={finish} />);
  });
}