Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .changeset/36442-console-file-preview.md
Original file line number Diff line number Diff line change
@@ -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.
134 changes: 97 additions & 37 deletions ui/packages/app-shell/src/views/RecordAttachmentsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -626,51 +630,85 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
[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<string> => {
// The stable `/files/:fileId` endpoint now requires an authenticated
// session for attachments-scope files (objectstack-ai/objectstack#2970) — an <a href> 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 <a href> 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<number | null>(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<string> => {
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
Expand Down Expand Up @@ -870,7 +908,7 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
</div>
) : (
<ul className="divide-y border-t">
{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);
Expand All @@ -879,7 +917,15 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
// and uploader step aside in a narrow container (a drawer).
<li key={row.id} className="flex h-[33px] items-center gap-2 px-1 text-sm" data-attachment-row="">
<TypeIcon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="min-w-0 flex-1 truncate" title={name}>{name}</span>
<button
type="button"
className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:underline focus-visible:outline-none"
title={name}
onClick={() => setPreviewIndex(index)}
data-attachment-preview=""
>
{name}
</button>
<span className="hidden w-16 shrink-0 text-right text-xs text-muted-foreground tabular-nums @md:inline">
{formatSize(row.size)}
</span>
Expand Down Expand Up @@ -943,6 +989,20 @@ export const RecordAttachmentsPanel: React.FC<RecordAttachmentsPanelProps> = ({
if (!open) setConfirmState((s) => ({ ...s, open: false }));
}}
/>
{previewIndex !== null && previewIndex < rows.length && (
<FilePreviewDialog
files={previewFiles}
index={previewIndex}
open
onOpenChange={(open) => !open && setPreviewIndex(null)}
onIndexChange={setPreviewIndex}
resolveUrl={previewSignedUrl}
onDownload={(_file, index) => {
const row = rows[index];
if (row) void handleDownload(row);
}}
/>
)}
<AttachmentRenameDialog
row={renaming}
onOpenChange={(open) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
6 changes: 6 additions & 0 deletions ui/packages/fields/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Loading
Loading