diff --git a/.changeset/36442-console-file-preview.md b/.changeset/36442-console-file-preview.md new file mode 100644 index 00000000000..d17f52f7462 --- /dev/null +++ b/.changeset/36442-console-file-preview.md @@ -0,0 +1,25 @@ +--- +'@object-ui/fields': patch +'@object-ui/app-shell': patch +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +--- + +feat(console): preview images, PDF, text and CSV in the page from a record's attachments and from a file field + +Clause-②: yes (widening) +Metadata-protocol: none + +A file opens in a dialog in the page instead of leaving it. In a record's attachments, the file's name opens the preview; the download stays in the row's menu. On a file field, a click on the file's link opens the preview; a modified click (new tab, new window) still opens the link as before. + +- **Four views, no new dependency.** Images (PNG, JPEG, GIF, WebP) draw in an image element, and an SVG only ever through an image element, never inlined. A PDF draws in the browser's own viewer in a frame; on a phone it opens in a new tab, which hands it to the system viewer. Plain text draws as text. A CSV draws as a table, read with the same GBK-aware decoder the grid's import wizard uses. +- **Download only.** Word, Excel, PowerPoint, HTML and every other type show "This file type cannot be previewed. Please download it." with a download button. An HTML file is never framed and never drawn as markup. +- **Limits.** Images and PDF up to 20 MB; text and CSV up to 2 MB, showing their first 1000 rows or lines. Past a limit the dialog shows "This file is too large to preview. Please download it." with a download button. +- **Controls.** Previous and next (and the arrow keys) walk a record's attachments; download; open in a new tab. +- **Same door as the download.** The preview reads the same signed link through the same permission check as the download, so a reader the download refuses sees the same refusal in the preview. When the browser cannot read a text or CSV file from the page (a bucket on another origin without the CORS rule the preview needs), the dialog offers the new tab instead. + +New exports from `@object-ui/fields`: `FilePreviewDialog` and its types `FilePreviewDialogProps` and `FilePreviewItem`; `decodeSpreadsheetText` and `parseDelimited`, the delimited-text reader that moved down from `@object-ui/plugin-grid` (which now imports them from `@object-ui/fields`; its own behaviour is unchanged). + +New `@object-ui/i18n` keys in every pack, under `fields.filePreview`: `title`, `previous`, `next`, `download`, `openInNewTab`, `loading`, `tooLarge`, `unsupported`, `denied`, `loadFailed`, `blocked`, `pdfOutside`, `truncatedRows`, `truncatedLines`, `empty`. + +No metadata key, value or default changes. diff --git a/ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx b/ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx index e548182f458..99a1a889efb 100644 --- a/ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx +++ b/ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx @@ -46,6 +46,7 @@ import { createAuthenticatedFetch, useAuth } from '@object-ui/auth'; import { useDisplayLocale } from '@object-ui/i18n'; import { useObjectTranslation, isPermissionError, classifyLoadError } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; +import { FilePreviewDialog, type FilePreviewItem } from '@object-ui/fields'; import { resolveAffordance, type ConfirmationHandler } from '@object-ui/core'; import { NATIVE_FILE_MAX_BYTES, @@ -77,6 +78,9 @@ import { RECORD_PAGE_ATTACHMENT_ROWS, recordAttachmentsCountField } from './reco * Downloads fetch a short-lived signed URL from `/storage/files/:fileId/url` * with the console's Bearer token (the endpoint requires an authenticated * session for attachments-scope files, objectstack-ai/objectstack#2970), then open it. + * A row's NAME opens the file in the page (`FilePreviewDialog`, objectstack#36442), + * which mints its link through that same door, so a reader the download refuses + * is refused the same way; the download itself stays in the row's ⋮ menu. * * The list read expands `uploaded_by` (the record page payload's attachments * part does the same), so the uploader column names whoever uploaded a row @@ -626,51 +630,85 @@ export const RecordAttachmentsPanel: React.FC = ({ [callAttachmentDoor, friendlyError, t], ); + /** + * The signed link for a row: the one door both the download and the preview + * read through. Throws the server's code on a refusal. + */ + const signedUrlFor = React.useCallback( + async (row: AttachmentRow): Promise => { + // The stable `/files/:fileId` endpoint now requires an authenticated + // session for attachments-scope files (objectstack-ai/objectstack#2970) — an can't + // carry the Bearer token. Fetch a short-lived signed URL with auth, + // then open it (the signed URL itself needs no credentials). + const res = await authFetch( + `${baseUrl}/api/v1/storage/files/${encodeURIComponent(row.file_id)}/url`, + ); + if (!res.ok) { + let code: string | undefined; + try { + // Read BOTH error dialects, the same way the success branch below + // reads both `url` shapes. The storage service moved its error + // code from a sibling of `error` into the declared + // `{ success: false, error: { code, message } }` envelope + // (objectstack#3675); a console build is deployed independently of + // the server it talks to, so it has to keep understanding the + // older top-level `code` too. Without the nested branch the 401/403 + // downgrade silently to "Download failed (403)" and the friendly + // copy below never fires. + const body = (await res.json()) as { code?: string; error?: { code?: string } } | null; + code = body?.error?.code ?? body?.code; + } catch { + /* non-JSON body */ + } + throw Object.assign(new Error(code ?? `Download failed (${res.status})`), { code }); + } + const body = await res.json(); + // Both URL dialects, for the same independent-deploy reason as the + // error branch above: the route answered a bare `{ url }` until + // objectstack#3689 moved it into the declared + // `{ success: true, data: { url } }` envelope. + const url: string | undefined = body?.url ?? body?.data?.url; + if (!url) throw new Error('Download URL missing from response'); + return /^https?:/i.test(url) ? url : `${baseUrl}${url}`; + }, + [authFetch, baseUrl], + ); + const handleDownload = React.useCallback( async (row: AttachmentRow) => { setError(null); try { - // The stable `/files/:fileId` endpoint now requires an authenticated - // session for attachments-scope files (objectstack-ai/objectstack#2970) — an can't - // carry the Bearer token. Fetch a short-lived signed URL with auth, - // then open it (the signed URL itself needs no credentials). - const res = await authFetch( - `${baseUrl}/api/v1/storage/files/${encodeURIComponent(row.file_id)}/url`, - ); - if (!res.ok) { - let code: string | undefined; - try { - // Read BOTH error dialects, the same way the success branch below - // reads both `url` shapes. The storage service moved its error - // code from a sibling of `error` into the declared - // `{ success: false, error: { code, message } }` envelope - // (objectstack#3675); a console build is deployed independently of - // the server it talks to, so it has to keep understanding the - // older top-level `code` too. Without the nested branch the 401/403 - // downgrade silently to "Download failed (403)" and the friendly - // copy below never fires. - const body = (await res.json()) as { code?: string; error?: { code?: string } } | null; - code = body?.error?.code ?? body?.code; - } catch { - /* non-JSON body */ - } - throw Object.assign(new Error(code ?? `Download failed (${res.status})`), { code }); - } - const body = await res.json(); - // Both URL dialects, for the same independent-deploy reason as the - // error branch above: the route answered a bare `{ url }` until - // objectstack#3689 moved it into the declared - // `{ success: true, data: { url } }` envelope. - const url: string | undefined = body?.url ?? body?.data?.url; - if (!url) throw new Error('Download URL missing from response'); - const target = /^https?:/i.test(url) ? url : `${baseUrl}${url}`; + const target = await signedUrlFor(row); if (await openInNativeShell(target, row)) return; window.open(target, '_blank', 'noopener,noreferrer'); } catch (err: any) { setError(friendlyError(err)); } }, - [authFetch, baseUrl, friendlyError], + [signedUrlFor, friendlyError], + ); + + // The in-page preview (objectstack#36442): the row whose name was clicked, + // and the rows as the dialog's set, so previous / next walk the list. + const [previewIndex, setPreviewIndex] = React.useState(null); + const previewFiles: FilePreviewItem[] = rows.map((row) => ({ + id: row.file_id, + name: row.file_name || row.file_id, + mimeType: row.mime_type ?? undefined, + size: row.size ?? undefined, + })); + const previewSignedUrl = React.useCallback( + async (file: FilePreviewItem): Promise => { + const row = rows.find((r) => r.file_id === file.id); + if (!row) throw new Error(t('fields.filePreview.loadFailed', { defaultValue: 'The preview could not be loaded.' })); + try { + return await signedUrlFor(row); + } catch (err) { + // The download's own copy for the download's own refusal. + throw Object.assign(new Error(friendlyError(err)), { cause: err }); + } + }, + [rows, signedUrlFor, friendlyError, t], ); // Upload is offered (the header's 「+ 上传」, the empty line's 「选择文件」 and @@ -870,7 +908,7 @@ export const RecordAttachmentsPanel: React.FC = ({ ) : (
    - {rows.map((row) => { + {rows.map((row, index) => { const TypeIcon = fileTypeIcon(row.mime_type); const name = row.file_name || row.file_id; const uploader = uploaderOf(row); @@ -879,7 +917,15 @@ export const RecordAttachmentsPanel: React.FC = ({ // and uploader step aside in a narrow container (a drawer).
  • - {name} + {formatSize(row.size)} @@ -943,6 +989,20 @@ export const RecordAttachmentsPanel: React.FC = ({ if (!open) setConfirmState((s) => ({ ...s, open: false })); }} /> + {previewIndex !== null && previewIndex < rows.length && ( + !open && setPreviewIndex(null)} + onIndexChange={setPreviewIndex} + resolveUrl={previewSignedUrl} + onDownload={(_file, index) => { + const row = rows[index]; + if (row) void handleDownload(row); + }} + /> + )} { diff --git a/ui/packages/app-shell/src/views/__tests__/RecordAttachmentsPanel.test.tsx b/ui/packages/app-shell/src/views/__tests__/RecordAttachmentsPanel.test.tsx index a77c489436e..c6aa047122b 100644 --- a/ui/packages/app-shell/src/views/__tests__/RecordAttachmentsPanel.test.tsx +++ b/ui/packages/app-shell/src/views/__tests__/RecordAttachmentsPanel.test.tsx @@ -1042,3 +1042,90 @@ describe('RecordAttachmentsPanel — Rename sends the new name to the rename doo expect(fetchSpy).not.toHaveBeenCalled(); }); }); + +/** + * objectstack#36442 — a row's name opens the file in the page. The preview + * mints its link through the download's own door (`/files/:id/url`, with the + * console's token), so a refused reader gets the download's own copy; the + * download itself stays in the row's ⋮ menu. + */ +describe('RecordAttachmentsPanel — the name opens the in-page preview (objectstack#36442)', () => { + const ROWS = [ + { ...ROW, id: 'a1', file_id: 'f1', file_name: 'report.pdf', mime_type: 'application/pdf' }, + { ...ROW, id: 'a2', file_id: 'f2', file_name: 'photo.png', mime_type: 'image/png' }, + { ...ROW, id: 'a3', file_id: 'f3', file_name: 'memo.docx', mime_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }, + ]; + const signed = (id: string) => + new Response(JSON.stringify({ success: true, data: { url: `/api/v1/storage/_local/raw/tok-${id}` } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + + it('clicking the name previews the file on the signed link the download mints', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!)); + setup(makeDataSource({ find: vi.fn(async () => ROWS) })); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: 'report.pdf' })); + const dialog = await screen.findByTestId('file-preview-dialog'); + await waitFor(() => expect(dialog.querySelector('iframe')?.getAttribute('src')).toContain('/api/v1/storage/_local/raw/tok-f1')); + expect(String(fetchSpy.mock.calls[0]![0])).toContain('/api/v1/storage/files/f1/url'); + expect(within(dialog).getByText('1 / 3')).toBeInTheDocument(); + }); + + it('next walks to the following row, with its own signed link', async () => { + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!)); + setup(makeDataSource({ find: vi.fn(async () => ROWS) })); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: 'report.pdf' })); + const dialog = await screen.findByTestId('file-preview-dialog'); + await user.click(within(dialog).getByRole('button', { name: 'Next file' })); + await waitFor(() => + expect((within(dialog).getByRole('img', { name: 'photo.png' }) as HTMLImageElement).getAttribute('src')).toContain('tok-f2'), + ); + expect(within(dialog).getByText('2 / 3')).toBeInTheDocument(); + }); + + it('a reader the download refuses is refused by the preview, with the same copy', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation( + async () => + new Response(JSON.stringify({ success: false, error: { code: 'ATTACHMENT_DOWNLOAD_DENIED', message: 'no' } }), { + status: 403, + headers: { 'Content-Type': 'application/json' }, + }), + ); + setup(makeDataSource({ find: vi.fn(async () => ROWS) })); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: 'photo.png' })); + const dialog = await screen.findByTestId('file-preview-dialog'); + await waitFor(() => + expect(within(dialog).getByRole('alert')).toHaveTextContent("You don't have access to download this attachment."), + ); + expect(dialog.querySelector('img, iframe')).toBeNull(); + // Asked once: a refusal is not re-asked on every render. + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it('a Word file offers the download only, and its download is the row menu\'s download', async () => { + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!)); + setup(makeDataSource({ find: vi.fn(async () => ROWS) })); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: 'memo.docx' })); + const dialog = await screen.findByTestId('file-preview-dialog'); + expect(within(dialog).getByText('This file type cannot be previewed. Please download it.')).toBeInTheDocument(); + expect(fetchSpy).not.toHaveBeenCalled(); + const view = dialog.querySelector('[data-preview-state="unsupported"]') as HTMLElement; + await user.click(within(view).getByRole('button', { name: 'Download' })); + await waitFor(() => + expect(openSpy).toHaveBeenCalledWith(expect.stringContaining('tok-f3'), '_blank', 'noopener,noreferrer'), + ); + }); + + it('the row menu still carries the download', async () => { + setup(makeDataSource({ find: vi.fn(async () => [ROW]) })); + const user = userEvent.setup(); + await screen.findByRole('button', { name: 'report.pdf' }); + await user.click(screen.getByRole('button', { name: /^More for / })); + expect(await screen.findByRole('menuitem', { name: 'Download' })).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 409e038efaf..0431cf91cd2 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5508,6 +5508,12 @@ export * from './widgets/FileField.js'; export * from './widgets/ImageField.js'; export { ImageCropperDialog } from './widgets/ImageCropperDialog.js'; export type { ImageCropperDialogProps } from './widgets/ImageCropperDialog.js'; +// The in-page file preview a record's attachments and a file field open +// (objectstack#36442), and the delimited-text reader its CSV view shares with +// the grid's import wizard. +export { FilePreviewDialog } from './widgets/FilePreviewDialog.js'; +export type { FilePreviewDialogProps, FilePreviewItem } from './widgets/FilePreviewDialog.js'; +export { decodeSpreadsheetText, parseDelimited } from './widgets/delimitedText.js'; export * from './widgets/LocationField.js'; export * from './widgets/FormulaField.js'; export * from './widgets/SummaryField.js'; diff --git a/ui/packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx b/ui/packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx new file mode 100644 index 00000000000..5da76682e1c --- /dev/null +++ b/ui/packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx @@ -0,0 +1,378 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36442 — the in-page file preview (decision objectstack#34781, + * option A): images, PDF, plain text and CSV preview in the page; Word, Excel, + * PowerPoint and HTML are download only; past a size limit the dialog says + * "too large"; a refusal reads as the download's refusal; SVG is only ever an + * `img`; HTML never reaches an `iframe` and never becomes markup. + * + * These pins read the rendered dialog: which view mounted (`data-preview-state`), + * which element carries the file, and which requests went out. + */ +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { I18nProvider } from '@object-ui/i18n'; +import { FilePreviewDialog, filePreviewKind, type FilePreviewDialogProps, type FilePreviewItem } from './FilePreviewDialog'; +import { FileValueAffordance } from './file-affordance'; +import { readFileValue } from './file-value'; + +const MB = 1024 * 1024; + +function renderDialog(props: Partial & { files: FilePreviewItem[] }) { + const onOpenChange = vi.fn(); + const utils = render( + + + , + ); + return { ...utils, onOpenChange }; +} + +/** The view the dialog mounted, by the slot it marks. */ +async function viewOf(): Promise { + const dialog = await screen.findByTestId('file-preview-dialog'); + await waitFor(() => expect(dialog.querySelector('[data-preview-state]')).not.toBeNull()); + return dialog.querySelector('[data-preview-state]')!.getAttribute('data-preview-state'); +} + +/** The PDF view's frame, if one mounted. */ +function frameOf(): HTMLIFrameElement | null { + return screen.getByTestId('file-preview-dialog').querySelector('iframe'); +} + +function textResponse(body: BodyInit, init: ResponseInit = {}) { + return new Response(body, { status: 200, ...init }); +} + +/** What the stable storage endpoint answers a grant with: a redirect, not followed. */ +const REDIRECT = { type: 'opaqueredirect', status: 0, ok: false, body: null } as unknown as Response; + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('filePreviewKind — which view a file gets (objectstack#36442)', () => { + it.each([ + [{ name: 'a.png', mimeType: 'image/png' }, 'image'], + [{ name: 'a.jpg', mimeType: 'image/jpeg' }, 'image'], + [{ name: 'a.gif', mimeType: 'image/gif' }, 'image'], + [{ name: 'a.webp', mimeType: 'image/webp' }, 'image'], + [{ name: 'logo.svg', mimeType: 'image/svg+xml' }, 'image'], + [{ name: 'a.pdf', mimeType: 'application/pdf' }, 'pdf'], + [{ name: 'notes.txt', mimeType: 'text/plain; charset=utf-8' }, 'text'], + [{ name: 'data.csv', mimeType: 'text/csv' }, 'csv'], + [{ name: 'data.csv', mimeType: 'application/vnd.ms-excel' }, 'csv'], + [{ name: 'report.docx', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }, 'unsupported'], + [{ name: 'sheet.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }, 'unsupported'], + [{ name: 'deck.pptx', mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }, 'unsupported'], + [{ name: 'old.doc', mimeType: 'application/msword' }, 'unsupported'], + [{ name: 'page.html', mimeType: 'text/html' }, 'unsupported'], + // A declared HTML type wins over a harmless-looking name, and the name wins + // over a declared plain-text type: neither is ever drawn or framed. + [{ name: 'page.pdf', mimeType: 'text/html' }, 'unsupported'], + [{ name: 'page.html', mimeType: 'text/plain' }, 'unsupported'], + // A PDF name with a non-PDF declared type is not framed. + [{ name: 'a.pdf', mimeType: 'application/octet-stream' }, 'unsupported'], + // The name decides only when no type is declared. + [{ name: 'a.pdf' }, 'pdf'], + [{ name: 'a.PNG' }, 'image'], + [{ name: 'File' }, 'unsupported'], + ] as Array<[FilePreviewItem, string]>)('%o → %s', (file, kind) => { + expect(filePreviewKind(file)).toBe(kind); + }); +}); + +describe('FilePreviewDialog — the four views (objectstack#36442)', () => { + it('draws an image through an img element, from the resolved link', async () => { + renderDialog({ files: [{ name: 'a.png', mimeType: 'image/png' }], resolveUrl: async () => 'https://store.example/a.png?sig=1' }); + expect(await viewOf()).toBe('image'); + const img = screen.getByRole('img', { name: 'a.png' }) as HTMLImageElement; + expect(img.src).toBe('https://store.example/a.png?sig=1'); + }); + + it('draws an SVG only through an img element: no inline svg, no iframe, no object', async () => { + const fetchSpy = vi.fn(); + renderDialog({ + files: [{ name: 'logo.svg', mimeType: 'image/svg+xml' }], + resolveUrl: async () => 'https://store.example/logo.svg', + fetchImpl: fetchSpy, + }); + expect(await viewOf()).toBe('image'); + const dialog = screen.getByTestId('file-preview-dialog'); + expect(dialog.querySelector('img')?.getAttribute('src')).toBe('https://store.example/logo.svg'); + expect(dialog.querySelector('iframe, object, embed')).toBeNull(); + // The dialog's own icons are lucide `svg`s; none carries the file. + dialog.querySelectorAll('svg').forEach((svg) => expect(svg.getAttribute('aria-hidden')).toBe('true')); + // The bytes are never fetched into the page. + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('frames a PDF on the desktop', async () => { + renderDialog({ files: [{ name: 'contract.pdf', mimeType: 'application/pdf' }], resolveUrl: async () => '/api/v1/storage/_local/raw/tok' }); + expect(await viewOf()).toBe('pdf'); + const frame = frameOf()!; + expect(frame.getAttribute('title')).toBe('contract.pdf'); + expect(frame.getAttribute('src')).toBe('/api/v1/storage/_local/raw/tok'); + }); + + it('on a phone, a PDF is offered in a new tab (the system viewer), never framed', async () => { + vi.stubGlobal('innerWidth', 375); + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + renderDialog({ files: [{ name: 'contract.pdf', mimeType: 'application/pdf' }], resolveUrl: async () => 'https://store.example/c.pdf' }); + expect(await viewOf()).toBe('pdf-outside'); + expect(screen.getByTestId('file-preview-dialog').querySelector('iframe')).toBeNull(); + const view = screen.getByTestId('file-preview-dialog').querySelector('[data-preview-state="pdf-outside"]') as HTMLElement; + fireEvent.click(within(view).getByRole('button', { name: 'Open in new tab' })); + await waitFor(() => expect(openSpy).toHaveBeenCalledWith('https://store.example/c.pdf', '_blank', 'noopener,noreferrer')); + }); + + it('on a phone, an image and a text file still preview in the page', async () => { + vi.stubGlobal('innerWidth', 375); + const fetchImpl = vi.fn(async () => textResponse('hello')); + renderDialog({ + files: [{ name: 'a.png', mimeType: 'image/png' }, { name: 'n.txt', mimeType: 'text/plain' }], + resolveUrl: async (f) => `https://store.example/${f.name}`, + fetchImpl, + }); + expect(await viewOf()).toBe('image'); + }); + + it('reads plain text through the resolved link and draws it as text, not markup', async () => { + const fetchImpl = vi.fn(async () => textResponse('line one\n\nbold')); + renderDialog({ files: [{ name: 'notes.txt', mimeType: 'text/plain' }], resolveUrl: async () => 'https://store.example/notes.txt', fetchImpl }); + expect(await viewOf()).toBe('text'); + expect(fetchImpl).toHaveBeenCalledWith('https://store.example/notes.txt', expect.anything()); + const dialog = screen.getByTestId('file-preview-dialog'); + expect(dialog.querySelector('pre')?.textContent).toContain(''); + expect(dialog.querySelector('script, b')).toBeNull(); + expect((window as unknown as { __x?: number }).__x).toBeUndefined(); + }); + + it('reads a GBK CSV with the import wizard\'s decoder and draws a table', async () => { + // 「姓名,城市\n张三,北京\n」 in GBK, as zh-CN Excel saves a CSV. + const gbk = new Uint8Array([208, 213, 195, 251, 44, 179, 199, 202, 208, 10, 213, 197, 200, 253, 44, 177, 177, 190, 169, 10]); + const fetchImpl = vi.fn(async () => textResponse(gbk)); + renderDialog({ files: [{ name: 'people.csv', mimeType: 'text/csv' }], resolveUrl: async () => 'https://store.example/p.csv', fetchImpl }); + expect(await viewOf()).toBe('csv'); + expect(screen.getByRole('columnheader', { name: '姓名' })).toBeInTheDocument(); + expect(screen.getByRole('cell', { name: '北京' })).toBeInTheDocument(); + }); + + it('shows the first 1000 rows of a long CSV and says so', async () => { + const csv = ['id,name', ...Array.from({ length: 1500 }, (_, i) => `${i},n${i}`)].join('\n'); + const fetchImpl = vi.fn(async () => textResponse(csv)); + renderDialog({ files: [{ name: 'big.csv', mimeType: 'text/csv' }], resolveUrl: async () => 'https://store.example/b.csv', fetchImpl }); + expect(await viewOf()).toBe('csv'); + expect(screen.getByText('Showing the first 1000 rows.')).toBeInTheDocument(); + // Header row + 1000 data rows. + expect(screen.getAllByRole('row')).toHaveLength(1001); + }); +}); + +describe('FilePreviewDialog — download only, and too large (objectstack#36442)', () => { + it.each([ + ['report.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], + ['sheet.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], + ['deck.pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'], + ['page.html', 'text/html'], + ])('%s offers the download only: nothing is resolved, fetched or framed', async (name, mimeType) => { + const resolveUrl = vi.fn(async () => 'https://store.example/x'); + const fetchImpl = vi.fn(); + const onDownload = vi.fn(); + renderDialog({ files: [{ name, mimeType }], resolveUrl, fetchImpl, onDownload }); + expect(await viewOf()).toBe('unsupported'); + expect(screen.getByText('This file type cannot be previewed. Please download it.')).toBeInTheDocument(); + const dialog = screen.getByTestId('file-preview-dialog'); + expect(dialog.querySelector('iframe, img, pre, table')).toBeNull(); + expect(resolveUrl).not.toHaveBeenCalled(); + expect(fetchImpl).not.toHaveBeenCalled(); + const view = dialog.querySelector('[data-preview-state="unsupported"]') as HTMLElement; + fireEvent.click(within(view).getByRole('button', { name: 'Download' })); + expect(onDownload).toHaveBeenCalledWith(expect.objectContaining({ name }), 0); + }); + + it.each([ + ['photo.png', 'image/png', 20 * MB + 1], + ['scan.pdf', 'application/pdf', 20 * MB + 1], + ['log.txt', 'text/plain', 2 * MB + 1], + ['rows.csv', 'text/csv', 2 * MB + 1], + ])('%s past its limit shows "too large" with a download, and nothing is read', async (name, mimeType, size) => { + const resolveUrl = vi.fn(async () => 'https://store.example/x'); + const fetchImpl = vi.fn(); + const onDownload = vi.fn(); + renderDialog({ files: [{ name, mimeType, size }], resolveUrl, fetchImpl, onDownload }); + expect(await viewOf()).toBe('too-large'); + expect(screen.getByText('This file is too large to preview. Please download it.')).toBeInTheDocument(); + expect(resolveUrl).not.toHaveBeenCalled(); + expect(fetchImpl).not.toHaveBeenCalled(); + const view = screen.getByTestId('file-preview-dialog').querySelector('[data-preview-state="too-large"]') as HTMLElement; + fireEvent.click(within(view).getByRole('button', { name: 'Download' })); + expect(onDownload).toHaveBeenCalledTimes(1); + }); + + it('CONTROL: at exactly its limit a file still previews', async () => { + renderDialog({ files: [{ name: 'photo.png', mimeType: 'image/png', size: 20 * MB }], resolveUrl: async () => 'https://store.example/p.png' }); + expect(await viewOf()).toBe('image'); + }); + + it('a text file whose size was not declared is judged on the bytes it answers', async () => { + const fetchImpl = vi.fn(async () => textResponse(new Uint8Array(2 * MB + 10))); + renderDialog({ files: [{ name: 'huge.txt', mimeType: 'text/plain' }], resolveUrl: async () => 'https://store.example/h.txt', fetchImpl }); + expect(await viewOf()).toBe('too-large'); + }); +}); + +describe('FilePreviewDialog — the refusal is the download\'s refusal (objectstack#36442)', () => { + it('a resolveUrl rejection is shown with its own message, for every view', async () => { + const resolveUrl = vi.fn(async () => { + throw new Error("You don't have access to download this attachment."); + }); + renderDialog({ files: [{ name: 'a.pdf', mimeType: 'application/pdf' }], resolveUrl }); + expect(await viewOf()).toBe('error'); + expect(screen.getByRole('alert')).toHaveTextContent("You don't have access to download this attachment."); + expect(screen.getByTestId('file-preview-dialog').querySelector('iframe')).toBeNull(); + }); + + it('by default, the stable storage endpoint is asked without following its redirect; a 403 is refused', async () => { + const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ success: false, error: { code: 'FILE_DOWNLOAD_DENIED' } }), { status: 403 })); + renderDialog({ files: [{ name: 'a.png', mimeType: 'image/png', url: '/api/v1/storage/files/f1' }], fetchImpl }); + expect(await viewOf()).toBe('error'); + expect(screen.getByRole('alert')).toHaveTextContent('You do not have access to this file.'); + expect(fetchImpl).toHaveBeenCalledWith('/api/v1/storage/files/f1', expect.objectContaining({ redirect: 'manual' })); + expect(screen.getByTestId('file-preview-dialog').querySelector('img')).toBeNull(); + }); + + it('CONTROL: by default, a redirect (a grant) previews the stable URL itself', async () => { + const fetchImpl = vi.fn(async () => REDIRECT); + renderDialog({ files: [{ name: 'a.png', mimeType: 'image/png', url: '/api/v1/storage/files/f1' }], fetchImpl }); + expect(await viewOf()).toBe('image'); + expect((screen.getByRole('img', { name: 'a.png' }) as HTMLImageElement).getAttribute('src')).toBe('/api/v1/storage/files/f1'); + }); + + it('a 403 on the text read is the same refusal', async () => { + const fetchImpl = vi.fn(async () => new Response('', { status: 403 })); + renderDialog({ files: [{ name: 'n.txt', mimeType: 'text/plain' }], resolveUrl: async () => 'https://store.example/n.txt', fetchImpl }); + expect(await viewOf()).toBe('error'); + expect(screen.getByRole('alert')).toHaveTextContent('You do not have access to this file.'); + }); + + it('a read the browser blocks (a bucket without CORS) offers the new tab', async () => { + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + const fetchImpl = vi.fn(async () => { + throw new TypeError('Failed to fetch'); + }); + renderDialog({ files: [{ name: 'p.csv', mimeType: 'text/csv' }], resolveUrl: async () => 'https://bucket.example/p.csv?sig=1', fetchImpl }); + expect(await viewOf()).toBe('blocked'); + const view = screen.getByTestId('file-preview-dialog').querySelector('[data-preview-state="blocked"]') as HTMLElement; + fireEvent.click(within(view).getByRole('button', { name: 'Open in new tab' })); + await waitFor(() => expect(openSpy).toHaveBeenCalledWith('https://bucket.example/p.csv?sig=1', '_blank', 'noopener,noreferrer')); + }); +}); + +describe('FilePreviewDialog — previous, next, download, new tab (objectstack#36442)', () => { + const files: FilePreviewItem[] = [ + { id: 'f1', name: 'a.png', mimeType: 'image/png' }, + { id: 'f2', name: 'b.pdf', mimeType: 'application/pdf' }, + { id: 'f3', name: 'c.docx', mimeType: 'application/msword' }, + ]; + + it('previous and next walk the set and wrap; the arrow keys do the same', () => { + const onIndexChange = vi.fn(); + renderDialog({ files, index: 0, onIndexChange, resolveUrl: async (f) => `https://s/${f.id}` }); + expect(screen.getByText('1 / 3')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Next file' })); + expect(onIndexChange).toHaveBeenLastCalledWith(1); + fireEvent.click(screen.getByRole('button', { name: 'Previous file' })); + expect(onIndexChange).toHaveBeenLastCalledWith(2); + fireEvent.keyDown(screen.getByTestId('file-preview-dialog'), { key: 'ArrowRight' }); + expect(onIndexChange).toHaveBeenLastCalledWith(1); + }); + + it('each file gets its own view and its own link as the index moves', async () => { + const resolveUrl = vi.fn(async (f: FilePreviewItem) => `https://s/${f.id}`); + const { rerender } = renderDialog({ files, index: 0, resolveUrl }); + expect(await viewOf()).toBe('image'); + rerender( + + {}} resolveUrl={resolveUrl} /> + , + ); + await waitFor(() => expect(frameOf()?.getAttribute('src')).toBe('https://s/f2')); + expect(screen.getByTestId('file-preview-dialog').querySelector('img')).toBeNull(); + }); + + it('a single file draws no previous / next', () => { + renderDialog({ files: [files[0]!], resolveUrl: async () => 'https://s/f1' }); + expect(screen.queryByRole('button', { name: 'Next file' })).toBeNull(); + expect(screen.queryByText('1 / 1')).toBeNull(); + }); + + it('the header download hands the file to onDownload; the new tab opens the resolved link', async () => { + const onDownload = vi.fn(); + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + renderDialog({ files, index: 1, onDownload, resolveUrl: async (f) => `https://s/${f.id}` }); + const header = screen.getByTestId('file-preview-dialog'); + fireEvent.click(within(header).getAllByRole('button', { name: 'Download' })[0]!); + expect(onDownload).toHaveBeenCalledWith(files[1], 1); + fireEvent.click(within(header).getAllByRole('button', { name: 'Open in new tab' })[0]!); + await waitFor(() => expect(openSpy).toHaveBeenCalledWith('https://s/f2', '_blank', 'noopener,noreferrer')); + }); +}); + +describe('FileValueAffordance — a file field opens the preview (objectstack#36442)', () => { + function renderAffordance(value: unknown) { + return render( + +
    + none} /> +
    +
    , + ); + } + const rowClick = vi.fn(); + + it('a plain click opens the dialog in the page, on the same link the download uses', async () => { + rowClick.mockClear(); + vi.stubGlobal('fetch', vi.fn(async () => REDIRECT)); + renderAffordance({ id: 'f9', name: 'scan.pdf', mimeType: 'application/pdf', url: '/api/v1/storage/files/f9' }); + const link = screen.getByRole('link', { name: 'scan.pdf' }); + expect(link.getAttribute('href')).toBe('/api/v1/storage/files/f9'); + fireEvent.click(link); + expect(await viewOf()).toBe('pdf'); + expect(frameOf()?.getAttribute('src')).toBe('/api/v1/storage/files/f9'); + expect(rowClick).not.toHaveBeenCalled(); + // A click inside the dialog does not reach the row behind it either. + fireEvent.click(screen.getAllByRole('button', { name: 'Download' })[0]!); + expect(rowClick).not.toHaveBeenCalled(); + }); + + it('a modified click keeps the browser\'s own new tab and opens no dialog', () => { + renderAffordance({ id: 'f9', name: 'scan.pdf', mimeType: 'application/pdf', url: '/api/v1/storage/files/f9' }); + fireEvent.click(screen.getByRole('link', { name: 'scan.pdf' }), { ctrlKey: true }); + expect(screen.queryByTestId('file-preview-dialog')).toBeNull(); + }); + + it('a field file the reader may not download gets the refusal in the preview', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 403 }))); + renderAffordance({ id: 'f9', name: 'scan.png', mimeType: 'image/png', url: '/api/v1/storage/files/f9' }); + fireEvent.click(screen.getByRole('link', { name: 'scan.png' })); + expect(await viewOf()).toBe('error'); + expect(screen.getByRole('alert')).toHaveTextContent('You do not have access to this file.'); + }); + + it('a Word file from a field offers the download only', async () => { + renderAffordance({ id: 'f9', name: 'memo.docx', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', url: '/api/v1/storage/files/f9' }); + fireEvent.click(screen.getByRole('link', { name: 'memo.docx' })); + expect(await viewOf()).toBe('unsupported'); + }); +}); diff --git a/ui/packages/fields/src/widgets/FilePreviewDialog.tsx b/ui/packages/fields/src/widgets/FilePreviewDialog.tsx new file mode 100644 index 00000000000..7d1e2f8dc3d --- /dev/null +++ b/ui/packages/fields/src/widgets/FilePreviewDialog.tsx @@ -0,0 +1,576 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The console's in-page file preview: one dialog for a record's attachments + * and for a file field's value (decision objectstack#34781, option A). + * + * Four views and nothing else, with no new dependency: + * - image (PNG, JPEG, GIF, WebP, and SVG): the lightbox's own `img` element. + * ⛔ An SVG is never inlined: an `img` element runs no script. + * - PDF: an `iframe` on the browser's own viewer. On a phone the dialog + * offers the new tab instead, which hands the file to the system viewer. + * - plain text: the bytes decoded and drawn as text. + * - CSV: the same GBK-aware decode and delimited parser the grid's import + * wizard reads with (`delimitedText.ts`), drawn as a table. + * Every other type, Word, Excel, PowerPoint and HTML included, is the + * "unsupported, please download" state. ⛔ An `iframe` is only ever pointed at + * a file judged PDF, never at HTML or SVG. + * + * Past a size limit (images and PDF 20 MB; text and CSV 2 MB) the dialog draws + * "too large, please download"; text and CSV show their first 1000 lines. + * + * The preview reads the file through the SAME door as the download: the + * caller's `resolveUrl` (the attachments panel mints the signed link exactly as + * its download does) or, by default, the file's own URL — the stable storage + * endpoint, probed without following its redirect so a refusal reads as the + * download's refusal. When the browser cannot read a file in the page (a + * bucket on another origin without the CORS rule the preview needs), the + * dialog offers the new tab instead. + */ + +import * as React from 'react'; +import { + Button, + cn, + Dialog, + DialogDescription, + DialogTitle, + MobileDialogContent, + useIsMobile, +} from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { AlertTriangle, ChevronLeft, ChevronRight, Download, ExternalLink, FileX, Loader2 } from 'lucide-react'; +import { LightboxImageView } from './ImageLightbox.js'; +import { decodeSpreadsheetText, parseDelimited } from './delimitedText.js'; + +/** One file the dialog can show. A `FileValueView` satisfies it as it is. */ +export interface FilePreviewItem { + /** + * The file's stable identity (a `sys_file` id). With `url`, it is what the + * dialog remembers a resolved link by, so pass it when there is no `url`. + */ + id?: string; + /** Display name; its extension decides the view when no MIME type is known. */ + name: string; + /** Where the bytes are. Optional when the caller passes `resolveUrl`. */ + url?: string; + /** Declared MIME type; decides the view when present. */ + mimeType?: string; + /** Size in bytes, when known: a file past its limit is never fetched. */ + size?: number; +} + +export interface FilePreviewDialogProps { + files: FilePreviewItem[]; + /** Index of the file shown. Controlled, like `ImageLightbox`. */ + index: number; + open: boolean; + onOpenChange: (open: boolean) => void; + /** Called on previous / next (buttons and arrow keys). Without it the set does not move. */ + onIndexChange?: (index: number) => void; + /** + * The link the preview reads, minted by the same check as the download. + * A rejection is the refusal: its `message` is shown as it is, so pass the + * copy the download would have shown. Default: the file's own `url`. + */ + resolveUrl?: (file: FilePreviewItem, index: number) => Promise; + /** The download. Default: a link to the resolved URL with `download` set. */ + onDownload?: (file: FilePreviewItem, index: number) => void; + /** The fetch used to read text and CSV, and to probe the default URL. */ + fetchImpl?: typeof fetch; +} + +/** + * The English copy, as the `en` pack says it: what a host without a loaded + * catalogue still shows (`t`'s `defaultValue`), never a bare key. + */ +const DEFAULT_COPY: Record = { + 'fields.filePreview.title': 'File preview', + 'fields.filePreview.previous': 'Previous file', + 'fields.filePreview.next': 'Next file', + 'fields.filePreview.download': 'Download', + 'fields.filePreview.openInNewTab': 'Open in new tab', + 'fields.filePreview.loading': 'Loading preview…', + 'fields.filePreview.tooLarge': 'This file is too large to preview. Please download it.', + 'fields.filePreview.unsupported': 'This file type cannot be previewed. Please download it.', + 'fields.filePreview.denied': 'You do not have access to this file.', + 'fields.filePreview.loadFailed': 'The preview could not be loaded.', + 'fields.filePreview.blocked': 'This file cannot be read in the page. Open it in a new tab instead.', + 'fields.filePreview.pdfOutside': 'On this device, a PDF opens in a new tab or in the device viewer.', + 'fields.filePreview.truncatedRows': 'Showing the first {{limit}} rows.', + 'fields.filePreview.truncatedLines': 'Showing the first {{limit}} lines.', + 'fields.filePreview.empty': 'This file is empty.', + 'fields.image.counter': '{{current}} / {{total}}', +}; + +type PreviewKind = 'image' | 'pdf' | 'text' | 'csv' | 'unsupported'; + +const MB = 1024 * 1024; +const MEDIA_LIMIT_BYTES = 20 * MB; +const TEXT_LIMIT_BYTES = 2 * MB; +const TEXT_ROW_LIMIT = 1000; + +const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml']); +const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg']); +const CSV_TYPES = new Set(['text/csv', 'application/csv', 'text/x-csv', 'text/comma-separated-values']); +/** Types a `.csv` file is commonly uploaded under besides its own. */ +const CSV_LOOSE_TYPES = new Set(['', 'text/plain', 'application/vnd.ms-excel', 'application/octet-stream']); +const TEXT_EXTENSIONS = new Set(['txt', 'log']); + +function extensionOf(name: string): string { + const dot = name.lastIndexOf('.'); + return dot < 0 ? '' : name.slice(dot + 1).toLowerCase(); +} + +/** A MIME type's essence: lower case, parameters dropped. */ +function essenceOf(mimeType?: string): string { + return (mimeType ?? '').split(';')[0]!.trim().toLowerCase(); +} + +/** + * The view a file gets. The declared type decides; the extension only fills + * in where no type is declared, except for the text views, which draw bytes as + * text and so cannot execute anything whatever the bytes are. + * + * ⛔ HTML is unsupported, never text and never framed. ⛔ PDF needs a PDF + * signal: the declared type, or the extension when nothing is declared — the + * `iframe` is the one view that hands bytes to the browser to interpret. + */ +export function filePreviewKind(file: FilePreviewItem): PreviewKind { + const type = essenceOf(file.mimeType); + const ext = extensionOf(file.name); + if (type === 'text/html' || type === 'application/xhtml+xml' || ext === 'html' || ext === 'htm') return 'unsupported'; + if (CSV_TYPES.has(type) || (ext === 'csv' && CSV_LOOSE_TYPES.has(type))) return 'csv'; + if (type === 'text/plain' || (!type && TEXT_EXTENSIONS.has(ext))) return 'text'; + if (IMAGE_TYPES.has(type) || (!type && IMAGE_EXTENSIONS.has(ext))) return 'image'; + if (type === 'application/pdf' || (!type && ext === 'pdf')) return 'pdf'; + return 'unsupported'; +} + +function limitFor(kind: PreviewKind): number { + return kind === 'text' || kind === 'csv' ? TEXT_LIMIT_BYTES : MEDIA_LIMIT_BYTES; +} + +type BodyState = + | { status: 'loading' } + | { status: 'ready'; url: string; text?: string; rows?: string[][]; truncated?: boolean } + /** Refused or failed: the message says which. */ + | { status: 'error'; message: string } + /** The browser could not read the bytes in the page (cross-origin without CORS). */ + | { status: 'blocked' } + | { status: 'tooLarge' }; + +/** An error whose message is already the copy to show. */ +class PreviewRefusal extends Error {} + +/** What a file is remembered by: primitives, never the item object (ui/AGENTS.md #10). */ +function fileKey(file: FilePreviewItem, index: number): string { + return JSON.stringify([file.id ?? null, file.url ?? null, file.id || file.url ? null : index, file.name]); +} + +function isSameOrigin(url: string): boolean { + if (typeof window === 'undefined') return false; + try { + return new URL(url, window.location.href).origin === window.location.origin; + } catch { + return false; + } +} + +/** + * Hook state for one dialog: resolves each file's URL once and remembers it, + * so previous / next and the header's buttons never mint twice. + */ +function useResolver( + resolveUrl: FilePreviewDialogProps['resolveUrl'], + fetchImpl: typeof fetch, + t: (key: string, params?: Record) => string, +) { + const cache = React.useRef(new Map>()); + // Read through a ref, so the resolver is ONE function for the dialog's life: + // the view's effect keys on it, and a caller's fresh closure each render + // must not re-run a read (nor, after a refusal, re-ask in a loop). + // Refreshed in an effect declared before the dialog's own read effect, so + // that read always sees this render's values. + const latest = React.useRef({ resolveUrl, fetchImpl, t }); + React.useEffect(() => { + latest.current = { resolveUrl, fetchImpl, t }; + }); + return React.useCallback( + (file: FilePreviewItem, index: number): Promise => { + const { resolveUrl, fetchImpl, t } = latest.current; + const key = fileKey(file, index); + const hit = cache.current.get(key); + if (hit) return hit; + const run = (async () => { + if (resolveUrl) return resolveUrl(file, index); + const url = file.url?.trim(); + if (!url) throw new PreviewRefusal(t('fields.filePreview.loadFailed')); + // The stable storage endpoint answers a refusal itself and a grant with + // a redirect to the signed link: ask it without following, so the + // answer is the download's answer and no byte moves twice. + if (isSameOrigin(url)) { + let res: Response | undefined; + try { + res = await fetchImpl(url, { redirect: 'manual', credentials: 'same-origin' }); + } catch { + res = undefined; // Unreadable here; the view itself will say so. + } + if (res) { + void res.body?.cancel().catch(() => undefined); + if (res.status === 401 || res.status === 403) throw new PreviewRefusal(t('fields.filePreview.denied')); + if (res.status >= 400) throw new PreviewRefusal(t('fields.filePreview.loadFailed')); + } + } + return url; + })(); + cache.current.set(key, run); + // A failed resolution is not remembered: the next try asks again. + run.catch(() => cache.current.delete(key)); + return run; + }, + [], + ); +} + +/** Read a text or CSV file's bytes through the resolved link. */ +async function readTextBody( + url: string, + kind: 'text' | 'csv', + fetchImpl: typeof fetch, + signal: AbortSignal, + t: (key: string, params?: Record) => string, +): Promise { + let res: Response; + try { + res = await fetchImpl(url, { credentials: 'same-origin', signal }); + } catch (err) { + if (signal.aborted) throw err; + return { status: 'blocked' }; + } + if (res.status === 401 || res.status === 403) return { status: 'error', message: t('fields.filePreview.denied') }; + if (!res.ok) return { status: 'error', message: t('fields.filePreview.loadFailed') }; + const declared = Number(res.headers.get('content-length')); + if (Number.isFinite(declared) && declared > TEXT_LIMIT_BYTES) { + void res.body?.cancel().catch(() => undefined); + return { status: 'tooLarge' }; + } + const buffer = await res.arrayBuffer(); + if (buffer.byteLength > TEXT_LIMIT_BYTES) return { status: 'tooLarge' }; + const text = decodeSpreadsheetText(buffer); + if (kind === 'csv') { + const rows = parseDelimited(text, ','); + // The header row plus the first 1000 data rows. + return { status: 'ready', url, rows: rows.slice(0, TEXT_ROW_LIMIT + 1), truncated: rows.length > TEXT_ROW_LIMIT + 1 }; + } + const lines = text.split(/\r?\n/); + return { + status: 'ready', + url, + text: lines.slice(0, TEXT_ROW_LIMIT).join('\n'), + truncated: lines.length > TEXT_ROW_LIMIT, + }; +} + +/** + * A shared preview dialog for files: previous / next across `files`, download, + * open in a new tab, and one of the four views — or the "too large" or + * "unsupported" state, both of which offer the download. + */ +export function FilePreviewDialog({ + files, + index, + open, + onOpenChange, + onIndexChange, + resolveUrl, + onDownload, + fetchImpl, +}: FilePreviewDialogProps) { + const { t: translate } = useObjectTranslation(); + const tr = React.useCallback( + (key: string, params?: Record) => + (translate as (k: string, p?: Record) => string)(key, { defaultValue: DEFAULT_COPY[key], ...params }), + [translate], + ); + const t = tr; + const isMobile = useIsMobile(); + const doFetch = fetchImpl ?? ((...args: Parameters) => fetch(...args)); + const resolve = useResolver(resolveUrl, doFetch, tr); + const count = files.length; + const file = files[index]; + const kind: PreviewKind = file ? filePreviewKind(file) : 'unsupported'; + const tooLargeByDeclaration = !!file && typeof file.size === 'number' && file.size > limitFor(kind); + const pdfOutside = kind === 'pdf' && isMobile; + const needsBody = open && !!file && kind !== 'unsupported' && !tooLargeByDeclaration && !pdfOutside; + + const key = file ? fileKey(file, index) : ''; + // Each answer carries the key of the file it is about, so a file never + // draws the previous file's answer while its own is on the way. + const [answer, setAnswer] = React.useState<{ key: string; state: BodyState; url?: string }>({ + key: '', + state: { status: 'loading' }, + }); + const state: BodyState = answer.key === key ? answer.state : { status: 'loading' }; + const resolvedUrl = answer.key === key ? answer.url : undefined; + const setState = React.useCallback( + (next: BodyState, url?: string) => setAnswer((prev) => ({ key, state: next, url: url ?? (prev.key === key ? prev.url : undefined) })), + [key], + ); + + React.useEffect(() => { + if (!needsBody || !file) return; + const controller = new AbortController(); + let live = true; + (async () => { + let url: string; + try { + url = await resolve(file, index); + } catch (err) { + if (!live) return; + const message = err instanceof Error && err.message ? err.message : tr('fields.filePreview.loadFailed'); + setState({ status: 'error', message }); + return; + } + if (!live) return; + if (kind === 'text' || kind === 'csv') { + try { + const next = await readTextBody(url, kind, doFetch, controller.signal, tr); + if (live) setState(next, url); + } catch { + if (live) setState({ status: 'error', message: tr('fields.filePreview.loadFailed') }, url); + } + return; + } + setState({ status: 'ready', url }, url); + })(); + return () => { + live = false; + controller.abort(); + }; + // Keyed on the file's primitives (`key`), never on the item object (ui/AGENTS.md #10); + // `doFetch` and `tr` are read through the run. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [needsBody, key, kind, resolve, setState]); + + const go = React.useCallback( + (delta: number) => { + if (count <= 1) return; + onIndexChange?.((index + delta + count) % count); + }, + [count, index, onIndexChange], + ); + + const openInNewTab = React.useCallback(async () => { + if (!file) return; + try { + const url = resolvedUrl ?? (await resolve(file, index)); + window.open(url, '_blank', 'noopener,noreferrer'); + } catch (err) { + setState({ + status: 'error', + message: err instanceof Error && err.message ? err.message : tr('fields.filePreview.loadFailed'), + }); + } + }, [file, index, resolvedUrl, resolve, setState, tr]); + + const download = React.useCallback(async () => { + if (!file) return; + if (onDownload) { + onDownload(file, index); + return; + } + try { + const url = resolvedUrl ?? (await resolve(file, index)); + const a = document.createElement('a'); + a.href = url; + a.download = file.name; + a.target = '_blank'; + a.rel = 'noopener noreferrer'; + document.body.appendChild(a); + a.click(); + a.remove(); + } catch (err) { + setState({ + status: 'error', + message: err instanceof Error && err.message ? err.message : tr('fields.filePreview.loadFailed'), + }); + } + }, [file, index, onDownload, resolvedUrl, resolve, setState, tr]); + + const handleKeyDown = React.useCallback( + (e: React.KeyboardEvent) => { + // Stopped too: a grid row behind a portal still hears React's bubble. + if (e.key === 'ArrowRight') { + e.preventDefault(); + e.stopPropagation(); + go(1); + } else if (e.key === 'ArrowLeft') { + e.preventDefault(); + e.stopPropagation(); + go(-1); + } + }, + [go], + ); + + if (!file) return null; + + const notice = (icon: React.ReactNode, message: string, slot: string, extra?: React.ReactNode) => ( +
    + {icon} +

    {message}

    + {extra} +
    + ); + const downloadButton = ( + + ); + const newTabButton = ( + + ); + + let body: React.ReactNode; + if (kind === 'unsupported') { + body = notice(