| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789 |
- import { useState, useRef, useCallback, useEffect } from 'react';
- import { Bug, X, Loader2, CheckCircle, AlertCircle, AlertTriangle, Trash2, Upload, Circle, CheckCircle2, Stethoscope } from 'lucide-react';
- import { useTranslation } from 'react-i18next';
- import { useQuery } from '@tanstack/react-query';
- import { api, bugReportApi, supportApi, type PrinterDiagnosticResult } from '../api/client';
- import { DiagnosticChecklist } from './ConnectionDiagnostic';
- import { SystemHealthPanel } from './SystemHealthPanel';
- import { Collapsible } from './Collapsible';
- import { useIsMobile } from '../hooks/useIsMobile';
- type ViewState = 'form' | 'logging' | 'stopping' | 'submitting' | 'success' | 'error';
- /** One scanned printer paired with its name — the diagnostic result alone
- * carries no name, and the bug-report panel lists affected printers by name. */
- type DiagnosticEntry = { name: string; result: PrinterDiagnosticResult };
- const MAX_DIMENSION = 1920;
- const JPEG_QUALITY = 0.7;
- const MAX_LOG_SECONDS = 300; // 5 minutes
- /**
- * A logging run outlives the panel that started it (#2847).
- *
- * Step 2 asks the user to reproduce the problem, and the panel sits over the
- * part of the app they have to reach to do that. Closing it has to be allowed,
- * so the run is written down rather than held only in component state: the
- * panel reopens on the step it left, and a reload lands there too instead of
- * leaving the server at DEBUG with nothing in the UI still tracking it.
- *
- * The screenshot is deliberately not persisted. A 1920px JPEG runs to hundreds
- * of kilobytes against an origin-wide budget this app shares with everything
- * else it stores, and it survives a close either way — only a reload loses it,
- * and it is the one optional field on the form.
- */
- const SESSION_KEY = 'bambuddy-bug-report-session';
- interface LoggingSession {
- description: string;
- email: string;
- /** Debug logging was already on before this run, so stopping must leave it on. */
- wasDebug: boolean;
- /** Wall clock. Elapsed is derived from it rather than counted in ticks, which
- * a background tab throttles — the 5-minute cap has to mean five minutes. */
- startedAt: number;
- }
- function readSession(): LoggingSession | null {
- try {
- const raw = window.localStorage.getItem(SESSION_KEY);
- if (!raw) return null;
- const parsed = JSON.parse(raw) as Partial<LoggingSession>;
- if (typeof parsed?.startedAt !== 'number') return null;
- return {
- description: typeof parsed.description === 'string' ? parsed.description : '',
- email: typeof parsed.email === 'string' ? parsed.email : '',
- wasDebug: parsed.wasDebug === true,
- startedAt: parsed.startedAt,
- };
- } catch {
- // Unparseable or unreadable. Treat it as no session rather than trapping
- // the user in a panel that cannot restore.
- return null;
- }
- }
- function writeSession(session: LoggingSession): void {
- try {
- window.localStorage.setItem(SESSION_KEY, JSON.stringify(session));
- } catch {
- // Quota, or storage refused outright in a locked-down browser. The run
- // still works and still survives a close; it just will not survive a
- // reload, which is no worse than before it was written down at all.
- }
- }
- function clearSession(): void {
- try {
- window.localStorage.removeItem(SESSION_KEY);
- } catch {
- // See writeSession.
- }
- }
- function compressImage(file: File): Promise<string> {
- return new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => {
- let { width, height } = img;
- if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
- const scale = MAX_DIMENSION / Math.max(width, height);
- width = Math.round(width * scale);
- height = Math.round(height * scale);
- }
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d');
- if (!ctx) { reject(new Error('No canvas context')); return; }
- ctx.drawImage(img, 0, 0, width, height);
- const dataUrl = canvas.toDataURL('image/jpeg', JPEG_QUALITY);
- resolve(dataUrl.replace(/^data:[^;]+;base64,/, ''));
- };
- img.onerror = reject;
- img.src = URL.createObjectURL(file);
- });
- }
- function formatElapsed(seconds: number): string {
- const m = Math.floor(seconds / 60);
- const s = seconds % 60;
- return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
- }
- interface BugReportBubbleProps {
- /**
- * Render the floating disc in the bottom-right corner. False when the
- * trigger lives somewhere else — the compact header does this (#2750), so
- * the panel still mounts here while the button that opens it sits in the
- * header. The panel deliberately stays at the Layout root rather than
- * moving into the header with its button: the header is a ``fixed z-40``
- * element and therefore its own stacking context, so a ``z-50`` panel
- * nested inside it would be capped at the header's level and end up
- * underneath every ordinary z-50 modal in the app.
- */
- showTrigger?: boolean;
- /** Controlled open state. Falls back to internal state when omitted. */
- open?: boolean;
- onOpenChange?: (open: boolean) => void;
- /**
- * Fired when a logging run starts or ends. The floating disc shows a live run
- * itself, but the compact layout replaces the disc with a header button and
- * has no room for a timer, so Layout uses this to mark that button and to
- * offer a way back into the run from the debug-logging banner (#2847).
- */
- onLoggingChange?: (active: boolean) => void;
- }
- export function BugReportBubble({ showTrigger = true, open, onOpenChange, onLoggingChange }: BugReportBubbleProps = {}) {
- const { t } = useTranslation();
- const isMobile = useIsMobile();
- const [internalOpen, setInternalOpen] = useState(false);
- const isControlled = open !== undefined;
- const isOpen = isControlled ? open : internalOpen;
- const setIsOpen = useCallback(
- (next: boolean) => {
- if (!isControlled) setInternalOpen(next);
- onOpenChange?.(next);
- },
- [isControlled, onOpenChange],
- );
- const [viewState, setViewState] = useState<ViewState>('form');
- const [description, setDescription] = useState('');
- const [email, setEmail] = useState('');
- const [screenshot, setScreenshot] = useState<string | null>(null);
- const [isDragging, setIsDragging] = useState(false);
- const [issueUrl, setIssueUrl] = useState<string | null>(null);
- const [issueNumber, setIssueNumber] = useState<number | null>(null);
- const [errorMessage, setErrorMessage] = useState('');
- const [elapsedSeconds, setElapsedSeconds] = useState(0);
- const [startedAt, setStartedAt] = useState<number | null>(null);
- const [wasDebug, setWasDebug] = useState(false);
- const modalRef = useRef<HTMLDivElement>(null);
- const fileInputRef = useRef<HTMLInputElement>(null);
- const handleStopLoggingRef = useRef<() => void>(() => {});
- // Read inside effects that must not re-run when the view changes.
- const viewStateRef = useRef(viewState);
- viewStateRef.current = viewState;
- const isLogging = viewState === 'logging';
- useEffect(() => {
- onLoggingChange?.(isLogging);
- }, [isLogging, onLoggingChange]);
- // Before the user files a report, diagnose configured printers. Most bug
- // reports are setup issues — surfacing a connection problem inline lets the
- // user self-fix instead of waiting on a triage round-trip. The result is
- // always shown (healthy or not) so the user can see the check ran.
- const diagnosticScan = useQuery({
- queryKey: ['bugReportDiagnostic'],
- enabled: isOpen && viewState === 'form',
- staleTime: 30_000,
- queryFn: async (): Promise<DiagnosticEntry[]> => {
- const printers = await api.getPrinters();
- const entries = await Promise.all(
- printers.map(async (p) => {
- const result = await api.diagnosePrinter(p.id).catch(() => null);
- return result ? { name: p.name, result } : null;
- }),
- );
- return entries.filter((e): e is DiagnosticEntry => e !== null);
- },
- });
- const diagnosticEntries = diagnosticScan.data ?? [];
- const diagnosticProblems = diagnosticEntries.filter((e) => e.result.overall === 'problems');
- // Scan recent logs against the known-issue catalog. Like the diagnostic
- // above, this surfaces user-fixable ("layer 8") problems before a report is
- // filed. Only shown when something matched — a clean scan stays silent so
- // the form is uncluttered.
- const logHealthScan = useQuery({
- queryKey: ['bugReportLogHealth'],
- enabled: isOpen && viewState === 'form',
- staleTime: 30_000,
- queryFn: api.getSystemHealth,
- });
- const logFindings = logHealthScan.data?.findings ?? [];
- // Elapsed timer for logging phase — auto-stop at 5 minutes. Measured against
- // the run's start time rather than counted in ticks: the run continues while
- // the panel is closed and while the tab is in the background, where timers
- // are throttled hard enough that a tick count is not a clock.
- useEffect(() => {
- if (viewState !== 'logging' || startedAt === null) return;
- const tick = () => {
- const elapsed = Math.floor((Date.now() - startedAt) / 1000);
- setElapsedSeconds(elapsed);
- if (elapsed >= MAX_LOG_SECONDS) handleStopLoggingRef.current();
- };
- tick();
- const timer = setInterval(tick, 1000);
- return () => clearInterval(timer);
- }, [viewState, startedAt]);
- // Reset on open rather than in the click handler: the panel now has two
- // possible triggers (the floating disc here, and the compact header's button
- // which only flips the controlled flag), and a stale half-filled form
- // reappearing for one of them would be a nasty little inconsistency.
- //
- // A run in progress is the exception (#2847). Step 2 asks the user to
- // reproduce the problem, which usually means reaching a part of the app the
- // panel is sitting on top of, so closing it has to be allowed — and the only
- // thing that stops debug logging is the Stop & Submit button on the step this
- // reset used to throw away.
- useEffect(() => {
- if (!isOpen) return;
- if (viewStateRef.current === 'logging' || viewStateRef.current === 'stopping' || viewStateRef.current === 'submitting') return;
- setViewState('form');
- setDescription('');
- setEmail('');
- setScreenshot(null);
- setIssueUrl(null);
- setIssueNumber(null);
- setErrorMessage('');
- setElapsedSeconds(0);
- setStartedAt(null);
- setWasDebug(false);
- }, [isOpen]);
- // Pick a run back up after a reload. The panel's own state is gone by then,
- // but the server still has the log level raised, so without this the app is
- // left logging at DEBUG with nothing in the report flow still pointing at it.
- useEffect(() => {
- const session = readSession();
- if (!session) return;
- let cancelled = false;
- (async () => {
- let stillLogging: boolean;
- try {
- stillLogging = (await supportApi.getDebugLoggingState()).enabled;
- } catch {
- // Can't tell. Leave the session written down for the next load rather
- // than dropping a run that may well still be going.
- return;
- }
- if (cancelled || viewStateRef.current !== 'form') return;
- if (!stillLogging) {
- // Switched off from the System page, or the run was finished in another
- // tab. Either way there is nothing left to resume.
- clearSession();
- return;
- }
- const elapsed = Math.floor((Date.now() - session.startedAt) / 1000);
- if (elapsed >= MAX_LOG_SECONDS) {
- // Past the cap with nobody watching — the browser was closed, or the
- // tab sat elsewhere for an hour. Put the log level back, but do not
- // submit: a description written that long ago is not a report anyone is
- // still expecting to be filed, and no one is here to see it happen.
- try {
- await bugReportApi.stopLogging(session.wasDebug);
- } catch {
- // The banner in Layout still shows the raised level, and the System
- // page can lower it.
- }
- clearSession();
- return;
- }
- setDescription(session.description);
- setEmail(session.email);
- setWasDebug(session.wasDebug);
- setStartedAt(session.startedAt);
- setElapsedSeconds(elapsed);
- setViewState('logging');
- })();
- return () => { cancelled = true; };
- }, []);
- const handleOpen = () => setIsOpen(true);
- const handleClose = () => {
- setIsOpen(false);
- };
- const handleFile = useCallback(async (file: File) => {
- if (!file.type.startsWith('image/')) return;
- try {
- const b64 = await compressImage(file);
- setScreenshot(b64);
- } catch {
- // Ignore read errors
- }
- }, []);
- const handlePaste = useCallback((e: React.ClipboardEvent) => {
- const items = e.clipboardData?.items;
- if (!items) return;
- for (const item of items) {
- if (item.type.startsWith('image/')) {
- const file = item.getAsFile();
- if (file) handleFile(file);
- break;
- }
- }
- }, [handleFile]);
- const handleDragOver = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- setIsDragging(true);
- }, []);
- const handleDragLeave = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- setIsDragging(false);
- }, []);
- const handleDrop = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- setIsDragging(false);
- const file = e.dataTransfer.files?.[0];
- if (file) handleFile(file);
- }, [handleFile]);
- const handleStartLogging = async () => {
- if (!description.trim()) return;
- try {
- const result = await bugReportApi.startLogging();
- const runStartedAt = Date.now();
- setWasDebug(result.was_debug);
- setStartedAt(runStartedAt);
- setElapsedSeconds(0);
- setViewState('logging');
- writeSession({
- description: description.trim(),
- email: email.trim(),
- wasDebug: result.was_debug,
- startedAt: runStartedAt,
- });
- } catch (err) {
- setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
- setViewState('error');
- }
- };
- const handleStopLogging = async () => {
- // The cap can fire while the panel is closed, and stopping submits. Show
- // the panel so that happens in front of the user instead of behind them.
- setIsOpen(true);
- // The run is over from here whichever way it goes, so there is nothing left
- // to resume — including when stopping fails, where the banner in Layout is
- // what surfaces a log level that did not come back down.
- clearSession();
- setStartedAt(null);
- setViewState('stopping');
- try {
- const stopResult = await bugReportApi.stopLogging(wasDebug);
- await handleSubmitReport(stopResult.logs);
- } catch (err) {
- setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
- setViewState('error');
- }
- };
- handleStopLoggingRef.current = handleStopLogging;
- const handleSubmitReport = async (debugLogs: string) => {
- setViewState('submitting');
- try {
- const result = await bugReportApi.submit({
- description: description.trim(),
- email: email.trim() || undefined,
- screenshot_base64: screenshot || undefined,
- include_support_info: true,
- debug_logs: debugLogs || undefined,
- });
- if (result.success) {
- setIssueUrl(result.issue_url || null);
- setIssueNumber(result.issue_number || null);
- setViewState('success');
- } else {
- setErrorMessage(result.message);
- setViewState('error');
- }
- } catch (err) {
- setErrorMessage(err instanceof Error ? err.message : t('bugReport.unexpectedError'));
- setViewState('error');
- }
- };
- return (
- <>
- {/* Floating bubble. Absent below the sidebar-compact breakpoint, where
- the compact header carries the trigger instead — see Layout. */}
- {showTrigger && (
- <button
- onClick={handleOpen}
- className={`fixed bottom-4 right-4 z-40 w-12 h-12 rounded-full text-white shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-110 flex items-center justify-center ${
- // Amber while a run is going, matching the debug-logging banner, so
- // a closed panel still says the recording is live and clickable.
- isLogging ? 'bg-amber-500 hover:bg-amber-600' : 'bg-red-500 hover:bg-red-600'
- }`}
- title={isLogging ? t('bugReport.resumeRecording', { elapsed: formatElapsed(elapsedSeconds) }) : t('bugReport.title')}
- >
- {isLogging && (
- <span className="absolute inset-0 rounded-full bg-amber-400 opacity-75 animate-ping" />
- )}
- <Bug className="w-5 h-5 relative" />
- </button>
- )}
- {/* Slide-in panel anchored to bottom-right; a bottom sheet on phones.
- The desktop geometry cannot be reused there: `w-full` resolves against
- the viewport for a fixed element, so on a 375px screen the panel was
- 375px wide and then pushed 16px in from the right, putting its left
- edge at -16px and cutting a strip of the form off-screen. `max-w-md`
- hid this on anything above ~464px wide. */}
- {isOpen && (
- <div
- id="bug-report-modal"
- className={
- isMobile
- ? 'fixed inset-x-0 bottom-0 z-50'
- : showTrigger
- ? 'fixed bottom-20 right-4 z-50 w-full max-w-md'
- // Trigger is in the compact header, so anchor under it rather
- // than to a corner the user did not touch. Only reachable
- // between the mobile and sidebar-compact breakpoints — below
- // that it is a bottom sheet, above it the disc is back.
- : 'fixed top-16 right-4 z-50 w-full max-w-md'
- }
- onPaste={handlePaste}
- >
- <div
- ref={modalRef}
- className={`bg-white dark:bg-gray-800 shadow-2xl border border-gray-200 dark:border-gray-700 overflow-y-auto ${
- isMobile
- ? 'rounded-t-2xl max-h-[85vh] pb-[env(safe-area-inset-bottom)]'
- : 'rounded-lg max-h-[80vh]'
- }`}
- >
- {/* Header */}
- <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10">
- <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
- <Bug className="w-5 h-5 text-red-500" />
- {t('bugReport.title')}
- </h2>
- <button
- onClick={handleClose}
- className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
- >
- <X className="w-5 h-5" />
- </button>
- </div>
- <div className="p-4 space-y-4">
- {viewState === 'form' && (
- <>
- {/* Connection diagnostic — scanned on form-open. A healthy
- fleet shows a single confirmation line. When printers
- have problems, each is a collapsed row (auto-expanded
- when only one) so the form stays reachable regardless
- of how many printers are configured. */}
- {diagnosticScan.isLoading && (
- <div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
- <Loader2 className="w-3.5 h-3.5 animate-spin" />
- {t('bugReport.diagnosticChecking')}
- </div>
- )}
- {!diagnosticScan.isLoading && diagnosticProblems.length > 0 && (
- <div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3 space-y-3">
- <div className="flex items-start gap-2">
- <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- <div>
- <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
- {t('bugReport.diagnosticSummary', {
- problems: diagnosticProblems.length,
- total: diagnosticEntries.length,
- })}
- </p>
- <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
- {t('bugReport.diagnosticIntro')}
- </p>
- </div>
- </div>
- <div className="space-y-2">
- {diagnosticProblems.map((entry) => (
- <Collapsible
- key={entry.result.printer_id ?? entry.result.ip_address}
- defaultOpen={diagnosticProblems.length === 1}
- className="rounded-lg bg-amber-100/60 dark:bg-amber-900/30 px-3 py-2"
- summary={
- <div className="flex items-center gap-2 min-w-0">
- <AlertTriangle className="w-4 h-4 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- <span className="text-sm font-medium text-amber-800 dark:text-amber-200 truncate">
- {entry.name}
- </span>
- </div>
- }
- >
- <DiagnosticChecklist result={entry.result} />
- </Collapsible>
- ))}
- </div>
- </div>
- )}
- {!diagnosticScan.isLoading &&
- diagnosticEntries.length > 0 &&
- diagnosticProblems.length === 0 && (
- <div className="flex items-start gap-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3">
- <CheckCircle className="w-4 h-4 mt-0.5 flex-shrink-0 text-green-600 dark:text-green-400" />
- <p className="text-xs text-green-800 dark:text-green-200">
- {t('bugReport.diagnosticHealthy')}
- </p>
- </div>
- )}
- {/* Log-health scan — known issues found in recent logs.
- Shown only when something matched. */}
- {!logHealthScan.isLoading && logFindings.length > 0 && logHealthScan.data && (
- <div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3 space-y-3">
- <div className="flex items-start gap-2">
- <Stethoscope className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- <div>
- <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
- {t('bugReport.logHealthSummary')}
- </p>
- <p className="text-xs text-amber-800 dark:text-amber-200 mt-0.5">
- {t('bugReport.logHealthIntro')}
- </p>
- </div>
- </div>
- <SystemHealthPanel result={logHealthScan.data} />
- </div>
- )}
- {/* Description */}
- <div>
- <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
- {t('bugReport.description')} *
- </label>
- <textarea
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder={t('bugReport.descriptionPlaceholder')}
- rows={3}
- className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"
- />
- </div>
- {/* Email (optional) */}
- <div>
- <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
- {t('bugReport.email')}
- </label>
- <input
- type="email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- placeholder={t('bugReport.emailPlaceholder')}
- className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
- />
- <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
- {t('bugReport.emailPrivacy')}
- </p>
- </div>
- {/* Screenshot — upload, paste, or drag */}
- <div>
- <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
- {t('bugReport.screenshot')}
- </label>
- {screenshot ? (
- <div className="relative">
- <img
- src={`data:image/jpeg;base64,${screenshot}`}
- alt={t('bugReport.screenshot')}
- className="w-full max-h-40 object-contain rounded-lg border border-gray-200 dark:border-gray-600"
- />
- <button
- onClick={() => setScreenshot(null)}
- className="absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full shadow"
- title={t('common.delete')}
- >
- <Trash2 className="w-3 h-3" />
- </button>
- </div>
- ) : (
- <button
- type="button"
- onClick={() => fileInputRef.current?.click()}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- className={`w-full flex flex-col items-center gap-2 px-4 py-4 border-2 border-dashed rounded-lg transition-colors cursor-pointer ${
- isDragging
- ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-500'
- : 'border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400 dark:hover:border-gray-500 hover:text-gray-600 dark:hover:text-gray-300'
- }`}
- >
- <Upload className="w-5 h-5" />
- <span className="text-sm">{t('bugReport.uploadOrPaste')}</span>
- </button>
- )}
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- className="hidden"
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) handleFile(file);
- e.target.value = '';
- }}
- />
- </div>
- {/* Data collection notice */}
- <details className="text-xs bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
- <summary className="cursor-pointer font-medium text-amber-700 dark:text-amber-300 hover:text-amber-800 dark:hover:text-amber-200">
- {t('bugReport.dataCollectedSummary')}
- </summary>
- <div className="mt-2 space-y-2 pl-2 border-l-2 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-200">
- <p className="font-medium">{t('bugReport.dataIncluded')}</p>
- <p>{t('bugReport.dataIncludedList')}</p>
- <p className="font-medium">{t('bugReport.dataNeverIncluded')}</p>
- <p>{t('bugReport.dataNeverIncludedList')}</p>
- </div>
- </details>
- {/* Buttons */}
- <div className="flex justify-end gap-2 pt-2">
- <button
- onClick={handleClose}
- className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
- >
- {t('common.cancel')}
- </button>
- <button
- onClick={handleStartLogging}
- disabled={!description.trim()}
- className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
- >
- {t('bugReport.startLogging')}
- </button>
- </div>
- </>
- )}
- {viewState === 'logging' && (
- <div className="py-6 space-y-6">
- {/* 3-step progress indicator */}
- <div className="space-y-3 px-2">
- {/* Step 1: Completed */}
- <div className="flex items-center gap-3">
- <CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
- <span className="text-sm text-green-700 dark:text-green-400">{t('bugReport.stepEnableLogging')}</span>
- </div>
- {/* Step 2: Active */}
- <div className="flex items-center gap-3">
- <span className="relative flex h-5 w-5 flex-shrink-0 items-center justify-center">
- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
- <span className="relative inline-flex rounded-full h-3 w-3 bg-blue-500"></span>
- </span>
- <span data-testid="bug-report-step-reproduce" className="text-sm font-medium text-blue-700 dark:text-blue-300">{t('bugReport.stepReproduce')}</span>
- </div>
- {/* Step 3: Upcoming */}
- <div className="flex items-center gap-3">
- <Circle className="w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0" />
- <span className="text-sm text-gray-400 dark:text-gray-500">{t('bugReport.stepStopLogging')}</span>
- </div>
- </div>
- {/* Elapsed timer */}
- <div className="text-center">
- <p className="text-3xl font-mono text-blue-500">{formatElapsed(elapsedSeconds)}</p>
- <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{t('bugReport.maxDuration', { minutes: 5 })}</p>
- {/* The panel covers whatever has to be clicked to reproduce
- the problem, so say plainly that closing it is fine. */}
- <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">{t('bugReport.closeKeepsRecording')}</p>
- </div>
- {/* Stop & Submit button */}
- <div className="flex justify-center">
- <button
- onClick={handleStopLogging}
- className="px-6 py-2.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
- >
- {t('bugReport.stopAndSubmit')}
- </button>
- </div>
- </div>
- )}
- {(viewState === 'stopping' || viewState === 'submitting') && (
- <div className="flex flex-col items-center justify-center py-6 gap-3">
- <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
- <p className="text-sm text-gray-600 dark:text-gray-400 text-center">
- {viewState === 'stopping' ? t('bugReport.stoppingLogs') : t('bugReport.submitting')}
- </p>
- {viewState === 'submitting' && (
- // Diagnostics are run server-side inside the submit call
- // (#1506 follow-up): the bubble already displays current
- // results inline, but the submitted report now also
- // includes a snapshot. Wait is bounded but noticeable —
- // list what's running so the user knows why.
- <ul className="text-xs text-gray-500 dark:text-gray-400 list-disc list-inside space-y-0.5">
- <li>{t('bugReport.submittingStepConnection')}</li>
- <li>{t('bugReport.submittingStepVirtualPrinters')}</li>
- <li>{t('bugReport.submittingStepLogScan')}</li>
- <li>{t('bugReport.submittingStepSubmit')}</li>
- </ul>
- )}
- </div>
- )}
- {viewState === 'success' && (
- <div className="flex flex-col items-center justify-center py-8 gap-3">
- <CheckCircle className="w-12 h-12 text-green-500" />
- <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.thankYou')}</p>
- <p className="text-sm text-gray-600 dark:text-gray-400">{t('bugReport.submitted')}</p>
- {issueUrl && (
- <a
- href={issueUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="text-sm text-blue-500 hover:text-blue-600 underline"
- >
- {t('bugReport.viewIssue')} #{issueNumber}
- </a>
- )}
- <button
- onClick={handleClose}
- className="mt-4 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
- >
- {t('common.close')}
- </button>
- </div>
- )}
- {viewState === 'error' && (
- <div className="flex flex-col items-center justify-center py-8 gap-3">
- <AlertCircle className="w-12 h-12 text-red-500" />
- <p className="text-lg font-semibold text-gray-900 dark:text-white">{t('bugReport.submitFailed')}</p>
- <p className="text-sm text-gray-600 dark:text-gray-400 text-center">{errorMessage}</p>
- <div className="flex gap-2 mt-4">
- <button
- onClick={() => setViewState('form')}
- className="px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors"
- >
- {t('bugReport.submit')}
- </button>
- <button
- onClick={handleClose}
- className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
- >
- {t('common.close')}
- </button>
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
- )}
- </>
- );
- }
|