Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

21.3 KB
Raw Blame
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { isRouteErrorResponse } from 'react-router-dom'
import classNames from 'classnames'
import {
  Copy,
  Download,
  EllipsisVertical,
  ExternalLink,
  FolderOpen,
  TriangleAlert
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'

import Badge from '../Badge'
import Button from '../Button'
import Icon from '../Icon'
import Panel from '../Panel'
import { isLogTooLarge } from '../AppErrorBoundary/logReport'
import { scrubSensitive } from './scrub'
import './index.css'

const GITHUB_NEW_ISSUE_URL =
  'https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher/issues/new?template=bug_report.yaml'
const LOG_TAIL_LINES = 80

export type AppErrorPanelVariant = 'page' | 'shell' | 'inline'

export type AppErrorContextItem = {
  label: string
  value: string
}

export type AppErrorMenuAction = {
  id: string
  label: string
  icon: LucideIcon
  onSelect: () => void
  separated?: boolean
  danger?: boolean
  mirror?: boolean
}

type AppErrorPrimaryAction = {
  label: string
  icon?: LucideIcon
  onClick?: () => void | Promise<void>
}

type ErrorInfo = {
  name: string
  message: string
  stack: string
}

type Feedback = {
  tone: 'success' | 'error'
  message: string
}

type Props = {
  variant: AppErrorPanelVariant
  title: string
  subtitle: string
  error: unknown
  route?: string
  context?: AppErrorContextItem[]
  primaryAction?: AppErrorPrimaryAction
  menuActionsBefore?: AppErrorMenuAction[]
  menuActionsAfter?: AppErrorMenuAction[]
  logCrash?: boolean
  autoFocusTitle?: boolean
}

function safeStringify(value: unknown): string {
  if (value == null) return ''
  if (typeof value === 'string') return value
  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value)
  }
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    // Circular or otherwise unserializable values
    return Object.prototype.toString.call(value)
  }
}

function normalizeError(
  error: unknown,
  unknownMessage = 'Unknown error'
): ErrorInfo {
  if (isRouteErrorResponse(error)) {
    return {
      name: `HTTP ${error.status}`,
      message: safeStringify(error.data) || error.statusText || unknownMessage,
      stack: ''
    }
  }

  if (error instanceof Error) {
    return {
      name: error.name || 'Error',
      message: error.message || safeStringify(error) || unknownMessage,
      stack: error.stack ?? ''
    }
  }

  return {
    name: 'Error',
    message: safeStringify(error) || unknownMessage,
    stack: ''
  }
}

async function writeToClipboard(text: string) {
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text)
      return
    }
  } catch {
    // Fall through to the Electron clipboard, which does not need a
    // permission prompt and works even when the document is not focused.
  }

  const electronClipboard = window.api?.clipboardWriteText as
    | ((value: string) => void | Promise<void>)
    | undefined

  if (!electronClipboard) {
    throw new Error('Clipboard is unavailable')
  }

  await Promise.resolve(electronClipboard(text))
}

async function readHeroicLog(): Promise<string> {
  try {
    return (await window.api?.getLogContent?.({})) ?? ''
  } catch {
    return ''
  }
}

async function readSystemInfo(): Promise<string> {
  try {
    const info = await window.api?.systemInfo?.get?.(false)
    return info ? JSON.stringify(info, null, 2) : ''
  } catch {
    return ''
  }
}

function reportFileName(date = new Date()): string {
  const pad = (value: number) => String(value).padStart(2, '0')

  return `heroic-error-report-${date.getFullYear()}${pad(
    date.getMonth() + 1
  )}${pad(date.getDate())}-${pad(date.getHours())}${pad(
    date.getMinutes()
  )}${pad(date.getSeconds())}.txt`
}

function downloadTextFile(text: string, filename: string) {
  const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const anchor = document.createElement('a')

  anchor.href = url
  anchor.download = filename
  anchor.style.display = 'none'
  document.body.append(anchor)

  try {
    anchor.click()
  } finally {
    anchor.remove()
    setTimeout(() => URL.revokeObjectURL(url), 0)
  }
}

