Skip to content

Commit 9c283a1

Browse files
feat(console): preview images, PDF, text and CSV in the page from attachments and file fields (#36587)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_ Fixes #36442 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 控制台用户在记录的附件列表点文件名、或在文件字段点文件链接时,图片、PDF、纯文本和表格文件直接在页面弹窗里看,不再先下载;Word、Excel、PPT 仍只能下载。 - 这是附件预览决策选定的方案甲(页内预览,社区版默认)的界面半边,服务端那半边由同区另一张卡负责。 - 若出错,最坏是预览打不开、用户点弹窗里的下载或新标签页照旧拿到文件;没有下载权限的人在预览里同样被拒;可整体撤回。 - 要你做的:无。 ## What changes A shared `FilePreviewDialog` in `@object-ui/fields` (decision #34781, option A), opened from a record's attachments and from a file field: - **Views, no new dependency.** Image (PNG, JPEG, GIF, WebP, and SVG through an `img` element only) via the lightbox's own image element (`LightboxImageView`, extracted from `ImageLightbox`); PDF in an `iframe` on the browser's own viewer, without a `sandbox` attribute; plain text as text; CSV as a table, read with the GBK-aware `decodeSpreadsheetText` and `parseDelimited`, which moved down from `@object-ui/plugin-grid` (it now imports them from `@object-ui/fields`; no copy). - **Download only.** Word, Excel, PowerPoint, HTML and every other type: "This file type cannot be previewed. Please download it." HTML was measured as a choice between "unsupported" and "source as text"; this PR takes **unsupported**: nothing is fetched, nothing is framed, nothing is drawn. A declared HTML type wins over a harmless name, and an `.html` name wins over a declared plain-text type. - **The PDF frame needs a PDF signal**: the declared `application/pdf`, or a `.pdf` name when no type is declared. A `.pdf` name with another declared type (for example `application/octet-stream`) is unsupported, so the frame never receives bytes the browser would read as anything else. - **Limits** (maintainer defaults): images and PDF 20 MB, text and CSV 2 MB, judged on the declared size before anything is fetched and on the bytes read when no size is declared; text and CSV show their first 1000 lines (CSV: header plus 1000 rows). Past a limit: "too large, please download" with a download button. - **Controls**: previous / next (and the arrow keys) across a record's attachments; download; open in a new tab. - **Same door as the download.** In the attachments panel the preview mints its link with the download's own call (`/files/:id/url` with the console's token, now one `signedUrlFor` both use), and a refusal shows the download's own copy. On a file field the preview uses the field's own link (the stable `/files/:id` endpoint) and first asks it with `redirect: 'manual'`: a redirect is the grant, a 401/403 is the refusal, so no byte moves twice. - **Phone**: below the `useIsMobile` breakpoint a PDF is offered in a new tab (the system viewer), never framed; image, text and CSV stay in the page. - **Cross-origin bucket** (the contract in #36443 / #36565): text and CSV are read with a `GET` on the signed link from the page; when the browser refuses that read (no bucket CORS rule for the console origin), the dialog offers "Open in new tab" instead. - **Wiring**: `RecordAttachmentsPanel`, the row's name is now a button that opens the preview (download stays in the row's menu); `FileValueAffordance` (`file-affordance.tsx`), a plain click opens the preview, a modified click keeps the link's own new tab, and a click inside the dialog does not bubble to the grid row behind its portal. - **Copy**: 15 new keys under `fields.filePreview` in all 12 packs (zh-Hant regenerated from zh-Hans by its generator). New public exports from `@object-ui/fields` (preferred names, built under them): `FilePreviewDialog`, `FilePreviewDialogProps`, `FilePreviewItem`, `decodeSpreadsheetText`, `parseDelimited`. Alternatives considered: `FileViewerDialog` / `FileViewerDialogProps` / `FileViewerItem`. New `@object-ui/i18n` keys (every pack): `fields.filePreview.title`, `fields.filePreview.previous`, `fields.filePreview.next`, `fields.filePreview.download`, `fields.filePreview.openInNewTab`, `fields.filePreview.loading`, `fields.filePreview.tooLarge`, `fields.filePreview.unsupported`, `fields.filePreview.denied`, `fields.filePreview.loadFailed`, `fields.filePreview.blocked`, `fields.filePreview.pdfOutside`, `fields.filePreview.truncatedRows`, `fields.filePreview.truncatedLines`, `fields.filePreview.empty`. Read first, by risk: `filePreviewKind` (which bytes may reach the `iframe`), `useResolver` in `FilePreviewDialog.tsx` (the refusal probe and the one-resolver-per-dialog rule), then `previewSignedUrl` / `signedUrlFor` in `RecordAttachmentsPanel.tsx`. Two-minute check: `pnpm --dir ui exec vitest run packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx` shows 51 passing. ## Tests - New card-named file `ui/packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx`: the kind table (Office, HTML, SVG, PDF-signal cases); each view and its element; SVG only as `img`, no `iframe`/`object`, bytes never fetched; text drawn as text (a script tag in the file stays text); GBK CSV; the 1000-row cap; Office and HTML download only with nothing resolved, fetched or framed; too large per kind, a control at exactly the limit, and a text file judged on its bytes; the refusal from `resolveUrl`, from the default probe (403), from the text read (403), with a redirect as the control; the CORS-blocked read offering the new tab; previous / next / arrow keys / wrap; download and new tab; phone PDF in a new tab and phone image in the page; the field link opening the preview, a modified click not, a refused field file, a Word field file. - Shared harness `RecordAttachmentsPanel.test.tsx`, new top-level `describe`: the name opens the preview on the signed link, next walks to the next row's own link, a refused reader gets the download's copy (and the link is asked once), a Word file offers only the download and that download is the row menu's, the row menu still carries Download. - Shared harness `importParsers.test.ts`, new `describe`: the wizard's `parseDelimited` / `decodeSpreadsheetText` are the very functions `@object-ui/fields` exports. - Tests changed because the product changed: none. Existing pins that query `getByText('report.pdf')` keep passing on the new name button. ## Acceptance notes - **Multi-file field values preview one file at a time.** A file field holding several files opens each file's own preview without previous / next across the value: the group lives at the call sites in `FileField.tsx` and the cell renderer in the fields barrel, outside this card's claimed file surface. The attachments panel walks its whole list. - "Phone" is the console's viewport breakpoint (`useIsMobile`, under 768 px), not a device check. - #36518 (open): answers stored bytes outside an inline allow-list as attachments, keeps PDF and plain text inline. Effect here: none on the in-page views (the text and CSV views read bytes with `fetch`, which ignores the disposition; #36565 measured Chromium mounting its PDF viewer under that PR's sandbox header). The "Open in new tab" for a CSV would download it rather than display it once #36518 lands. - On S3, the PDF frame needs #36565's `frame-src` and the text and CSV reads need the bucket CORS rule #36443 documents; without them the dialog offers the new tab, as that card's contract states. - The pre-existing `FILE_DOWNLOAD_DENIED` (field-owned files) has no friendly copy in the attachments panel's mapper; the panel only maps `ATTACHMENT_DOWNLOAD_DENIED`. The preview shows exactly what the download shows. Observation only. ## Verification Screenshots: NOT MEASURED. Reason: the relay writes text bodies only and no write door here uploads an image to a pull request; a live Console run was not started in this container. <details><summary>Package suites on the merged head (ab1feda, then c131bca and 81b19aa for the census fixes)</summary> ``` pnpm --dir ui exec vitest run packages/fields/ packages/plugin-grid/ packages/i18n/ (merged head 538f09f) Test Files 1 failed | 735 passed | 1 skipped (737) the zh-Hant pack is generated: regenerated in ab1feda pnpm --dir ui exec vitest run packages/i18n/ FilePreviewDialog-36442 RecordAttachmentsPanel.test importParsers.test (ab1feda) Test Files 109 passed (109) Tests 2138 passed | 13 skipped (2151) pnpm --dir ui exec vitest run scripts/ packages/plugin-grid/src/importParsers.test.ts (c131bca) Test Files 173 passed | 2 skipped (175) Tests 5185 passed | 2 skipped (5187) pnpm --dir ui exec vitest run dialogViewportGutterCensus-12603 clickableNonControlCensus-13461 FilePreviewDialog-36442 fileCellDownload-9485 RecordAttachmentsPanel.test (81b19aa) Test Files 5 passed (5) Tests 129 passed (129) pnpm --filter @object-ui/{fields,i18n,plugin-grid,app-shell} type-check TC-OK on all four ``` </details> <details><summary>Ablation: delete the default probe's refusal (one line in useResolver)</summary> ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob 1697ea6 -> 6bf8a8ebcffc × by default, the stable storage endpoint is asked without following its redirect; a 403 is refused × a field file the reader may not download gets the refusal in the preview Tests 2 failed | 49 passed (51) ablation-replace: ok restored: blob == HEAD (1697ea6) and `git diff HEAD` is empty ``` </details> <details><summary>Derived gate list on 81b19aa: 42 of 42 run, all exit 0</summary> `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE`: "42 derived famil(ies) accounted for — 42 run, 0 NOT-MEASURED". `check:type-check-debt` and the ui `scripts/` suite ran under the shared verify lock. `node scripts/pm/overlap-check.mjs`: VERDICT clean exit 0. </details> CI on 81b19aa: every required check green (Lint & Repo Gates, TypeScript Type Check, Test Core, Governed Surface Queue Guard, Lint UI, Type Check UI, Test UI, Build & E2E UI, Live E2E UI, Dogfood Regression Gate; Build Core skipped by its selector). Two shared censuses the first CI round named are now satisfied without touching them: the dialog's width is `sm:max-w-[92vw] xl:max-w-5xl`, a viewport-relative cap that keeps a margin at every width (the gutter census counts it as not wide), and the dialog stops its own clicks at its content rather than through a clickable wrapper element (the clickable-non-control census). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRB34k9WUWeGpRnVNm --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 93d8921 commit 9c283a1

22 files changed

Lines changed: 1516 additions & 103 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@object-ui/fields': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/plugin-grid': patch
5+
'@object-ui/i18n': patch
6+
---
7+
8+
feat(console): preview images, PDF, text and CSV in the page from a record's attachments and from a file field
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
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.
14+
15+
- **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.
16+
- **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.
17+
- **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.
18+
- **Controls.** Previous and next (and the arrow keys) walk a record's attachments; download; open in a new tab.
19+
- **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.
20+
21+
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).
22+
23+
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`.
24+
25+
No metadata key, value or default changes.

‎ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx‎

Lines changed: 97 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { createAuthenticatedFetch, useAuth } from '@object-ui/auth';
4646
import { useDisplayLocale } from '@object-ui/i18n';
4747
import { useObjectTranslation, isPermissionError, classifyLoadError } from '@object-ui/react';
4848
import { usePermissions } from '@object-ui/permissions';
49+
import { FilePreviewDialog, type FilePreviewItem } from '@object-ui/fields';
4950
import { resolveAffordance, type ConfirmationHandler } from '@object-ui/core';
5051
import {
5152
NATIVE_FILE_MAX_BYTES,
@@ -77,6 +78,9 @@ import { RECORD_PAGE_ATTACHMENT_ROWS, recordAttachmentsCountField } from './reco
7778
* Downloads fetch a short-lived signed URL from `/storage/files/:fileId/url`
7879
* with the console's Bearer token (the endpoint requires an authenticated
7980
* session for attachments-scope files, objectstack-ai/objectstack#2970), then open it.
81+
* A row's NAME opens the file in the page (`FilePreviewDialog`, objectstack#36442),
82+
* which mints its link through that same door, so a reader the download refuses
83+
* is refused the same way; the download itself stays in the row's ⋮ menu.
8084
*
8185
* The list read expands `uploaded_by` (the record page payload's attachments
8286
* part does the same), so the uploader column names whoever uploaded a row
@@ -626,51 +630,85 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
626630
[callAttachmentDoor, friendlyError, t],
627631
);
628632

633+
/**
634+
* The signed link for a row: the one door both the download and the preview
635+
* read through. Throws the server's code on a refusal.
636+
*/
637+
const signedUrlFor = React.useCallback(
638+
async (row: AttachmentRow): Promise<string> => {
639+
// The stable `/files/:fileId` endpoint now requires an authenticated
640+
// session for attachments-scope files (objectstack-ai/objectstack#2970) — an <a href> can't
641+
// carry the Bearer token. Fetch a short-lived signed URL with auth,
642+
// then open it (the signed URL itself needs no credentials).
643+
const res = await authFetch(
644+
`${baseUrl}/api/v1/storage/files/${encodeURIComponent(row.file_id)}/url`,
645+
);
646+
if (!res.ok) {
647+
let code: string | undefined;
648+
try {
649+
// Read BOTH error dialects, the same way the success branch below
650+
// reads both `url` shapes. The storage service moved its error
651+
// code from a sibling of `error` into the declared
652+
// `{ success: false, error: { code, message } }` envelope
653+
// (objectstack#3675); a console build is deployed independently of
654+
// the server it talks to, so it has to keep understanding the
655+
// older top-level `code` too. Without the nested branch the 401/403
656+
// downgrade silently to "Download failed (403)" and the friendly
657+
// copy below never fires.
658+
const body = (await res.json()) as { code?: string; error?: { code?: string } } | null;
659+
code = body?.error?.code ?? body?.code;
660+
} catch {
661+
/* non-JSON body */
662+
}
663+
throw Object.assign(new Error(code ?? `Download failed (${res.status})`), { code });
664+
}
665+
const body = await res.json();
666+
// Both URL dialects, for the same independent-deploy reason as the
667+
// error branch above: the route answered a bare `{ url }` until
668+
// objectstack#3689 moved it into the declared
669+
// `{ success: true, data: { url } }` envelope.
670+
const url: string | undefined = body?.url ?? body?.data?.url;
671+
if (!url) throw new Error('Download URL missing from response');
672+
return /^https?:/i.test(url) ? url : `${baseUrl}${url}`;
673+
},
674+
[authFetch, baseUrl],
675+
);
676+
629677
const handleDownload = React.useCallback(
630678
async (row: AttachmentRow) => {
631679
setError(null);
632680
try {
633-
// The stable `/files/:fileId` endpoint now requires an authenticated
634-
// session for attachments-scope files (objectstack-ai/objectstack#2970) — an <a href> can't
635-
// carry the Bearer token. Fetch a short-lived signed URL with auth,
636-
// then open it (the signed URL itself needs no credentials).
637-
const res = await authFetch(
638-
`${baseUrl}/api/v1/storage/files/${encodeURIComponent(row.file_id)}/url`,
639-
);
640-
if (!res.ok) {
641-
let code: string | undefined;
642-
try {
643-
// Read BOTH error dialects, the same way the success branch below
644-
// reads both `url` shapes. The storage service moved its error
645-
// code from a sibling of `error` into the declared
646-
// `{ success: false, error: { code, message } }` envelope
647-
// (objectstack#3675); a console build is deployed independently of
648-
// the server it talks to, so it has to keep understanding the
649-
// older top-level `code` too. Without the nested branch the 401/403
650-
// downgrade silently to "Download failed (403)" and the friendly
651-
// copy below never fires.
652-
const body = (await res.json()) as { code?: string; error?: { code?: string } } | null;
653-
code = body?.error?.code ?? body?.code;
654-
} catch {
655-
/* non-JSON body */
656-
}
657-
throw Object.assign(new Error(code ?? `Download failed (${res.status})`), { code });
658-
}
659-
const body = await res.json();
660-
// Both URL dialects, for the same independent-deploy reason as the
661-
// error branch above: the route answered a bare `{ url }` until
662-
// objectstack#3689 moved it into the declared
663-
// `{ success: true, data: { url } }` envelope.
664-
const url: string | undefined = body?.url ?? body?.data?.url;
665-
if (!url) throw new Error('Download URL missing from response');
666-
const target = /^https?:/i.test(url) ? url : `${baseUrl}${url}`;
681+
const target = await signedUrlFor(row);
667682
if (await openInNativeShell(target, row)) return;
668683
window.open(target, '_blank', 'noopener,noreferrer');
669684
} catch (err: any) {
670685
setError(friendlyError(err));
671686
}
672687
},
673-
[authFetch, baseUrl, friendlyError],
688+
[signedUrlFor, friendlyError],
689+
);
690+
691+
// The in-page preview (objectstack#36442): the row whose name was clicked,
692+
// and the rows as the dialog's set, so previous / next walk the list.
693+
const [previewIndex, setPreviewIndex] = React.useState<number | null>(null);
694+
const previewFiles: FilePreviewItem[] = rows.map((row) => ({
695+
id: row.file_id,
696+
name: row.file_name || row.file_id,
697+
mimeType: row.mime_type ?? undefined,
698+
size: row.size ?? undefined,
699+
}));
700+
const previewSignedUrl = React.useCallback(
701+
async (file: FilePreviewItem): Promise<string> => {
702+
const row = rows.find((r) => r.file_id === file.id);
703+
if (!row) throw new Error(t('fields.filePreview.loadFailed', { defaultValue: 'The preview could not be loaded.' }));
704+
try {
705+
return await signedUrlFor(row);
706+
} catch (err) {
707+
// The download's own copy for the download's own refusal.
708+
throw Object.assign(new Error(friendlyError(err)), { cause: err });
709+
}
710+
},
711+
[rows, signedUrlFor, friendlyError, t],
674712
);
675713

676714
// Upload is offered (the header's 「+ 上传」, the empty line's 「选择文件」 and
@@ -870,7 +908,7 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
870908
</div>
871909
) : (
872910
<ul className="divide-y border-t">
873-
{rows.map((row) => {
911+
{rows.map((row, index) => {
874912
const TypeIcon = fileTypeIcon(row.mime_type);
875913
const name = row.file_name || row.file_id;
876914
const uploader = uploaderOf(row);
@@ -879,7 +917,15 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
879917
// and uploader step aside in a narrow container (a drawer).
880918
<li key={row.id} className="flex h-[33px] items-center gap-2 px-1 text-sm" data-attachment-row="">
881919
<TypeIcon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
882-
<span className="min-w-0 flex-1 truncate" title={name}>{name}</span>
920+
<button
921+
type="button"
922+
className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none"
923+
title={name}
924+
onClick={() => setPreviewIndex(index)}
925+
data-attachment-preview=""
926+
>
927+
{name}
928+
</button>
883929
<span className="hidden w-16 shrink-0 text-right text-xs text-muted-foreground tabular-nums @md:inline">
884930
{formatSize(row.size)}
885931
</span>
@@ -943,6 +989,20 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
943989
if (!open) setConfirmState((s) => ({ ...s, open: false }));
944990
}}
945991
/>
992+
{previewIndex !== null && previewIndex < rows.length && (
993+
<FilePreviewDialog
994+
files={previewFiles}
995+
index={previewIndex}
996+
open
997+
onOpenChange={(open) => !open && setPreviewIndex(null)}
998+
onIndexChange={setPreviewIndex}
999+
resolveUrl={previewSignedUrl}
1000+
onDownload={(_file, index) => {
1001+
const row = rows[index];
1002+
if (row) void handleDownload(row);
1003+
}}
1004+
/>
1005+
)}
9461006
<AttachmentRenameDialog
9471007
row={renaming}
9481008
onOpenChange={(open) => {

‎ui/packages/app-shell/src/views/__tests__/RecordAttachmentsPanel.test.tsx‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,3 +1042,90 @@ describe('RecordAttachmentsPanel — Rename sends the new name to the rename doo
10421042
expect(fetchSpy).not.toHaveBeenCalled();
10431043
});
10441044
});
1045+
1046+
/**
1047+
* objectstack#36442 — a row's name opens the file in the page. The preview
1048+
* mints its link through the download's own door (`/files/:id/url`, with the
1049+
* console's token), so a refused reader gets the download's own copy; the
1050+
* download itself stays in the row's ⋮ menu.
1051+
*/
1052+
describe('RecordAttachmentsPanel — the name opens the in-page preview (objectstack#36442)', () => {
1053+
const ROWS = [
1054+
{ ...ROW, id: 'a1', file_id: 'f1', file_name: 'report.pdf', mime_type: 'application/pdf' },
1055+
{ ...ROW, id: 'a2', file_id: 'f2', file_name: 'photo.png', mime_type: 'image/png' },
1056+
{ ...ROW, id: 'a3', file_id: 'f3', file_name: 'memo.docx', mime_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
1057+
];
1058+
const signed = (id: string) =>
1059+
new Response(JSON.stringify({ success: true, data: { url: `/api/v1/storage/_local/raw/tok-${id}` } }), {
1060+
status: 200,
1061+
headers: { 'Content-Type': 'application/json' },
1062+
});
1063+
1064+
it('clicking the name previews the file on the signed link the download mints', async () => {
1065+
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!));
1066+
setup(makeDataSource({ find: vi.fn(async () => ROWS) }));
1067+
const user = userEvent.setup();
1068+
await user.click(await screen.findByRole('button', { name: 'report.pdf' }));
1069+
const dialog = await screen.findByTestId('file-preview-dialog');
1070+
await waitFor(() => expect(dialog.querySelector('iframe')?.getAttribute('src')).toContain('/api/v1/storage/_local/raw/tok-f1'));
1071+
expect(String(fetchSpy.mock.calls[0]![0])).toContain('/api/v1/storage/files/f1/url');
1072+
expect(within(dialog).getByText('1 / 3')).toBeInTheDocument();
1073+
});
1074+
1075+
it('next walks to the following row, with its own signed link', async () => {
1076+
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!));
1077+
setup(makeDataSource({ find: vi.fn(async () => ROWS) }));
1078+
const user = userEvent.setup();
1079+
await user.click(await screen.findByRole('button', { name: 'report.pdf' }));
1080+
const dialog = await screen.findByTestId('file-preview-dialog');
1081+
await user.click(within(dialog).getByRole('button', { name: 'Next file' }));
1082+
await waitFor(() =>
1083+
expect((within(dialog).getByRole('img', { name: 'photo.png' }) as HTMLImageElement).getAttribute('src')).toContain('tok-f2'),
1084+
);
1085+
expect(within(dialog).getByText('2 / 3')).toBeInTheDocument();
1086+
});
1087+
1088+
it('a reader the download refuses is refused by the preview, with the same copy', async () => {
1089+
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(
1090+
async () =>
1091+
new Response(JSON.stringify({ success: false, error: { code: 'ATTACHMENT_DOWNLOAD_DENIED', message: 'no' } }), {
1092+
status: 403,
1093+
headers: { 'Content-Type': 'application/json' },
1094+
}),
1095+
);
1096+
setup(makeDataSource({ find: vi.fn(async () => ROWS) }));
1097+
const user = userEvent.setup();
1098+
await user.click(await screen.findByRole('button', { name: 'photo.png' }));
1099+
const dialog = await screen.findByTestId('file-preview-dialog');
1100+
await waitFor(() =>
1101+
expect(within(dialog).getByRole('alert')).toHaveTextContent("You don't have access to download this attachment."),
1102+
);
1103+
expect(dialog.querySelector('img, iframe')).toBeNull();
1104+
// Asked once: a refusal is not re-asked on every render.
1105+
expect(fetchSpy).toHaveBeenCalledTimes(1);
1106+
});
1107+
1108+
it('a Word file offers the download only, and its download is the row menu\'s download', async () => {
1109+
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
1110+
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => signed(String(input).match(/files\/(\w+)\/url/)![1]!));
1111+
setup(makeDataSource({ find: vi.fn(async () => ROWS) }));
1112+
const user = userEvent.setup();
1113+
await user.click(await screen.findByRole('button', { name: 'memo.docx' }));
1114+
const dialog = await screen.findByTestId('file-preview-dialog');
1115+
expect(within(dialog).getByText('This file type cannot be previewed. Please download it.')).toBeInTheDocument();
1116+
expect(fetchSpy).not.toHaveBeenCalled();
1117+
const view = dialog.querySelector('[data-preview-state="unsupported"]') as HTMLElement;
1118+
await user.click(within(view).getByRole('button', { name: 'Download' }));
1119+
await waitFor(() =>
1120+
expect(openSpy).toHaveBeenCalledWith(expect.stringContaining('tok-f3'), '_blank', 'noopener,noreferrer'),
1121+
);
1122+
});
1123+
1124+
it('the row menu still carries the download', async () => {
1125+
setup(makeDataSource({ find: vi.fn(async () => [ROW]) }));
1126+
const user = userEvent.setup();
1127+
await screen.findByRole('button', { name: 'report.pdf' });
1128+
await user.click(screen.getByRole('button', { name: /^More for / }));
1129+
expect(await screen.findByRole('menuitem', { name: 'Download' })).toBeInTheDocument();
1130+
});
1131+
});

‎ui/packages/fields/src/index.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5508,6 +5508,12 @@ export * from './widgets/FileField.js';
55085508
export * from './widgets/ImageField.js';
55095509
export { ImageCropperDialog } from './widgets/ImageCropperDialog.js';
55105510
export type { ImageCropperDialogProps } from './widgets/ImageCropperDialog.js';
5511+
// The in-page file preview a record's attachments and a file field open
5512+
// (objectstack#36442), and the delimited-text reader its CSV view shares with
5513+
// the grid's import wizard.
5514+
export { FilePreviewDialog } from './widgets/FilePreviewDialog.js';
5515+
export type { FilePreviewDialogProps, FilePreviewItem } from './widgets/FilePreviewDialog.js';
5516+
export { decodeSpreadsheetText, parseDelimited } from './widgets/delimitedText.js';
55115517
export * from './widgets/LocationField.js';
55125518
export * from './widgets/FormulaField.js';
55135519
export * from './widgets/SummaryField.js';

0 commit comments

Comments
 (0)