Skip to content

AI, fully local on your computer.

12.6 KB
Raw Blame
// The read-only document Preview modal, extracted to its own sibling file (DX-3 split,
// full-audit-2026-06-29 follow-up Phase 8). Relocated VERBATIM from `DocumentsScreen.tsx`;
// the summary + extracted-text disclosures, coverage meter, provenance, and copy/save/
// regenerate actions are byte-identical. Behavior unchanged.

import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { Banner, Button, CoverageMeter, Modal, TierMenu, useToast } from '../../components'
import { SourcesDisclosure } from '../../chat/SourcesDisclosure'
import { AssistantMarkdown } from '../../chat'
import type {
  CoverageTier,
  DocumentCoverage,
  DocumentOcrInfo,
  DocumentPreview,
  DocumentSummary
} from '@shared/types'
import { useT, type I18n } from '../../i18n'
import { friendlyIpcError } from '../../lib/errors'
import type { UiLanguage } from '@shared/i18n'
import { isPhotoDocument, ocrInfoLine, ocrUnsureLine } from './ocrNotes'

/** "Generated by <model> · <date>" — the summary attribution line. */
function summaryAttribution(s: DocumentSummary, t: I18n['t'], lang: UiLanguage): string {
  const date = s.createdAt ? new Date(s.createdAt) : null
  const when = date && !Number.isNaN(date.getTime()) ? date.toLocaleDateString(lang) : ''
  return `${t('docs.previewModal.generatedBy', { model: s.modelId })}${when ? ` · ${when}` : ''}`
}

/**
 * Read-only document preview: the parser's extracted text segments, grouped under their
 * page/section labels. Shows extracted TEXT (what the AI reads), not the original
 * layout — in encrypted workspaces the original bytes never leave the vault.
 * When the document has a persisted summary, it leads in a collapsible
 * section with the model/date attribution and a Regenerate action.
 */
