feat: preview s3 text and markdown files and compact the s3 table card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem LemouelandClaude Opus 5.5 committed 2026-11-26 07:56:38 -08:00
1 parent ea1cbc19bc
commit 673b9be401
13 files changed
+575 -414

No files matched your search

+42 -19
View File
@@ -59,7 +59,7 @@
import type { IDbTableOps } from './dbOps'
import type { TableEditorForeignKey } from './apps/components/display/dbtable/tableEditor'
import type { ColumnDef } from './apps/components/display/dbtable/utils'
import { untrack } from 'svelte'
import { untrack, type Snippet } from 'svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import FilterSearchbar from './FilterSearchbar.svelte'
import {
@@ -105,6 +105,13 @@
joinTargets?: DbJoinTarget[]
/** Offered from the add-column button: adding a column to the table itself. */
onNewColumn?: () => void
/** Hides the button that downloads the loaded rows, for a file whose owner disabled downloads. */
disableDownload?: boolean
/** The caller's own controls, placed in the toolbar before the row count. */
toolbar?: Snippet
/** For a narrow container: a short search placeholder, a smaller row count and an
* icon-only Columns button. */
compact?: boolean
}
let {
dbTableOps,
@@ -114,7 +121,10 @@
onRowFilterApplied,
layoutStorageKey,
joinTargets,
onNewColumn
onNewColumn,
disableDownload = false,
toolbar,
compact = false
}: Props = $props()
const storedLayout = untrack(() =>
@@ -1037,32 +1047,44 @@
<div class="h-full relative flex flex-col">
<div class="flex justify-between items-center bg-surface-input pr-2">
<FilterSearchbar
class="grow rounded-none !border-0"
class="grow min-w-0 rounded-none !border-0"
size="lg"
searchIconPosition="left"
dropdownMaxWidth={480}
dropdownOffsetY={1}
schema={filterSchema.schema}
bind:value={filters}
placeholder="Search, or filter by column..."
placeholder={compact ? 'Search' : 'Search, or filter by column...'}
/>
<div class="flex shrink-0 items-center gap-2 text-xs text-secondary">
{@render toolbar?.()}
{#if totalRows > 0 && endRow !== 0}
<span class="whitespace-nowrap">
{Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)}
{#if rowCount !== undefined || endRow !== undefined}
of {endRow ?? rowCount} rows
{/if}
</span>
{#if compact}
<span
class="whitespace-nowrap text-2xs text-hint"
title="Rows {Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)}"
>
{endRow ?? rowCount ?? totalRows} rows
</span>
{:else}
<span class="whitespace-nowrap">
{Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)}
{#if rowCount !== undefined || endRow !== undefined}
of {endRow ?? rowCount} rows
{/if}
</span>
{/if}
{/if}
{#if !disableDownload}
<Button
startIcon={{ icon: Download }}
variant="subtle"
unifiedSize="sm"
iconOnly
title="Download loaded rows as CSV"
onClick={downloadCsv}
/>
{/if}
<Button
startIcon={{ icon: Download }}
variant="subtle"
unifiedSize="sm"
iconOnly
title="Download loaded rows as CSV"
onClick={downloadCsv}
/>
<div class="flex" bind:this={columnsAnchor}>
<Popover
floatingConfig={{ strategy: 'fixed', placement: 'bottom-end' }}
@@ -1075,8 +1097,9 @@
startIcon={{ icon: Columns3 }}
selected={hidden.length > 0}
nonCaptureEvent
title="Choose the columns to show"
title={compact && hidden.length ? columnsLabel : 'Choose the columns to show'}
btnClasses="max-w-64"
iconOnly={compact}
>
<span class="truncate">{hidden.length ? columnsLabel : 'Columns'}</span>
</Button>
@@ -37,8 +37,11 @@
import { markdownProse } from './markdownProse'
import Toggle from './Toggle.svelte'
import S3ObjectHeader from './common/fileDownload/S3ObjectHeader.svelte'
import S3TextPreview from './common/fileDownload/S3TextPreview.svelte'
import ParqetTableRenderer from './ParqetCsvTableRenderer.svelte'
import S3ObjectTable from './common/fileDownload/S3ObjectTable.svelte'
import { serverTableFormat } from './s3TableOps'
import { isMarkdownFile } from './common/fileDownload/FileTextPreview.svelte'
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
import MapResult from './MapResult.svelte'
@@ -203,11 +206,15 @@
return url
}
function s3PreviewKind(key: unknown): 'table' | 'image' | 'pdf' | undefined {
function s3PreviewKind(
key: unknown
): 'table' | 'image' | 'pdf' | 'text' | 'markdown' | undefined {
if (typeof key !== 'string') return undefined
if (key.endsWith('.parquet') || key.endsWith('.csv')) return 'table'
if (serverTableFormat(key)) return 'table'
if (['.png', '.jpeg', '.jpg', '.webp'].some((ext) => key.endsWith(ext))) return 'image'
if (key.endsWith('.pdf')) return 'pdf'
if (key.endsWith('.txt') || key.endsWith('.log')) return 'text'
if (isMarkdownFile(key)) return 'markdown'
return undefined
}
@@ -667,6 +674,13 @@
let globalForceJson: boolean = $state(false)
let seeS3PreviewFileFromList = $state('')
/** Keys of the markdown files shown as their source rather than rendered. */
let markdownSourceKeys: string[] = $state([])
function setMarkdownSource(key: string, source: boolean) {
markdownSourceKeys = source
? [...markdownSourceKeys, key]
: markdownSourceKeys.filter((k) => k !== key)
}
const disableTooltips = hasContext('disableTooltips')
? getContext('disableTooltips') === true
@@ -820,16 +834,9 @@
})}
{@const kind = s3PreviewKind(s3object?.s3)}
{#if kind === 'table'}
<ParqetTableRenderer
disable_download={s3object?.disable_download}
{workspaceId}
{appPath}
s3resource={s3object?.s3}
storage={s3object?.storage}
presigned={s3object?.presigned}
/>
<S3ObjectTable {s3object} {workspaceId} {appPath} />
{:else if kind === 'image'}
<div class="h-full">
<div class="h-full p-3">
<ExpandableImage
alt="Preview of {s3object?.s3}"
title={s3object?.s3}
@@ -838,13 +845,21 @@
/>
</div>
{:else if kind === 'pdf'}
<div class="h-96 rounded-md overflow-hidden" data-interactive>
<div class="h-96 overflow-hidden" data-interactive>
{#await import('$lib/components/display/PdfViewer.svelte')}
<Loader2 class="animate-spin" />
{:then Module}
<Module.default allowFullscreen source={s3DisplayUrl(s3object)} />
{/await}
</div>
{:else if kind === 'text' || kind === 'markdown'}
<S3TextPreview
{s3object}
{workspaceId}
{appPath}
markdown={kind === 'markdown'}
markdownSource={markdownSourceKeys.includes(s3object.s3)}
/>
{/if}
{/snippet}
@@ -882,8 +897,8 @@
}}
>
{#snippet children({ item })}
<ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton value="json" label="JSON" icon={Braces} {item} />
<ToggleButton size="xs" value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton size="xs" value="json" label="JSON" icon={Braces} {item} />
{/snippet}
</ToggleButtonGroup>
</div>
@@ -930,11 +945,11 @@
>
{#snippet children({ item })}
{#if ['table-col', 'table-row', 'table-row-object'].includes(resultKind ?? '')}
<ToggleButton size="sm" value="table" label="Table" icon={Table2} {item} />
<ToggleButton size="xs" value="table" label="Table" icon={Table2} {item} />
{:else}
<ToggleButton size="sm" value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton size="xs" value="pretty" label="Pretty" icon={Highlighter} {item} />
{/if}
<ToggleButton size="sm" value="json" label="JSON" icon={Braces} {item} />
<ToggleButton size="xs" value="json" label="JSON" icon={Braces} {item} />
{/snippet}
</ToggleButtonGroup>
{/if}
@@ -1216,43 +1231,63 @@
{/if}
{:else if !forceJson && resultKind === 's3object'}
{@const s3object = parseS3Object(result) as typeof result}
<div class="h-full w-full">
<div class="h-full w-full pt-2">
{#if typeof s3object?.s3 === 'string'}
<div class="rounded-md border bg-surface flex flex-col gap-2 px-3 py-2">
<S3ObjectHeader
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
/>
{#key s3object.s3}
{@render s3Preview(s3object)}
{/key}
<!-- One card: the header, then the preview flush below a separator, as in the S3
file browser. -->
<div class="rounded-md border bg-surface overflow-hidden">
<div class="px-3 py-2">
<S3ObjectHeader
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
markdownSource={s3PreviewKind(s3object.s3) === 'markdown'
? markdownSourceKeys.includes(s3object.s3)
: undefined}
onMarkdownSource={(source) => setMarkdownSource(s3object.s3, source)}
/>
</div>
{#if s3PreviewKind(s3object.s3)}
<div class="border-t">
{#key s3object.s3}
{@render s3Preview(s3object)}
{/key}
</div>
{/if}
</div>
{/if}
</div>
{:else if !forceJson && resultKind === 's3object-list'}
<div class="h-full w-full">
<div class="h-full w-full pt-2">
<div class="flex flex-col gap-2">
<div class="rounded-md border bg-surface divide-y">
<div class="rounded-md border bg-surface divide-y overflow-hidden">
{#each result as _s3object}
{@const s3object = parseS3Object(_s3object) as typeof _s3object}
{@const kind = s3PreviewKind(s3object?.s3)}
{@const collapsible = kind === 'table' || kind === 'image'}
{@const collapsible = kind !== undefined && kind !== 'pdf'}
{@const previewOpen = seeS3PreviewFileFromList == s3object?.s3}
<div class="flex flex-col gap-2 px-3 py-2">
<S3ObjectHeader
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
previewOpen={collapsible ? previewOpen : undefined}
onTogglePreview={() => {
seeS3PreviewFileFromList = previewOpen ? '' : s3object?.s3
}}
/>
{#if !collapsible || previewOpen}
{@render s3Preview(s3object)}
<div class="flex flex-col">
<div class="px-3 py-2">
<S3ObjectHeader
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
previewOpen={collapsible ? previewOpen : undefined}
onTogglePreview={() => {
seeS3PreviewFileFromList = previewOpen ? '' : s3object?.s3
}}
markdownSource={kind === 'markdown' && previewOpen
? markdownSourceKeys.includes(s3object.s3)
: undefined}
onMarkdownSource={(source) => setMarkdownSource(s3object.s3, source)}
/>
</div>
{#if kind !== undefined && (!collapsible || previewOpen)}
<div class="border-t">
{@render s3Preview(s3object)}
</div>
{/if}
</div>
{/each}
@@ -1,326 +0,0 @@
<script lang="ts">
import { run } from 'svelte/legacy'
import { type GridApi, createGrid, type IDatasource } from 'ag-grid-community'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import DarkModeObserver from './DarkModeObserver.svelte'
import { Button } from './common'
import { AppService, HelpersService } from '$lib/gen'
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
import { enterpriseLicense } from '$lib/stores'
import { Download } from 'lucide-svelte'
import { Loader2 } from 'lucide-svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
const operatingWorkspace = useOperatingWorkspace()
// import 'ag-grid-community/dist/styles/ag-theme-alpine-dark.css'
let selectedRowIndex = -1
interface Props {
s3resource: string
storage: string | undefined
workspaceId: string | undefined
disable_download?: boolean
// When set (deployed app view), read the file on-behalf of the app author
// through the app-scoped, provenance-gated `apps_u/*` endpoints instead of
// the viewer-scoped `job_helpers/*` API. Undefined in the editor/preview.
appPath?: string | undefined
// HMAC bearer (`exp=..&sig=..`) minted by `signS3Objects`. When present on a
// deployed-app read, it bypasses the provenance gate — matching the download
// and image routes. Forwarded to every app-scoped preview/count/export call.
presigned?: string | undefined
}
let {
s3resource,
storage,
workspaceId,
disable_download = false,
appPath = undefined,
presigned = undefined
}: Props = $props()
// Split the presigned bearer into typed query params for the generated client.
// Only meaningful in deployed-app (`appPath`) reads; empty otherwise.
function presignedParams(): { sig?: string; exp?: string } {
if (!appPath || !presigned) return {}
const p = new URLSearchParams(presigned)
return { sig: p.get('sig') ?? undefined, exp: p.get('exp') ?? undefined }
}
// Route the parquet/csv read through the app-scoped endpoints when `appPath`
// is set, else the viewer-scoped helpers. Same request/response shape either
// way — the only difference is which identity authorizes the S3 read.
function loadRowCount(searchCol: string | undefined, searchTerm: string | undefined) {
const workspace = workspaceId ?? $operatingWorkspace!
return appPath
? AppService.appLoadTableCount({
workspace,
path: appPath,
fileKey: s3resource,
searchCol,
searchTerm,
storage,
...presignedParams()
})
: HelpersService.loadTableRowCount({
workspace,
path: s3resource,
searchCol,
searchTerm,
storage
})
}
function loadChunk(args: {
offset?: number
limit?: number
sortCol?: string
sortDesc?: boolean
searchCol?: string
searchTerm?: string
csvSeparator?: string
}) {
const workspace = workspaceId ?? $operatingWorkspace!
const csv = s3resource.endsWith('.csv')
if (appPath) {
const data = {
workspace,
path: appPath,
fileKey: s3resource,
storage,
...args,
...presignedParams()
}
return csv ? AppService.appLoadCsvPreview(data) : AppService.appLoadParquetPreview(data)
}
const data = { workspace, path: s3resource, storage, ...args }
return csv ? HelpersService.loadCsvPreview(data) : HelpersService.loadParquetPreview(data)
}
let lastSearch: string | undefined = undefined
let nbRows: number | undefined = $state(undefined)
// Unfiltered count: the grid keeps its height while a filter narrows the rows.
let totalRows: number | undefined = $state(undefined)
// The infinite row model cannot size itself to its rows, so the height is computed from
// the explicit row and header heights passed to createGrid, plus room for a horizontal
// scrollbar when the columns overflow. The floor keeps the column filter menu inside the
// grid: ag-grid clips its popups to the grid, and moving them to <body> would put them
// under the drawers this table is shown in.
const ROW_HEIGHT = 42
const HEADER_HEIGHT = 48
const MIN_GRID_HEIGHT = 180
const MAX_GRID_HEIGHT = 600
let gridHeight = $derived(
totalRows === undefined
? 240
: Math.min(
MAX_GRID_HEIGHT,
Math.max(MIN_GRID_HEIGHT, HEADER_HEIGHT + totalRows * ROW_HEIGHT + 18)
)
)
let csvSeparatorChar: string = $state(',')
let datasource: IDatasource = {
rowCount: 0,
getRows: async function (params) {
try {
const searchCol = params.filterModel ? Object.keys(params.filterModel)?.[0] : undefined
const searchTerm = searchCol ? params.filterModel?.[searchCol]?.filter : undefined
const csv = s3resource.endsWith('.csv')
const newSearch = searchCol ? searchCol + searchTerm : undefined
if (!nbRows || lastSearch != newSearch) {
nbRows = undefined
const res = await loadRowCount(searchCol, searchTerm)
nbRows = res.count
if (newSearch === undefined) totalRows = res.count
lastSearch = newSearch
}
const res = (await loadChunk({
offset: params.startRow,
limit: params.endRow - params.startRow,
sortCol: params.sortModel?.[0]?.colId,
sortDesc: params.sortModel?.[0]?.sort == 'desc',
searchCol,
searchTerm,
csvSeparator: csv ? csvSeparatorChar : undefined
})) as any
for (let i = 0; i < res.rows.length; i++) {
res.rows[i]['__index'] = i + params.startRow
if (!$enterpriseLicense) {
Object.keys(res.rows[i]).forEach((key) => {
if (key != '__index') {
res.rows[i][key] = 'Require EE'
}
})
}
}
params.successCallback(res.rows, nbRows)
} catch (e) {
console.error(e)
params.failCallback()
}
}
}
function toggleRow(row: any) {
if (row) {
let rowIndex = row.rowIndex
let data = { ...row.data }
delete data['__index']
if (selectedRowIndex !== rowIndex) {
selectedRowIndex = rowIndex
}
}
}
function toggleRows(rows: any[]) {
toggleRow(rows[0])
}
let eGui: HTMLDivElement | undefined = $state()
let error: string | undefined = $state(undefined)
async function mountGrid() {
if (eGui) {
try {
const csv = s3resource.endsWith('.csv')
const res = (await loadChunk({
limit: 0,
csvSeparator: csv ? csvSeparatorChar : undefined
})) as any
createGrid(
eGui,
{
rowModelType: 'infinite',
datasource,
rowHeight: ROW_HEIGHT,
headerHeight: HEADER_HEIGHT,
// @ts-ignore
columnDefs: res.columns.map((c) => {
return {
field: c,
sortable: true,
filter: true,
filterParams: {
filterOptions: ['contains'],
maxNumConditions: 1
}
}
}),
pagination: false,
// defaultColDef: {
// flex: 1
// },
suppressColumnMoveAnimation: true,
rowSelection: 'multiple',
rowMultiSelectWithClick: true,
suppressRowDeselection: true,
onSelectionChanged: (e) => {
onSelectionChanged(e.api)
},
getRowId: (data) => {
return (data as any).data['__index']
}
},
{}
)
error = undefined
} catch (e) {
error = e.body
console.error(e)
}
}
}
function onSelectionChanged(api: GridApi<any>) {
const rows = api.getSelectedNodes()
if (rows != undefined) {
toggleRows(rows)
}
}
let darkMode: boolean = $state(false)
run(() => {
eGui && mountGrid()
})
</script>
<DarkModeObserver bind:darkMode />
<div class="flex flex-col gap-1">
<div class="flex flex-row items-center justify-between gap-2 min-h-7">
{#if nbRows != undefined}
<div class="text-secondary text-2xs">{nbRows} rows</div>
{:else}
<Loader2 class="animate-spin" size={12} />
{/if}
{#if s3resource.endsWith('.csv')}
<div class="flex items-center gap-2">
<label for="csvSeparatorChar" class="text-2xs text-secondary">Separator</label>
<div class="w-12">
<select
id="csvSeparatorChar"
class="h-7"
bind:value={csvSeparatorChar}
onchange={(e) => mountGrid()}
>
<option value=",">,</option>
<option value=";">;</option>
<option value="\t">\t</option>
<option value="|">|</option>
</select>
</div>
</div>
{:else if !disable_download}
{@const csvApiPath = appPath
? `/w/${workspaceId}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}${presigned ? `&${presigned}` : ''}`
: `/w/${workspaceId}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}`}
{@const csvName = (s3resource.split('/').pop() ?? 'download') + '.csv'}
{#if shouldDownloadViaClient()}
<Button
variant="subtle"
unifiedSize="sm"
startIcon={{ icon: Download }}
onClick={() => downloadViaClient(csvApiPath, csvName)}
>
Download as CSV
</Button>
{:else}
<Button
variant="subtle"
unifiedSize="sm"
startIcon={{ icon: Download }}
href="/api{csvApiPath}"
download={csvName}
>
Download as CSV
</Button>
{/if}
{/if}
</div>
<div
class="ag-theme-alpine shadow-sm"
class:ag-theme-alpine-dark={darkMode}
style="height: {gridHeight}px;"
>
{#if error}
<div class="text-red-500">{error}</div>
<div>Try changing separator to fix it</div>
{/if}
<div bind:this={eGui} style="height:100%; "></div>
</div>
</div>
<!-- <div class="flex gap-1 absolute bottom-1 right-2 text-sm text-secondary"
>{firstRow}{'->'}{lastRow + 1} of {datasource?.rowCount} rows</div
> -->
@@ -18,7 +18,8 @@
FileArchive,
FilePlay,
FileAudio,
Table2
Table2,
Eye
} from 'lucide-svelte'
import { Pane, Splitpanes } from 'svelte-splitpanes'
import TextInput from './text_input/TextInput.svelte'
@@ -71,6 +72,7 @@
import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte'
import FileUploadModal from './common/fileUpload/FileUploadModal.svelte'
import S3FilePreview from './S3FilePreview.svelte'
import { isMarkdownFile } from './common/fileDownload/FileTextPreview.svelte'
import { twMerge } from 'tailwind-merge'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
@@ -211,6 +213,7 @@
| undefined = $state(undefined)
let viewMode: 'table' | 'text' = $state('table')
let markdownView: 'rendered' | 'text' = $state('rendered')
/** The selected file, when it can be shown as a table. Its own requests can't read
* files behind a custom listing (git repos), so those keep the text preview. */
let tableSource = $derived.by(() => {
@@ -1441,6 +1444,18 @@
<ToggleButton value="text" label="Text" icon={FileText} small {item} />
{/snippet}
</ToggleButtonGroup>
{:else if isMarkdownFile(fileMetadata.fileKey)}
<ToggleButtonGroup
noWFull
selected={markdownView}
onSelected={(v) => (markdownView = v)}
class="shrink-0"
>
{#snippet children({ item })}
<ToggleButton value="rendered" label="Rendered" icon={Eye} small {item} />
<ToggleButton value="text" label="Text" icon={FileText} small {item} />
{/snippet}
</ToggleButtonGroup>
{/if}
{#if filePreview?.contentType === 'Csv'}
<div class="flex items-center gap-4 shrink-0 text-xs text-secondary">
@@ -1553,6 +1568,7 @@
{loadFileMetadataRequest}
class="flex-1 min-h-0"
csvOptions={{ separator: csvSeparatorChar, hasHeader: csvHasHeader }}
markdownSource={markdownView === 'text'}
bodyClass="bg-transparent px-3"
/>
{/if}
@@ -22,6 +22,11 @@
import { twMerge } from 'tailwind-merge'
import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import FileTextPreview, {
isMarkdownFile
} from '$lib/components/common/fileDownload/FileTextPreview.svelte'
const PREVIEW_BYTES = 128 * 1024
const operatingWorkspace = useOperatingWorkspace()
@@ -51,6 +56,8 @@
/** CSV parsing options owned by the caller, which then renders its own controls:
* the preview hides its own and reloads when these change. */
csvOptions?: { separator: string | undefined; hasHeader: boolean }
/** Markdown shown as its source, owned by the caller, which then renders its own switch. */
markdownSource?: boolean
/** Merged onto the preview body, below the metadata strip. */
bodyClass?: string
// Bump this to force a re-fetch (metadata + preview). Used by the
@@ -71,6 +78,7 @@
class: className = '',
bodyClass = '',
csvOptions = undefined,
markdownSource = undefined,
refreshKey
}: Props = $props()
@@ -191,16 +199,12 @@
csvSeparator: csvOptions ? csvOptions.separator : csvSeparatorChar,
csvHasHeader: csvOptions?.hasHeader ?? csvHasHeader,
readBytesFrom: 0,
readBytesLength: 128 * 1024,
readBytesLength: PREVIEW_BYTES,
storage,
s3ResourcePath
})
let content = raw.content
if (content !== null && content !== undefined && content.length >= 128 * 1024) {
content = content.substring(0, 128 * 1024 - 35) + '\n\n ... FILE CONTENT TRUNCATED ...\n\n'
}
if (raw !== undefined) {
filePreview = { fileKey: key, contentPreview: content, contentType: raw.content_type }
filePreview = { fileKey: key, contentPreview: raw.content, contentType: raw.content_type }
if (fileMetadata) {
fileMetadata.mimeType =
((key.endsWith('.png') ||
@@ -225,6 +229,20 @@
(s3ResourcePath ? `&s3_resource_path=${encodeURIComponent(s3ResourcePath)}` : '')
)
/** The file's text is on screen, drawn on this body's background (see FileTextPreview). */
let showsText = $derived(
!!fileKey &&
!notFound &&
!loadError &&
!filePreviewLoading &&
!isImageOrPdf(fileMetadata?.fileKey) &&
filePreview?.contentType !== 'Unknown' &&
!emptyString(filePreview?.contentPreview)
)
function isImageOrPdf(key: string | undefined) {
return /\.(png|jpe?g|webp|pdf)$/.test(key ?? '')
}
function onCsvControlsChanged() {
if (fileMetadata?.fileKey) {
void reloadPreview(fileMetadata.fileKey, fileMetadata.size, fileMetadata.mimeType)
@@ -250,7 +268,13 @@
{#if fileMetadata.lastModified}<span>{fileMetadata.lastModified}</span>{/if}
</div>
{/if}
<div class={twMerge('flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary', bodyClass)}>
<div
class={twMerge(
'flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary',
bodyClass,
showsText ? 'bg-surface-input' : ''
)}
>
{#if !fileKey}
<div class="text-tertiary text-xs">No file selected.</div>
{:else if fileInfoLoading && !fileMetadata && !notFound && !loadError}
@@ -340,9 +364,17 @@
{/if}
</div>
{/if}
<pre class="grow whitespace-no-wrap break-words"
>{#if !emptyString(filePreview.contentPreview)}{filePreview.contentPreview}{:else if filePreview.contentType !== undefined}Preview impossible.{/if}</pre
>
{#if filePreview.contentPreview && !emptyString(filePreview.contentPreview)}
<FileTextPreview
content={filePreview.contentPreview}
readLimit={PREVIEW_BYTES}
markdown={isMarkdownFile(filePreview.fileKey)}
fill
{markdownSource}
/>
{:else if filePreview.contentType !== undefined}
<div class="text-primary">Preview impossible.</div>
{/if}
{/if}
</div>
</div>
@@ -117,7 +117,7 @@ export async function getS3File({
// Editor/preview runs execute as the *caller* (Viewer mode), so read their
// results back as the caller through the viewer-scoped `job_helpers` endpoint —
// never author-mode — consistent with DisplayResult/ParqetCsvTableRenderer. Only
// never author-mode — consistent with DisplayResult. Only
// a deployed app view reads on-behalf of the author via the provenance-gated
// `apps_u` endpoint.
if (isEditor) {
@@ -0,0 +1,101 @@
<script lang="ts" module>
export function isMarkdownFile(fileKey: string | undefined): boolean {
return /\.(md|markdown)$/i.test(fileKey ?? '')
}
// The read stops at a byte count, so a truncated file usually ends mid-line.
function dropPartialLastLine(text: string) {
const end = text.lastIndexOf('\n')
return end > 0 ? text.slice(0, end) : text
}
</script>
<script lang="ts">
import { Code, Eye, Loader2 } from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
interface Props {
/** The start of a file, as read by a file preview request. */
content: string
/** Bytes the request read at most: content this long is the start of a longer file. */
readLimit: number
/** Rendered as the session renders a markdown artifact, with a switch to its source. */
markdown?: boolean
/** Fill the parent's height, whose padding then sets the margins, instead of capping the
* text at 384px with margins of its own. Drawn flat on `surface-input` either way. */
fill?: boolean
/** Markdown shown as its source, owned by the caller, which then renders its own switch:
* the preview hides its own. */
markdownSource?: boolean
}
let {
content,
readLimit,
markdown = false,
fill = false,
markdownSource = undefined
}: Props = $props()
let localShowSource = $state(false)
let showSource = $derived(markdownSource ?? localShowSource)
let truncated = $derived(new TextEncoder().encode(content).length >= readLimit)
let shown = $derived(truncated ? dropPartialLastLine(content) : content)
let source = $derived(markdown && showSource)
// The source editor fills its box, so the box needs a height rather than a cap.
let boxSize = $derived(fill ? 'flex-1 min-h-0' : source ? 'h-96' : 'max-h-96')
</script>
<div class={twMerge('flex flex-col min-w-0 bg-surface-input', fill ? 'h-full gap-2' : '')}>
{#if markdown}
{#if markdownSource === undefined}
<!-- The session's own switch for a markdown artifact. -->
<ToggleButtonGroup
noWFull
class="self-end"
selected={showSource ? 'source' : 'preview'}
onSelected={(v) => (localShowSource = v === 'source')}
>
{#snippet children({ item })}
<ToggleButton {item} value="preview" icon={Eye} iconOnly tooltip="Preview" size="sm" />
<ToggleButton
{item}
value="source"
icon={Code}
iconOnly
tooltip="View source"
size="sm"
/>
{/snippet}
</ToggleButtonGroup>
{/if}
<div class={twMerge('overflow-auto', source ? '' : fill ? 'px-5' : 'px-8', boxSize)}>
<!-- Lazy: the source view is a Monaco editor, and the logged-in layout mounts the S3
file browser that renders this. No `pre`: the default code block keeps mermaid off,
since a file or a job result is untrusted markdown. -->
{#await import('$lib/components/copilot/chat/artifacts/ArtifactBody.svelte')}
<div class="flex items-center gap-1 p-3 text-2xs text-secondary">
<Loader2 size={12} class="animate-spin" /> Loading preview
</div>
{:then ArtifactBody}
<ArtifactBody.default
content={shown}
{source}
fadeFrom="from-surface-input"
docPadding={fill ? 'pb-8 pt-2' : 'pb-8 pt-6'}
/>
{/await}
</div>
{:else}
<div class={twMerge('overflow-auto', fill ? '' : 'px-3 py-2', boxSize)}>
<pre class="text-xs font-mono text-primary whitespace-pre">{shown}</pre>
</div>
{/if}
{#if truncated}
<div class={twMerge('text-2xs text-hint', fill ? '' : 'px-3 pb-2')}>
Showing the first {Math.round(readLimit / 1024)} KB. Download the file to see all of it.
</div>
{/if}
</div>
@@ -10,6 +10,8 @@
} from 'lucide-svelte'
import { Button } from '$lib/components/common'
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
import FileDownload from './FileDownload.svelte'
interface Props {
@@ -21,6 +23,9 @@
/** Set when the preview is collapsible (list rows); undefined hides the toggle. */
previewOpen?: boolean | undefined
onTogglePreview?: (() => void) | undefined
/** Set for a markdown file whose preview is shown; undefined hides the switch. */
markdownSource?: boolean | undefined
onMarkdownSource?: ((source: boolean) => void) | undefined
}
let {
@@ -29,7 +34,9 @@
appPath = undefined,
onExplore = undefined,
previewOpen = undefined,
onTogglePreview = undefined
onTogglePreview = undefined,
markdownSource = undefined,
onMarkdownSource = undefined
}: Props = $props()
let key = $derived(s3object?.s3 ?? '')
@@ -46,16 +53,30 @@
)
</script>
<div class="flex flex-row items-center gap-3 min-w-0">
<!-- Wraps the actions onto their own line before the file name gets too narrow to read. -->
<div class="flex flex-row flex-wrap items-center gap-x-3 gap-y-2 min-w-0">
<FileIcon size={20} class="shrink-0 text-secondary" />
<div class="flex flex-col min-w-0 grow">
<div class="flex flex-col min-w-20 flex-1">
<span class="text-xs font-semibold text-emphasis truncate" title={filename}>{filename}</span>
<span class="text-2xs text-secondary truncate" title={key}>
S3 object{#if s3object?.storage}&nbsp;in {s3object.storage}{/if} ·
<span class="font-mono">{key}</span>
</span>
</div>
<div class="flex flex-row items-center gap-1 shrink-0">
<div class="flex flex-row items-center gap-1 shrink-0 ml-auto">
{#if markdownSource !== undefined && onMarkdownSource}
<ToggleButtonGroup
noWFull
selected={markdownSource ? 'text' : 'rendered'}
onSelected={(v) => onMarkdownSource(v === 'text')}
class="shrink-0 mr-1"
>
{#snippet children({ item })}
<ToggleButton value="rendered" icon={Eye} iconOnly tooltip="Rendered" size="sm" {item} />
<ToggleButton value="text" icon={FileText} iconOnly tooltip="Text" size="sm" {item} />
{/snippet}
</ToggleButtonGroup>
{/if}
{#if onTogglePreview && previewOpen !== undefined}
<Button
variant="subtle"
@@ -0,0 +1,147 @@
<script lang="ts">
import { ChevronDown, Loader2, PanelTop } from 'lucide-svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import { Button } from '$lib/components/common'
import type { IDbTableOps } from '$lib/components/dbOps'
import { s3TableOps, serverTableFormat } from '$lib/components/s3TableOps'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
interface Props {
s3object: { s3: string; storage?: string; presigned?: string; disable_download?: boolean }
workspaceId?: string | undefined
/** Set in a deployed app: the file is read through the app-scoped `apps_u/*` routes. */
appPath?: string | undefined
}
let { s3object, workspaceId = undefined, appPath = undefined }: Props = $props()
const operatingWorkspace = useOperatingWorkspace()
const CSV_SEPARATORS = [
{ value: ',', short: ',', name: 'Comma' },
{ value: ';', short: ';', name: 'Semicolon' },
{ value: '\t', short: 'Tab', name: 'Tab' },
{ value: '|', short: '|', name: 'Pipe' }
]
// Below this width the table drops the Columns label and shortens its search placeholder.
const COMPACT_WIDTH = 600
// DBTable's search bar, header row and body rows, in px.
const TOOLBAR_HEIGHT = 40
const HEADER_HEIGHT = 30
const ROW_HEIGHT = 34
const SCROLLBAR = 12
let csvSeparator: string | undefined = $state(undefined)
let csvHasHeader = $state(true)
/** The separator the server guessed while none is picked. */
let detectedSeparator: string | undefined = $state(undefined)
let isCsv = $derived(serverTableFormat(s3object.s3) === 'csv')
let width = $state(0)
let separator = $derived(
CSV_SEPARATORS.find((s) => s.value === (csvSeparator ?? detectedSeparator))
)
let separatorItems = $derived([
...CSV_SEPARATORS.map((s) => ({
displayName: s.short === s.name ? s.name : `${s.name} ${s.short}`,
action: () => (csvSeparator = s.value)
})),
...(csvSeparator !== undefined
? [{ displayName: 'Detect automatically', action: () => (csvSeparator = undefined) }]
: [])
])
/** Rows in the whole file, kept while a search narrows them so the table keeps its height. */
let totalRows: number | undefined = $state(undefined)
let height = $derived(
totalRows === undefined
? 240
: Math.min(
600,
Math.max(180, TOOLBAR_HEIGHT + HEADER_HEIGHT + totalRows * ROW_HEIGHT + SCROLLBAR)
)
)
function recordingTotal(ops: IDbTableOps): IDbTableOps {
return {
...ops,
getCount: async (params) => {
const n = await ops.getCount(params)
const filtered = !!params.quicksearch || Object.keys(params.columnFilters ?? {}).length > 0
if (!filtered) totalRows = n
return n
}
}
}
// Lazy: DBTable reaches Monaco, and every page that shows a job result imports this card.
const dbTable = import('$lib/components/DBTable.svelte')
let table = $derived(
s3TableOps({
workspace: workspaceId ?? $operatingWorkspace!,
fileKey: s3object.s3,
storage: s3object.storage,
csvSeparator,
csvHasHeader,
app: appPath ? { path: appPath, presigned: s3object.presigned } : undefined
}).then((t) => {
detectedSeparator = t.csvSeparator
return dbTable.then((m) => ({ ...t, ops: recordingTotal(t.ops), DBTable: m.default }))
})
)
</script>
{#snippet csvControls()}
<DropdownV2 items={separatorItems} placement="bottom-end">
{#snippet buttonReplacement()}
<Button
nonCaptureEvent
variant="subtle"
unifiedSize="sm"
endIcon={{ icon: ChevronDown }}
title="Separator: {separator?.name ?? 'detecting'}{csvSeparator === undefined
? ' (detected)'
: ''}"
>
<span class="font-mono">{separator?.short ?? '…'}</span>
</Button>
{/snippet}
</DropdownV2>
<!-- The app-scoped routes always read the first row as the header. -->
{#if !appPath}
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: PanelTop }}
selected={csvHasHeader}
title={csvHasHeader ? 'First row is the header' : 'First row is data'}
onClick={() => (csvHasHeader = !csvHasHeader)}
/>
{/if}
<div class="w-px h-5 border-l"></div>
{/snippet}
<div class="overflow-hidden" style="height: {height}px" bind:clientWidth={width} data-interactive>
{#await table}
<div class="flex h-full items-center justify-center gap-1 text-2xs text-secondary">
<Loader2 size={12} class="animate-spin" /> Loading table
</div>
{:then t}
<t.DBTable
dbTableOps={t.ops}
disableDownload={s3object.disable_download}
toolbar={isCsv ? csvControls : undefined}
compact={width < COMPACT_WIDTH}
/>
{:catch e}
{#if isCsv}
<div class="flex items-center justify-end gap-2 bg-surface-input px-2 py-1.5">
{@render csvControls()}
</div>
{/if}
<div class="p-3 text-xs text-red-600 dark:text-red-400 break-words">
Could not read this file as a table: {e?.body ?? e?.message ?? e}
</div>
{/await}
</div>
@@ -0,0 +1,64 @@
<script lang="ts">
import { Loader2 } from 'lucide-svelte'
import { AppService, HelpersService } from '$lib/gen'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import FileTextPreview from './FileTextPreview.svelte'
interface Props {
s3object: { s3: string; storage?: string; presigned?: string }
workspaceId?: string | undefined
/** Set in a deployed app: the file is read through the app-scoped `apps_u/*` route. */
appPath?: string | undefined
markdown?: boolean
/** Markdown shown as its source; the caller renders the switch. */
markdownSource?: boolean
}
let {
s3object,
workspaceId = undefined,
appPath = undefined,
markdown = false,
markdownSource = undefined
}: Props = $props()
const operatingWorkspace = useOperatingWorkspace()
const MAX_BYTES = 64 * 1024
function load(key: string, storage: string | undefined, presigned: string | undefined) {
const workspace = workspaceId ?? $operatingWorkspace!
const range = { readBytesFrom: 0, readBytesLength: MAX_BYTES }
if (appPath) {
const p = new URLSearchParams(presigned ?? '')
return AppService.appLoadFilePreview({
workspace,
path: appPath,
fileKey: key,
storage,
...range,
sig: p.get('sig') ?? undefined,
exp: p.get('exp') ?? undefined
})
}
return HelpersService.loadFilePreview({ workspace, fileKey: key, storage, ...range })
}
let preview = $derived(load(s3object.s3, s3object.storage, s3object.presigned))
</script>
{#await preview}
<div class="flex items-center gap-1 px-3 py-2 text-2xs text-secondary">
<Loader2 size={12} class="animate-spin" /> Loading preview
</div>
{:then res}
{#if res.content_type === 'Unknown' || !res.content}
<div class="px-3 py-2 text-2xs text-secondary">{res.msg || 'No preview available.'}</div>
{:else}
<FileTextPreview content={res.content} readLimit={MAX_BYTES} {markdown} {markdownSource} />
{/if}
{:catch e}
<div class="px-3 py-2 text-2xs text-red-500 break-all">
Could not load the preview: {e?.body ?? e?.message ?? e}
</div>
{/await}
@@ -16,7 +16,7 @@
disabled?: boolean
selectedColor?: string | undefined
small?: boolean
size?: 'sm' | 'md' | 'lg'
size?: 'xs' | 'sm' | 'md' | 'lg'
iconProps?: Record<string, any>
showTooltipIcon?: boolean
documentationLink?: string | undefined
@@ -20,9 +20,19 @@
* the chat's, which also needs the chat context the shared pages do not have.
*/
pre?: Component<any>
/** The background the top fade blends into, as a Tailwind `from-*` class. */
fadeFrom?: string
/** Padding above and below the rendered document. */
docPadding?: string
}
let { content, source, pre }: Props = $props()
let {
content,
source,
pre,
fadeFrom = 'from-surface-tertiary',
docPadding = 'pb-16 pt-8'
}: Props = $props()
// The shared chain (raw HTML re-parsed, then sanitized) rather than a chat-only one, because
// this body also renders what another member wrote. Renderers merge in order, so the chat's
@@ -49,10 +59,9 @@
{:else}
<!-- Pinned under the header, fades scrolled-under content instead of hard-clipping it.
The negative margin cancels its flow height so it overlays instead of pushing. -->
<div class="sticky top-0 z-10 h-4 -mb-4 bg-gradient-to-b from-surface-tertiary to-transparent"
></div>
<div class="sticky top-0 z-10 h-4 -mb-4 bg-gradient-to-b {fadeFrom} to-transparent"></div>
<div class="wm-doc-frame">
<div class="wm-doc pb-16 pt-8">
<div class="wm-doc {docPadding}">
<Markdown md={content} {plugins} />
</div>
</div>
+42 -3
View File
@@ -1,4 +1,4 @@
import { HelpersService, OpenAPI } from '$lib/gen'
import { AppService, HelpersService, OpenAPI } from '$lib/gen'
import { getHeaders } from '$lib/gen/core/request'
import { ColumnIdentity, type ColumnDef } from './apps/components/display/dbtable/utils'
import type { IDbTableOps } from './dbOps'
@@ -18,6 +18,9 @@ export type S3TableSource = {
s3ResourcePath?: string
csvSeparator?: string
csvHasHeader?: boolean
/** Read through a deployed app's `apps_u/*` routes, which take no column filters and
* no header flag. */
app?: { path: string; presigned?: string }
}
type Chunk = {
@@ -47,14 +50,29 @@ export async function s3TableOps(
): Promise<{ ops: IDbTableOps; csvSeparator?: string }> {
const format = serverTableFormat(source.fileKey)
if (!format) throw new Error(`${source.fileKey} cannot be read as a table`)
const app = source.app
const common = {
workspace: source.workspace,
path: source.fileKey,
storage: source.storage,
s3ResourcePath: source.s3ResourcePath
}
const signed = new URLSearchParams(app?.presigned ?? '')
const appCommon = app && {
workspace: source.workspace,
path: app.path,
fileKey: source.fileKey,
storage: source.storage,
sig: signed.get('sig') ?? undefined,
exp: signed.get('exp') ?? undefined
}
const csvOptions: { csvSeparator?: string; csvHasHeader?: boolean } =
format === 'csv' ? { csvSeparator: source.csvSeparator, csvHasHeader: source.csvHasHeader } : {}
format === 'csv'
? {
csvSeparator: source.csvSeparator,
csvHasHeader: app ? undefined : source.csvHasHeader
}
: {}
const filtersParam = (columnFilters: Record<string, unknown> | undefined) =>
columnFilters && Object.keys(columnFilters).length ? JSON.stringify(columnFilters) : undefined
const searchParam = (quicksearch: string) => quicksearch.trim() || undefined
@@ -77,6 +95,20 @@ export async function s3TableOps(
sortCol: params.orderBy,
sortDesc: params.isDesc
}
if (appCommon) {
const appData = {
...appCommon,
csvSeparator: csvOptions.csvSeparator,
offset: data.offset,
limit: data.limit,
searchTerm: data.searchTerm,
sortCol: data.sortCol,
sortDesc: data.sortDesc
}
return (await (format === 'parquet'
? AppService.appLoadParquetPreview(appData)
: AppService.appLoadCsvPreview(appData))) as Chunk
}
return (await (format === 'parquet'
? HelpersService.loadParquetPreview(data)
: HelpersService.loadCsvPreview(data))) as Chunk
@@ -89,7 +121,7 @@ export async function s3TableOps(
field,
datatype: datatypeOf(head.column_types?.[i]),
// The server cannot read a struct, map or union as text to filter it.
filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ""),
filterable: !app && !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ''),
defaultvalue: '',
isprimarykey: false,
isidentity: ColumnIdentity.No,
@@ -102,6 +134,13 @@ export async function s3TableOps(
tableKey: source.fileKey.split('/').pop() ?? source.fileKey,
colDefs,
getCount: async ({ quicksearch, columnFilters }) => {
if (appCommon) {
const res = await AppService.appLoadTableCount({
...appCommon,
searchTerm: searchParam(quicksearch)
})
return res.count ?? 0
}
const res = await HelpersService.loadTableRowCount({
...common,
...csvOptions,