fix: restore app column filters and parquet csv export in the s3 card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-27 01:32:35 -08:00
co-authored by Claude Opus 5.5
parent 327873eb66
commit 78f963a04f
10 changed files with 115 additions and 52 deletions
+1 -2
View File
@@ -165,7 +165,6 @@
// ── Filters ──────────────────────────────────────────────────────────────
let filterSchema = $derived(buildDbTableFilterSchema(columns))
let hasColumnFilters = $derived(Object.values(filterSchema.schema).some((f) => !f.hidden))
let filters: Record<string, any> = $state({})
let quicksearch = $derived(unescapeFreeText(String(filters[FREE_TEXT_KEY] ?? '')))
let filterWhere = $derived(
@@ -1055,7 +1054,7 @@
dropdownOffsetY={1}
schema={filterSchema.schema}
bind:value={filters}
placeholder={compact || !hasColumnFilters ? 'Search' : '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?.()}
@@ -213,7 +213,10 @@
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'
// Fetched on display, unlike an image, so not for a viewer who cannot read the file (a
// logged-out public page).
if (!$userStore && !appPath) return undefined
if (/\.(txt|log)$/i.test(key)) return 'text'
if (isMarkdownFile(key)) return 'markdown'
return undefined
}
@@ -351,7 +354,8 @@
let is_render_all = $state(false)
let download_as_csv = $state(false)
function inferResultKind(result: any) {
if (typeof result === 'string' && result.match(/s3:\/\/[^/]*\/.+/)) {
// Anchored: a sentence that mentions an `s3://` URI is a plain string.
if (typeof result === 'string' && result.match(/^s3:\/\/[^/]*\/.+/)) {
largeObject = false
return 's3object'
}
@@ -530,6 +534,8 @@
let jsonViewer: Drawer | undefined = $state()
let s3FileViewer: S3FilePicker | undefined = $state()
// The file browser is only mounted with the result's controls.
let canExplore = $derived(!!$userStore && !disableExpand && !noControls)
function checkIfHasBigInt(result: any) {
if (typeof result === 'number' && Number.isInteger(result) && !Number.isSafeInteger(result)) {
@@ -897,8 +903,8 @@
}}
>
{#snippet children({ item })}
<ToggleButton size="xs" value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton size="xs" value="json" label="JSON" icon={Braces} {item} />
<ToggleButton value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton value="json" label="JSON" icon={Braces} {item} />
{/snippet}
</ToggleButtonGroup>
</div>
@@ -945,11 +951,11 @@
>
{#snippet children({ item })}
{#if ['table-col', 'table-row', 'table-row-object'].includes(resultKind ?? '')}
<ToggleButton size="xs" value="table" label="Table" icon={Table2} {item} />
<ToggleButton size="sm" value="table" label="Table" icon={Table2} {item} />
{:else}
<ToggleButton size="xs" value="pretty" label="Pretty" icon={Highlighter} {item} />
<ToggleButton size="sm" value="pretty" label="Pretty" icon={Highlighter} {item} />
{/if}
<ToggleButton size="xs" value="json" label="JSON" icon={Braces} {item} />
<ToggleButton size="sm" value="json" label="JSON" icon={Braces} {item} />
{/snippet}
</ToggleButtonGroup>
{/if}
@@ -1241,7 +1247,7 @@
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
onExplore={canExplore ? () => s3FileViewer?.open?.(s3object) : undefined}
markdownSource={s3PreviewKind(s3object.s3) === 'markdown'
? markdownSourceKeys.includes(s3object.s3)
: undefined}
@@ -1273,7 +1279,7 @@
{s3object}
{workspaceId}
{appPath}
onExplore={$userStore ? () => s3FileViewer?.open?.(s3object) : undefined}
onExplore={canExplore ? () => s3FileViewer?.open?.(s3object) : undefined}
previewOpen={collapsible ? previewOpen : undefined}
onTogglePreview={() => {
seeS3PreviewFileFromList = previewOpen ? '' : s3object?.s3
@@ -715,15 +715,6 @@
})
)
// The filter list has nothing to show when no filter is left to pick (a table with no
// filterable column, or a term matching none) and there are no presets: opening it would
// leave a bare "Filters" heading over the content below.
let hasMenuContent = $derived(
(!!currentTag && !!schema[currentTag]) ||
presets.length > 0 ||
menuItems.some((i) => i.type === 'filter')
)
function appendFilterAsText(presetValue: string) {
// For allowMultiple fields, append value with comma to existing filter instead of adding duplicate key
const match = presetValue.match(/^(\w+):\\\s+(.+)$/)
@@ -830,7 +821,7 @@
</div>
<GenericDropdown
open={(dropdownVisible && hasMenuContent) || freeTextFilterHint}
open={dropdownVisible || freeTextFilterHint}
instantClose={hideDropdownOnFreeText}
getInputRect={() => {
const r = inputElement?.getBoundingClientRect() ?? new DOMRect()
@@ -794,6 +794,8 @@
// the same key, so comparing keys would let an older request speak for a newer one.
const requestId = ++metadataRequestId
fileInfoLoading = true
// Each file opens rendered, as the separator resets per file.
markdownView = 'rendered'
let fileMetadataRaw: LoadFileMetadataResponse
try {
fileMetadataRaw = await loadFileMetadataRequest({
@@ -270,7 +270,7 @@
{/if}
<div
class={twMerge(
'flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary',
'flex flex-col flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary',
bodyClass,
showsText ? 'bg-surface-input' : ''
)}
@@ -365,13 +365,16 @@
</div>
{/if}
{#if filePreview.contentPreview && !emptyString(filePreview.contentPreview)}
<FileTextPreview
content={filePreview.contentPreview}
readLimit={PREVIEW_BYTES}
markdown={isMarkdownFile(filePreview.fileKey)}
fill
{markdownSource}
/>
<!-- Takes the height left under the line above, so only the text scrolls. -->
<div class="flex-1 min-h-0">
<FileTextPreview
content={filePreview.contentPreview}
readLimit={PREVIEW_BYTES}
markdown={isMarkdownFile(filePreview.fileKey)}
fill
{markdownSource}
/>
</div>
{:else if filePreview.contentType !== undefined}
<div class="text-primary">Preview impossible.</div>
{/if}
@@ -1,6 +1,7 @@
<script lang="ts" module>
export function isMarkdownFile(fileKey: string | undefined): boolean {
return /\.(md|markdown)$/i.test(fileKey ?? '')
// Not `.markdown`: the file preview route reads it as an unknown type.
return /\.md$/i.test(fileKey ?? '')
}
// The read stops at a byte count, so a truncated file usually ends mid-line.
@@ -47,7 +47,7 @@
? FileImage
: ['csv', 'parquet'].includes(extension ?? '')
? FileSpreadsheet
: ['pdf', 'txt', 'md', 'json'].includes(extension ?? '')
: ['pdf', 'txt', 'log', 'md', 'markdown', 'json'].includes(extension ?? '')
? FileText
: File
)
@@ -63,7 +63,7 @@
<span class="font-mono">{key}</span>
</span>
</div>
<div class="flex flex-row items-center gap-1 shrink-0 ml-auto">
<div class="flex flex-row flex-wrap justify-end items-center gap-1 min-w-0 ml-auto">
{#if markdownSource !== undefined && onMarkdownSource}
<ToggleButtonGroup
noWFull
@@ -1,10 +1,11 @@
<script lang="ts">
import { ChevronDown, Loader2, PanelTop } from 'lucide-svelte'
import { ChevronDown, FileDown, 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'
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
interface Props {
s3object: { s3: string; storage?: string; presigned?: string; disable_download?: boolean }
@@ -35,7 +36,17 @@
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')
// JSON lines are read through the CSV route too, but have no separator or header row.
let isCsv = $derived(/\.(csv|tsv)$/i.test(s3object.s3))
let isParquet = $derived(serverTableFormat(s3object.s3) === 'parquet')
let workspace = $derived(workspaceId ?? $operatingWorkspace!)
// The server converts the whole file; the table's own export only has the rows it loaded.
let parquetCsvPath = $derived(
appPath
? `/w/${workspace}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}${s3object.presigned ? `&${s3object.presigned}` : ''}`
: `/w/${workspace}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}`
)
let parquetCsvName = $derived((s3object.s3.split('/').pop() ?? 'download') + '.csv')
let width = $state(0)
let separator = $derived(
CSV_SEPARATORS.find((s) => s.value === (csvSeparator ?? detectedSeparator))
@@ -78,7 +89,7 @@
let table = $derived(
s3TableOps({
workspace: workspaceId ?? $operatingWorkspace!,
workspace,
fileKey: s3object.s3,
storage: s3object.storage,
csvSeparator,
@@ -96,13 +107,13 @@
items={separatorItems}
placement="bottom-end"
fixedHeight={false}
triggerLabel="Separator: {separator?.name ?? 'detecting'}{csvSeparator === undefined
? ' (detected)'
: ''}"
triggerLabel={separator
? `Separator: ${separator.name}${csvSeparator === undefined ? ' (detected)' : ''}`
: 'Separator: detect automatically'}
class="h-7 px-2 gap-1 rounded-md text-xs text-primary hover:bg-surface-hover"
>
{#snippet buttonReplacement()}
<span class="font-mono">{separator?.short ?? '…'}</span>
<span class={separator ? 'font-mono' : ''}>{separator?.short ?? 'Auto'}</span>
<ChevronDown size={14} />
{/snippet}
</DropdownV2>
@@ -121,6 +132,42 @@
<div class="w-px h-5 border-l"></div>
{/snippet}
{#snippet parquetControls()}
{#if shouldDownloadViaClient()}
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: FileDown }}
title="Download the whole file as CSV"
onClick={() => downloadViaClient(parquetCsvPath, parquetCsvName)}
/>
{:else}
<Button
variant="subtle"
unifiedSize="sm"
iconOnly
startIcon={{ icon: FileDown }}
title="Download the whole file as CSV"
href="/api{parquetCsvPath}"
download={parquetCsvName}
/>
{/if}
<div class="w-px h-5 border-l"></div>
{/snippet}
<!-- The storage reports an empty file as a failed range read. -->
{#snippet loadError(e: any)}
{@const message = String(e?.body ?? e?.message ?? e)}
{#if /Range started at 0 and ended at 0/.test(message)}
<div class="p-3 text-xs text-secondary">This file is empty.</div>
{:else}
<div class="p-3 text-xs text-red-600 dark:text-red-400 break-words">
Could not read this file as a table: {message}
</div>
{/if}
{/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">
@@ -129,8 +176,12 @@
{:then t}
<t.DBTable
dbTableOps={t.ops}
disableDownload={s3object.disable_download}
toolbar={isCsv ? csvControls : undefined}
disableDownload={s3object.disable_download || isParquet}
toolbar={isCsv
? csvControls
: isParquet && !s3object.disable_download
? parquetControls
: undefined}
compact={width < COMPACT_WIDTH}
/>
{:catch e}
@@ -139,8 +190,6 @@
{@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>
{@render loadError(e)}
{/await}
</div>
@@ -16,7 +16,7 @@
disabled?: boolean
selectedColor?: string | undefined
small?: boolean
size?: 'xs' | 'sm' | 'md' | 'lg'
size?: 'sm' | 'md' | 'lg'
iconProps?: Record<string, any>
showTooltipIcon?: boolean
documentationLink?: string | undefined
+19 -7
View File
@@ -18,8 +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. */
/** Read through a deployed app's `apps_u/*` routes, which take no header flag and no
* `filters`: only a "contains" match on one column (`search_col`), or a search of all of
* them. */
app?: { path: string; presigned?: string }
}
@@ -76,6 +77,13 @@ export async function s3TableOps(
const filtersParam = (columnFilters: Record<string, unknown> | undefined) =>
columnFilters && Object.keys(columnFilters).length ? JSON.stringify(columnFilters) : undefined
const searchParam = (quicksearch: string) => quicksearch.trim() || undefined
// The app routes take one search: the first column filter, else the search of all columns.
const appSearch = (quicksearch: string, columnFilters: Record<string, unknown> | undefined) => {
const [column, value] = Object.entries(columnFilters ?? {})[0] ?? []
return column
? { searchCol: column, searchTerm: String(value ?? '').replace(/^=/, '') }
: { searchTerm: searchParam(quicksearch) }
}
async function loadChunk(params: {
offset: number
@@ -101,7 +109,7 @@ export async function s3TableOps(
csvSeparator: csvOptions.csvSeparator,
offset: data.offset,
limit: data.limit,
searchTerm: data.searchTerm,
...appSearch(params.quicksearch ?? '', params.columnFilters),
sortCol: data.sortCol,
sortDesc: data.sortDesc
}
@@ -120,8 +128,11 @@ export async function s3TableOps(
const colDefs: ColumnDef[] = head.columns.map((field, i) => ({
field,
datatype: datatypeOf(head.column_types?.[i]),
// The server cannot read a struct, map or union as text to filter it.
filterable: !app && !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ''),
// The server cannot read a struct, map or union as text to filter it. The app routes only
// match a substring, so there only text columns take a filter.
filterable: app
? datatypeOf(head.column_types?.[i]) === 'text'
: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ''),
defaultvalue: '',
isprimarykey: false,
isidentity: ColumnIdentity.No,
@@ -131,13 +142,14 @@ export async function s3TableOps(
const ops: IDbTableOps = {
dbType: 'duckdb',
tableKey: source.fileKey.split('/').pop() ?? source.fileKey,
// Named after the file without its extension: the table's CSV export appends `.csv`.
tableKey: (source.fileKey.split('/').pop() ?? source.fileKey).replace(/\.[^.]+$/, ''),
colDefs,
getCount: async ({ quicksearch, columnFilters }) => {
if (appCommon) {
const res = await AppService.appLoadTableCount({
...appCommon,
searchTerm: searchParam(quicksearch)
...appSearch(quicksearch, columnFilters)
})
return res.count ?? 0
}