function logTail(log: string): string {
  if (!log.trim()) return ''

  return log.split('\n').slice(-LOG_TAIL_LINES).join('\n')
}

export default function AppErrorPanel({
  variant,
  title,
  subtitle,
  error,
  route,
  context = [],
  primaryAction,
  menuActionsBefore = [],
  menuActionsAfter = [],
  logCrash = false,
  autoFocusTitle = false
}: Props) {
  const { t } = useTranslation()
  const titleId = useId()
  const descriptionId = useId()
  const isInline = variant === 'inline'

  const titleRef = useRef<HTMLHeadingElement>(null)
  const messageRef = useRef<HTMLParagraphElement>(null)
  const menuRef = useRef<HTMLDivElement>(null)
  const menuTriggerRef = useRef<HTMLButtonElement>(null)
  const mountedRef = useRef(false)

  const [heroicVersion, setHeroicVersion] = useState('')
  const [versionSettled, setVersionSettled] = useState(false)
  const [busy, setBusy] = useState(false)
  const [primaryBusy, setPrimaryBusy] = useState(false)
  const [feedback, setFeedback] = useState<Feedback | null>(null)
  const [menuOpen, setMenuOpen] = useState(false)
  const [messageExpanded, setMessageExpanded] = useState(false)
  const [messageOverflows, setMessageOverflows] = useState(false)
  const [logExcerpt, setLogExcerpt] = useState('')

  const [occurredAt] = useState(() => new Date().toISOString())
  const [reportMode, setReportMode] = useState<'copy' | 'download'>('copy')

  const unknownMessage = t('error.unknown-error', 'Unknown error')
  const errorInfo = useMemo(
    () => normalizeError(error, unknownMessage),
    [error, unknownMessage]
  )
  const safeErrorInfo = useMemo(
    () => ({
      name: scrubSensitive(errorInfo.name),
      message: scrubSensitive(errorInfo.message),
      stack: scrubSensitive(errorInfo.stack)
    }),
    [errorInfo]
  )
  const safeContext = useMemo(
    () =>
      context.map((item) => ({
        label: item.label,
        value: scrubSensitive(item.value)
      })),
    [context]
  )
  const showErrorBlock = !isInline || safeErrorInfo.message !== unknownMessage

  const displayContext = useMemo(() => {
    const errorLabel = t('error.context.error', 'Error')

    return isInline
      ? safeContext.filter((item) => item.label !== errorLabel)
      : safeContext
  }, [isInline, safeContext, t])

  const logRef = useRef<string | null>(null)
  const logRequestRef = useRef<Promise<string> | null>(null)

  const loadLog = useCallback(() => {
    if (logRef.current !== null) return Promise.resolve(logRef.current)

    if (!logRequestRef.current) {
      logRequestRef.current = readHeroicLog().then((log) => {
        logRef.current = log
        return log
      })
    }

    return logRequestRef.current
  }, [])

  useEffect(() => {
    let cancelled = false

    void loadLog().then((log) => {
      if (!cancelled) {
        setReportMode(isLogTooLarge(log) ? 'download' : 'copy')
        setLogExcerpt(logTail(log))
      }
    })

    return () => {
      cancelled = true
    }
  }, [loadLog])

  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  useEffect(() => {
    if (autoFocusTitle) {
      titleRef.current?.focus()
    }
  }, [autoFocusTitle])

  useEffect(() => {
    let cancelled = false

    Promise.resolve(window.api?.getHeroicVersion?.())
      .then((version) => {
        if (!cancelled && typeof version === 'string') {
          setHeroicVersion(version)
        }
      })
      .catch(() => {
        // The version is a nice-to-have, never block the screen on it
      })
      .finally(() => {
        if (!cancelled) setVersionSettled(true)
      })

    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    const element = messageRef.current
    if (!element || messageExpanded) return

    const measure = () => {
      setMessageOverflows(element.scrollHeight > element.clientHeight + 1)
    }

    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(element)

    return () => observer.disconnect()
  }, [safeErrorInfo.message, messageExpanded])

  useEffect(() => {
    if (!menuOpen) return

    const handlePointerDown = (event: MouseEvent) => {
      if (!menuRef.current?.contains(event.target as Node)) {
        setMenuOpen(false)
      }
    }

    document.addEventListener('mousedown', handlePointerDown)
    return () => document.removeEventListener('mousedown', handlePointerDown)
  }, [menuOpen])

  useEffect(() => {
    if (!logCrash || !versionSettled) return

    try {
      window.api?.logError?.(
        [
          'Unexpected application error',
          `Route: ${route || 'unknown'}`,
          `Heroic version: ${heroicVersion || 'unknown'}`,
          `${safeErrorInfo.name}: ${safeErrorInfo.message}`,
          safeErrorInfo.stack
        ]
          .filter(Boolean)
          .join('\n')
      )
    } catch {
      // Reporting an error must never throw
    }
  }, [logCrash, route, heroicVersion, safeErrorInfo, versionSettled])

  const platform = useMemo(
    () =>
      typeof navigator === 'undefined'
        ? 'unknown'
        : `${navigator.platform || 'unknown'} — ${navigator.userAgent}`,
    []
  )

  const technicalDetails = useMemo(() => {
    const contextDetails = safeContext
      .map((item) => `${item.label}: ${item.value}`)
      .join('\n')

    return [
      `Time: ${occurredAt}`,
      `Route: ${route || 'unknown'}`,
      `Heroic version: ${heroicVersion || 'unknown'}`,
      `Platform: ${platform}`,
      contextDetails,
      '',
      `${safeErrorInfo.name}: ${safeErrorInfo.message}`,
      safeErrorInfo.stack ? `\nStack trace:\n${safeErrorInfo.stack}` : '',
      logExcerpt
        ? `\nLog (last ${LOG_TAIL_LINES} lines):\n${scrubSensitive(logExcerpt)}`
        : ''
    ]
      .filter(Boolean)
      .join('\n')
  }, [
    occurredAt,
    route,
    heroicVersion,
    platform,
    safeContext,
    safeErrorInfo,
    logExcerpt
  ])

  const buildReport = useCallback(
    (log: string, systemInfo: string) =>
      scrubSensitive(
        [
          '=== Heroic Games Launcher error report ===',
          '',
          technicalDetails,
          '',
          '=== System information ===',
          systemInfo || '(unavailable)',
          '',
          '=== Heroic log ===',
          log.trim() || '(no log file found)'
        ].join('\n')
      ),
    [technicalDetails]
  )

  const handleCopyReport = async () => {
    setBusy(true)
    setFeedback(null)

    try {
      const [log, systemInfo] = await Promise.all([loadLog(), readSystemInfo()])
      await writeToClipboard(buildReport(log, systemInfo))

      setFeedback({
        tone: 'success',
        message: log.trim()
          ? t(
              'error.report-copied',
              'Error report copied. Paste it into your issue on GitHub.'
            )
          : t(
              'error.report-copied-no-log',
              'Error report copied, without the Heroic log (none was found).'
            )
      })
    } catch {
      setFeedback({
        tone: 'error',
        message: t(
          'error.copy-failed',
          'Could not copy. Try again, or open the log folder.'
        )
      })
    } finally {
      setBusy(false)
    }
  }

  const handleDownloadReport = async () => {
    setBusy(true)
    setFeedback(null)

    try {
      const [log, systemInfo] = await Promise.all([loadLog(), readSystemInfo()])
      downloadTextFile(buildReport(log, systemInfo), reportFileName())
      setFeedback({
        tone: 'success',
        message: t(
          'error.report-downloaded',
          'Error report downloaded. Attach it to your issue on GitHub.'
        )
      })
    } catch {
      setFeedback({
        tone: 'error',
        message: t(
          'error.report-download-failed',
          'Could not download the report. Try again.'
        )
      })
    } finally {
      setBusy(false)
    }
  }

  const handleOpenLogFolder = () => {
    try {
      window.api?.showLogFileInFolder?.({})
    } catch {
      // Nothing sensible to do if the folder cannot be opened
    }
  }

  const handleOpenIssue = () => {
    try {
      window.api?.openExternalUrl?.(GITHUB_NEW_ISSUE_URL)
    } catch {
      // Ignore
    }
  }

  const closeMenu = useCallback((returnFocus = true) => {
    setMenuOpen(false)
    if (returnFocus) {
      menuTriggerRef.current?.focus()
    }
  }, [])

  const handleMenuKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    const items = Array.from(
      menuRef.current?.querySelectorAll<HTMLButtonElement>(
        '[role="menuitem"]:not([disabled])'
      ) ?? []
    )
    const current = items.indexOf(document.activeElement as HTMLButtonElement)

    if (event.key === 'Escape') {
      event.preventDefault()
      closeMenu()
      return
    }

    if (!items.length) return

    let next = -1
    if (event.key === 'ArrowDown') next = (current + 1) % items.length
    if (event.key === 'ArrowUp')
      next = (current - 1 + items.length) % items.length
    if (event.key === 'Home') next = 0
    if (event.key === 'End') next = items.length - 1

    if (next >= 0) {
      event.preventDefault()
      items[next].focus()
    }
  }

  const handleMenuToggle = () => {
    if (menuOpen) {
      closeMenu()
      return
    }

    setMenuOpen(true)
    requestAnimationFrame(() => {
      menuRef.current
        ?.querySelector<HTMLButtonElement>('[role="menuitem"]')
        ?.focus()
    })
  }

  const handlePrimaryAction = async () => {
    if (!primaryAction?.onClick) return

    const result = primaryAction.onClick()
    if (!isInline || !result || typeof result.then !== 'function') return

    setPrimaryBusy(true)
    setFeedback(null)

    try {
      await result
      if (mountedRef.current) {
        setFeedback({
          tone: 'error',
          message: t(
            'error.install-info.still-unavailable',
            'Still unavailable. Try Refresh library or Clear cache from More.'
          )
        })
      }
    } catch {
      if (mountedRef.current) {
        setFeedback({
          tone: 'error',
          message: t(
            'error.install-info.still-unavailable',
            'Still unavailable. Try Refresh library or Clear cache from More.'
          )
        })
      }
    } finally {
      if (mountedRef.current) {
        setPrimaryBusy(false)
      }
    }
  }

  const internalMenuActions: AppErrorMenuAction[] = [
    {
      id: 'open-log-folder',
      label: t('error.open-log-folder', 'Open log folder'),
      icon: FolderOpen,
      onSelect: handleOpenLogFolder
    },
    ...(reportMode === 'copy'
      ? [
          {
            id: 'download-report',
            label: t('error.download-report', 'Download error report'),
            icon: Download,
            onSelect: handleDownloadReport
          }
        ]
      : []),
    {
      id: 'report-issue',
      label: t('error.report-issue', 'Report on GitHub'),
      icon: ExternalLink,
      onSelect: handleOpenIssue,
      separated: true
    }
  ]

  const menuActions = [
    ...menuActionsBefore,
    ...internalMenuActions,
    ...menuActionsAfter
  ]

  const Heading = isInline ? 'h2' : 'h1'

  return (
    <div
      className={classNames('AppError', `AppError--${variant}`)}
      data-variant={variant}
      role={isInline ? 'status' : 'alert'}
      aria-live={isInline ? 'polite' : undefined}
      aria-labelledby={titleId}
      aria-describedby={descriptionId}
    >
      <Panel className="AppError__panel" padding="lg" tone="solid">
        <header className="AppError__header">
          <span className="AppError__icon" aria-hidden="true">
            <Icon glyph={TriangleAlert} size="lg" />
          </span>
          <div className="AppError__heading">
            <Heading
              className="AppError__title"
              id={titleId}
              ref={titleRef}
              tabIndex={autoFocusTitle ? -1 : undefined}
            >
              {title}
            </Heading>
            <p className="AppError__subtitle" id={descriptionId}>
              {subtitle}
            </p>
          </div>
        </header>

        {displayContext.length > 0 && (
          <dl className="AppError__context">
            {displayContext.map((item) => (
              <div className="AppError__contextRow" key={item.label}>
                <dt>{item.label}</dt>
                <dd>{item.value}</dd>
              </div>
            ))}
          </dl>
        )}

        {showErrorBlock && (
          <div className="AppError__error">
            <Badge variant="error">{safeErrorInfo.name}</Badge>
            <p
              className={classNames('AppError__message', {
                'is-expanded': messageExpanded
              })}
              ref={messageRef}
            >
              {safeErrorInfo.message}
            </p>
            {messageOverflows && !messageExpanded && (
              <button
                type="button"
                className="AppError__show-full"
                onClick={() => setMessageExpanded(true)}
              >
                {t('error.show-full-message', 'Show full message')}
              </button>
            )}
          </div>
        )}

        {variant === 'page' && heroicVersion && (
          <p className="AppError__caption">
            {t('error.version-caption', 'Heroic {{version}}', {
              version: heroicVersion
            })}
          </p>
        )}

        <details className="AppError__details">
          <summary>{t('error.technical-details', 'Technical details')}</summary>
          <pre className="AppError__stack">{technicalDetails}</pre>
        </details>

        <div className="AppError__actions">
          {primaryAction && (
            <Button
              icon={
                primaryAction.icon ? (
                  <Icon
                    glyph={primaryAction.icon}
                    size="sm"
                    className="AppError__mirror"
                  />
                ) : undefined
              }
              aria-disabled={primaryBusy}
              onClick={() => {
                if (!primaryBusy) {
                  void handlePrimaryAction()
                }
              }}
            >
              {primaryBusy
                ? t('error.install-info.trying-again', 'Trying again…')
                : primaryAction.label}
            </Button>
          )}

          <Button
            variant="secondary"
            icon={
              <Icon
                glyph={reportMode === 'download' ? Download : Copy}
                size="sm"
              />
            }
            onClick={() => {
              if (!busy) {
                void (reportMode === 'download'
                  ? handleDownloadReport()
                  : handleCopyReport())
              }
            }}
            aria-disabled={busy}
          >
            {busy
              ? t('error.preparing-report', 'Preparing…')
              : reportMode === 'download'
                ? t('error.download-report', 'Download error report')
                : t('error.copy-report', 'Copy error report')}
          </Button>

          <div
            className="AppError__menu"
            ref={menuRef}
            onBlur={(event) => {
              if (
                !menuRef.current?.contains(event.relatedTarget as Node | null)
              ) {
                setMenuOpen(false)
              }
            }}
          >
            <button
              type="button"
              ref={menuTriggerRef}
              className="AppError__menuTrigger"
              aria-label={t('error.more-actions', 'More actions')}
              aria-haspopup="menu"
              aria-expanded={menuOpen}
              onClick={handleMenuToggle}
              onKeyDown={(event) => {
                if (event.key === 'Escape') closeMenu()
              }}
            >
              <Icon glyph={EllipsisVertical} size="lg" />
            </button>

            {menuOpen && (
              <div
                className="AppError__menuPanel"
                role="menu"
                aria-label={t('error.more-actions', 'More actions')}
                onKeyDown={handleMenuKeyDown}
              >
                {menuActions.map((action) => (
                  <button
                    key={action.id}
                    type="button"
                    role="menuitem"
                    className={classNames('AppError__menuItem', {
                      'is-separated': action.separated,
                      'is-danger': action.danger
                    })}
                    onClick={() => {
                      closeMenu(action.id !== 'retry')
                      action.onSelect()
                    }}
                  >
                    <Icon
                      glyph={action.icon}
                      size="sm"
                      className={action.mirror ? 'AppError__mirror' : undefined}
                    />
                    <span>{action.label}</span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="AppError__feedback" aria-live="polite">
          {feedback && (
            <p className={`AppError__feedback-message is-${feedback.tone}`}>
              {feedback.message}
            </p>
          )}
        </div>
      </Panel>
    </div>
  )
}