export function PreviewModal({
  preview,
  ocr,
  summary,
  treeReady,
  originLine,
  regenerateDisabled,
  onLoadMore,
  onRegenerate,
  onSelectTier,
  onReadAgain,
  documentPages,
  onClose
}: {
  preview: DocumentPreview
  /** Recognition metadata when the text came from local OCR, or null. */
  ocr?: DocumentOcrInfo | null
  summary?: DocumentSummary | null
  /** A whole-document deep index is ready ⇒ the coverage-tier selector is offered. */
  treeReady?: boolean
  /** Provenance line when this is a generated document, or null. */
  originLine?: ReactNode
  regenerateDisabled?: boolean
  /** FE-6: fetch + append the next preview page; offered only when `preview.nextOffset != null`. */
  onLoadMore?: () => Promise<void>
  onRegenerate?: () => void
  /** Re-summarize at a coverage tier (whole-document-analysis §4.5); only when `treeReady`. */
  onSelectTier?: (tier: CoverageTier) => void
  /**
   * "Read again (OCR)" beside the low-confidence note (#538); offered only while OCR can run.
   * Absent ⇒ the note names the causes without the action.
   */
  onReadAgain?: () => void
  /** #575: the whole document's page count when only its scanned pages were read by OCR. */
  documentPages?: number
  onClose: () => void
}): JSX.Element {
  const { t, tCount, lang } = useT()
  const showToast = useToast()
  const photo = isPhotoDocument(preview.mimeType)
  const ocrUnsure = ocr ? ocrUnsureLine(ocr, t, { photo, documentPages }) : null
  // FE-6: guards the "Show more" button while a page is in flight.
  const [loadingMore, setLoadingMore] = useState(false)
  // full-audit 2026-07-11 CODE-35: a failed "Show more" page fetch used to land on the SCREEN
  // banner, which sits UNDER the dialog overlay — the button just looked dead. The error lives
  // here, inside the modal, next to the button that caused it; cleared on the next attempt.
  const [loadMoreError, setLoadMoreError] = useState<string | null>(null)
  async function loadMore(): Promise<void> {
    if (!onLoadMore || loadingMore) return
    setLoadingMore(true)
    setLoadMoreError(null)
    try {
      await onLoadMore()
    } catch (e) {
      setLoadMoreError(friendlyIpcError(e))
    } finally {
      setLoadingMore(false)
    }
  }
  // Coverage + source provenance of the current summary (whole-document-analysis §5.1).
  // Read-only, no model call; refreshes whenever the shown summary changes.
  const [cov, setCov] = useState<DocumentCoverage | null>(null)
  useEffect(() => {
    let alive = true
    if (!summary) {
      setCov(null)
      return
    }
    // Tolerant: a partial test bridge (or an older preload) may not provide the method —
    // `Promise.resolve(undefined)` then yields null, never a crash.
    void Promise.resolve(window.api.documentCoverage?.(preview.id))
      .then((c) => {
        if (alive) setCov(c ?? null)
      })
      .catch(() => {
        if (alive) setCov(null)
      })
    return () => {
      alive = false
    }
  }, [preview.id, summary])
  // Copy the raw summary Markdown to the OS clipboard (via MAIN — the packaged
  // renderer can't use navigator.clipboard). Confirmation is a transient toast.
  function onCopySummary(): void {
    if (!summary) return
    void Promise.resolve(window.api.copyToClipboard?.(summary.text))
      .then((ok) => showToast(ok ? t('docs.previewModal.copied') : t('docs.previewModal.copyFailed')))
      .catch(() => showToast(t('docs.previewModal.copyFailed')))
  }
  // Save the summary to a user-chosen Markdown file (dialog + fs run in MAIN). A
  // cancelled dialog resolves null and shows no toast.
  async function onSaveSummary(): Promise<void> {
    if (!summary) return
    try {
      const path = await window.api.exportSummary?.(preview.id)
      if (path) showToast(t('docs.previewModal.savedTo', { path }))
    } catch {
      // Export is cancellable from the OS dialog; a failure simply shows no toast.
    }
  }
  return (
    <Modal
      open
      title={preview.title}
      ariaLabel={t('docs.previewModal.aria', { title: preview.title })}
      width="wide"
      onClose={onClose}
      t={t}
    >
      <p className="hint" style={{ margin: '0 0 8px' }}>
        {t('docs.previewModal.hint')}
      </p>
      {ocr && (
        <p className="hint" style={{ margin: '0 0 8px' }}>
          {ocrInfoLine(ocr, t, tCount, { photo, documentPages })}
        </p>
      )}
      {ocrUnsure && (
        <div className="preview-ocr-unsure">
          <p className="hint" style={{ margin: 0 }}>
            {ocrUnsure} {t('docs.ocr.unsure.causes')}
          </p>
          {onReadAgain && (
            <Button
              size="sm"
              title={t(photo ? 'docs.makeSearchableAgainPhotoTitle' : 'docs.makeSearchableAgainTitle')}
              onClick={onReadAgain}
            >
              {t('docs.makeSearchableAgain')}
            </Button>
          )}
        </div>
      )}
      {originLine && (
        <p className="hint" style={{ margin: '0 0 8px' }}>
          {originLine}
        </p>
      )}
      {/* Single scroll region (audit: a long summary sat above the scroll box and overflowed
          with no scrollbar). Summary + extracted text now scroll together.
          DOC-10 (#150): named preview-scroll, NOT .modal-body — Modal already wraps all
          children in its own .modal-body, so the old nested copy doubled padding-right and
          made any future .modal-body change hit this dialog twice. */}
      <div className="preview-scroll">
        {summary && (
          <details className="doc-summary" open>
            <summary>{t('docs.previewModal.summary')}</summary>
            <div className="doc-summary-body">
              <p className="hint" style={{ margin: 0 }}>
                {summaryAttribution(summary, t, lang)}
              </p>
              {/* Coverage meter (whole-document-analysis §5.2): states breadth (whole document
                  vs the beginning) AND depth (tier) honestly — augments the truncated banner. */}
              {cov && <CoverageMeter coverage={cov.coverage} />}
              {summary.truncated && (
                <Banner tone="warning">{t('docs.previewModal.truncated')}</Banner>
              )}
              {/* Coverage-tier selector — only with a ready deep index (Tier 2/3 read it). */}
              {treeReady && onSelectTier && (
                <TierMenu
                  value={summary.tier ?? 1}
                  disabled={regenerateDisabled}
                  onChange={onSelectTier}
                />
              )}
              {/* Render the summary as Markdown (local models emit `**bold**`/lists/headings —
                  the raw asterisks read as broken). Reuses the chat answer styling + sanitizer. */}
              <div className="msg-content md">
                <AssistantMarkdown text={summary.text} />
              </div>
              {/* Source provenance behind a deep-index summary — the leaf SOURCE chunks (M2:
                  never node summaries). Reuses the chat sources disclosure; passing the coverage
                  mode (a deep-index summary is mode `tree`) renders it as whole-document
                  provenance + caps the list, same as the chat path (FE-B / F11 Phase 5). */}
              {cov && cov.provenance.length > 0 && (
                <SourcesDisclosure citations={cov.provenance} mode={cov.coverage.mode} />
              )}
              <div className="actions" style={{ marginTop: 4 }}>
                <Button size="sm" onClick={onCopySummary}>
                  {t('docs.previewModal.copy')}
                </Button>
                <Button size="sm" onClick={() => void onSaveSummary()}>
                  {t('docs.previewModal.save')}
                </Button>
                {onRegenerate && (
                  <Button size="sm" disabled={regenerateDisabled} onClick={onRegenerate}>
                    {t('docs.previewModal.regenerate')}
                  </Button>
                )}
              </div>
            </div>
          </details>
        )}
        {preview.segments.length === 0 && (
          <p className="hint">{t('docs.previewModal.noText')}</p>
        )}
        {/* The extracted text is collapsed behind a disclosure: for a large document the
            per-page list runs very long and buries the summary above. Open by default only
            when there's no summary, so the preview never looks empty. Markdown documents
            (e.g. machine-translated .md) render formatted — the raw `**bold**`/lists read
            as broken otherwise — reusing the chat answer styling + sanitizer. */}
        {preview.segments.length > 0 &&
          (() => {
            const isMarkdown = (preview.mimeType ?? '').includes('markdown')
            return (
              <details className="doc-summary doc-rawtext" open={!summary}>
                <summary>{t('docs.previewModal.documentText')}</summary>
                <div className="doc-summary-body">
                  {preview.segments.map((s, i) => (
                    <div key={i} className="preview-segment">
                      {(s.pageNumber != null || s.sectionLabel) && (
                        <div className="preview-label">
                          {s.pageNumber != null
                            ? t('docs.previewModal.page', { page: s.pageNumber })
                            : s.sectionLabel}
                        </div>
                      )}
                      {isMarkdown ? (
                        <div className="msg-content md">
                          <AssistantMarkdown text={s.text} />
                        </div>
                      ) : (
                        <div className="preview-text">{s.text}</div>
                      )}
                    </div>
                  ))}
                  {/* FE-6: the preview arrives a page at a time; reveal the rest on demand
                      instead of mounting a whole large document at once. */}
                  {preview.nextOffset != null && (
                    <div className="preview-more">
                      {/* CODE-35: the page-fetch failure, visible ABOVE the overlay. */}
                      {loadMoreError && <Banner tone="error">{loadMoreError}</Banner>}
                      <Button size="sm" disabled={loadingMore} onClick={() => void loadMore()}>
                        {loadingMore
                          ? t('docs.previewModal.loadingMore')
                          : t('docs.previewModal.showMore')}
                      </Button>
                      {preview.totalSegments != null && (
                        <span className="hint">
                          {t('docs.previewModal.segmentProgress', {
                            shown: preview.segments.length,
                            total: preview.totalSegments
                          })}
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </details>
            )
          })()}
      </div>
    </Modal>
  )
}