mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-17 08:20:12 +00:00
feat: download session artifacts as pdf (#12182)
* feat: download session artifacts as pdf Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: wrap code and wait only on pending diagrams in artifact pdf Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: wait for markdown images before printing an artifact Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: iterate stylesheet nodes through Array.from for ci's dom lib 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
67dcf145f4
commit
b532c81971
@@ -28,12 +28,15 @@
|
||||
applyButtonIcon = undefined,
|
||||
// Render ```mermaid blocks as diagrams. Off by default so untrusted
|
||||
// markdown surfaces don't execute mermaid — the chat opts in.
|
||||
renderMermaid = false
|
||||
renderMermaid = false,
|
||||
// Draw diagrams in the light theme whatever the app's theme (printing).
|
||||
lightMermaid = false
|
||||
}: {
|
||||
showApplyButton?: boolean
|
||||
onApplyCode?: () => void
|
||||
applyButtonIcon?: typeof ClipboardCopy
|
||||
renderMermaid?: boolean
|
||||
lightMermaid?: boolean
|
||||
} = $props()
|
||||
|
||||
const astNode = getAstNode()
|
||||
@@ -131,7 +134,7 @@
|
||||
<div class="flex flex-col gap-0.5 rounded-md relative not-prose !text-xs">
|
||||
<div class="relative w-full bg-surface-secondary rounded-md overflow-hidden">
|
||||
{#if renderMermaid && language === 'mermaid'}
|
||||
<MermaidDisplay code={code ?? ''} />
|
||||
<MermaidDisplay code={code ?? ''} forceLight={lightMermaid} />
|
||||
{:else}
|
||||
<HighlightCode
|
||||
className="px-3 py-2.5 !text-xs"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { Check, Copy, Download } from 'lucide-svelte'
|
||||
import { Check, Copy, Download, FileDown } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import { copyToClipboard, download } from '$lib/utils'
|
||||
import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB'
|
||||
import { printArtifact } from './printArtifact'
|
||||
|
||||
interface Props {
|
||||
name: string
|
||||
@@ -31,11 +32,23 @@
|
||||
title="Copy raw markdown"
|
||||
dropdownItems={[
|
||||
{
|
||||
label: 'Download as .md',
|
||||
label: `Download as .${kind}`,
|
||||
icon: Download,
|
||||
onClick: () => download(artifactFilename({ name, kind }), content, artifactMimeType(kind)),
|
||||
disabled
|
||||
}
|
||||
},
|
||||
// Markdown only: an html artifact is agent-written markup, and printing it would run its
|
||||
// scripts in this origin.
|
||||
...(kind === 'md'
|
||||
? [
|
||||
{
|
||||
label: 'Download as PDF',
|
||||
icon: FileDown,
|
||||
onClick: () => printArtifact(name, content),
|
||||
disabled
|
||||
}
|
||||
]
|
||||
: [])
|
||||
]}
|
||||
>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<script lang="ts">
|
||||
import Markdown from 'svelte-exmarkdown'
|
||||
import { markdownProse } from '$lib/components/markdownProse'
|
||||
import { markdownPlugins } from '$lib/components/markdownPlugins'
|
||||
import ArtifactPrintCodeBlock from './ArtifactPrintCodeBlock.svelte'
|
||||
|
||||
let { content }: { content: string } = $props()
|
||||
|
||||
const plugins = [...markdownPlugins, { renderer: { pre: ArtifactPrintCodeBlock } }]
|
||||
</script>
|
||||
|
||||
<div class={markdownProse.doc}>
|
||||
<Markdown md={content} {plugins} />
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte'
|
||||
</script>
|
||||
|
||||
<!-- The viewer's code block without the chat context its own renderer needs. Mermaid is on as
|
||||
in the viewer: only the session's own artifacts are exported. -->
|
||||
<MarkdownCodeBlock renderMermaid lightMermaid />
|
||||
@@ -0,0 +1,115 @@
|
||||
import { mount, unmount, tick } from 'svelte'
|
||||
import ArtifactPrintBody from './ArtifactPrintBody.svelte'
|
||||
|
||||
/**
|
||||
* Opens the browser's print dialog on a markdown artifact, where "Save as PDF" writes the file.
|
||||
* The browser's print engine keeps the text selectable and the links live, which a
|
||||
* canvas-rendered PDF would not.
|
||||
*
|
||||
* The document is rendered into a hidden iframe with the viewer's renderer rather than printing
|
||||
* this page: the app's own print would include the whole session layout. The iframe copies
|
||||
* this page's stylesheets, and its <html> carries no `dark` class, so the PDF always uses the
|
||||
* light theme.
|
||||
*/
|
||||
// Set while the iframe is being prepared, so a second click before the dialog opens does not
|
||||
// stack a second print behind the first.
|
||||
let preparing = false
|
||||
|
||||
export async function printArtifact(name: string, content: string): Promise<void> {
|
||||
if (preparing) return
|
||||
preparing = true
|
||||
try {
|
||||
await preparePrint(name, content)
|
||||
} finally {
|
||||
preparing = false
|
||||
}
|
||||
}
|
||||
|
||||
async function preparePrint(name: string, content: string): Promise<void> {
|
||||
const iframe = document.createElement('iframe')
|
||||
iframe.setAttribute('aria-hidden', 'true')
|
||||
iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0'
|
||||
document.body.appendChild(iframe)
|
||||
|
||||
const doc = iframe.contentDocument
|
||||
const win = iframe.contentWindow
|
||||
if (!doc || !win) {
|
||||
iframe.remove()
|
||||
return
|
||||
}
|
||||
// The print dialog proposes the title as the PDF's file name.
|
||||
doc.title = name
|
||||
for (const node of Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))) {
|
||||
doc.head.appendChild(node.cloneNode(true))
|
||||
}
|
||||
const page = doc.createElement('style')
|
||||
// Without exact color adjust, browsers drop code-block and callout backgrounds. The break
|
||||
// rules keep a code block, diagram, callout or table row whole and a heading with what follows.
|
||||
// Code blocks scroll on screen; paper cannot, so they wrap and lose their height cap.
|
||||
page.textContent = `
|
||||
@page { margin: 16mm }
|
||||
html, body { background: white }
|
||||
body { margin: 0; print-color-adjust: exact; -webkit-print-color-adjust: exact }
|
||||
pre, svg, blockquote, tr, .markdown-alert { break-inside: avoid }
|
||||
h1, h2, h3, h4, h5, h6 { break-after: avoid }
|
||||
.not-prose, .not-prose * { overflow: visible !important; max-height: none !important }
|
||||
.not-prose pre, .not-prose code { white-space: pre-wrap !important; overflow-wrap: anywhere }
|
||||
`
|
||||
doc.head.appendChild(page)
|
||||
|
||||
// Printing before the stylesheets load gives an unstyled PDF; the cap keeps a link that
|
||||
// never settles from swallowing the click.
|
||||
const stylesheets = Array.from(
|
||||
doc.head.querySelectorAll('link[rel="stylesheet"]'),
|
||||
(link) =>
|
||||
new Promise<void>((resolve) => {
|
||||
link.addEventListener('load', () => resolve(), { once: true })
|
||||
link.addEventListener('error', () => resolve(), { once: true })
|
||||
})
|
||||
)
|
||||
await Promise.race([
|
||||
Promise.all(stylesheets),
|
||||
new Promise((resolve) => setTimeout(resolve, 3000))
|
||||
])
|
||||
|
||||
const component = mount(ArtifactPrintBody, { target: doc.body, props: { content } })
|
||||
await tick()
|
||||
await diagramsSettled(doc)
|
||||
await imagesSettled(doc)
|
||||
await doc.fonts?.ready
|
||||
|
||||
const cleanup = () => {
|
||||
unmount(component)
|
||||
iframe.remove()
|
||||
}
|
||||
// print() blocks until the dialog closes in Chromium and Firefox, but returns at once in
|
||||
// Safari, so the iframe is removed on afterprint rather than after the call.
|
||||
win.addEventListener('afterprint', cleanup, { once: true })
|
||||
win.focus()
|
||||
win.print()
|
||||
}
|
||||
|
||||
/** The print dialog snapshots the document as it is, so an image still loading is missing from
|
||||
* the PDF. A broken image settles through `error`; the cap covers one that never answers. */
|
||||
async function imagesSettled(doc: Document): Promise<void> {
|
||||
const pending = Array.from(doc.images)
|
||||
.filter((img) => !img.complete)
|
||||
.map(
|
||||
(img) =>
|
||||
new Promise<void>((resolve) => {
|
||||
img.addEventListener('load', () => resolve(), { once: true })
|
||||
img.addEventListener('error', () => resolve(), { once: true })
|
||||
})
|
||||
)
|
||||
await Promise.race([Promise.all(pending), new Promise((resolve) => setTimeout(resolve, 10_000))])
|
||||
}
|
||||
|
||||
/** Mermaid draws asynchronously; printing before it lands puts the diagram source in the PDF.
|
||||
* A diagram that fails to parse settles too (as its source), so this waits only on renders
|
||||
* still in flight; the cap covers one that never returns. */
|
||||
async function diagramsSettled(doc: Document): Promise<void> {
|
||||
const deadline = Date.now() + 10_000
|
||||
while (doc.querySelector('[data-mermaid-pending="true"]') && Date.now() < deadline) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
import { ClipboardCopy, Download, Maximize2, Minus, Plus, RotateCcw } from 'lucide-svelte'
|
||||
import type { PanZoom } from 'panzoom'
|
||||
|
||||
let { code }: { code: string } = $props()
|
||||
let { code, forceLight = false }: { code: string; forceLight?: boolean } = $props()
|
||||
|
||||
const isDarkMode = useIsDarkMode()
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
// Monotonic token so an earlier-started render that resolves late can't
|
||||
// overwrite the result of a newer one (out-of-order async on rapid code/theme changes).
|
||||
let renderSeq = 0
|
||||
// False while a render is in flight, true once it drew or failed. Exposed as
|
||||
// data-mermaid-pending so a print can wait for diagrams without counting fences.
|
||||
let settled = $state(false)
|
||||
|
||||
let expanded = $state(false)
|
||||
|
||||
@@ -27,8 +30,10 @@
|
||||
if (!source?.trim()) {
|
||||
svg = undefined
|
||||
renderedCode = undefined
|
||||
settled = true
|
||||
return
|
||||
}
|
||||
settled = false
|
||||
try {
|
||||
const mermaid = (await import('mermaid')).default
|
||||
mermaid.initialize({
|
||||
@@ -65,11 +70,13 @@
|
||||
// Parse failure (often a partial block still streaming in): fall back to the
|
||||
// raw source. `showSvg` already hides any previous diagram since `renderedCode`
|
||||
// no longer matches the current `code`.
|
||||
} finally {
|
||||
if (seq === renderSeq) settled = true
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void render(code, isDarkMode.val)
|
||||
void render(code, !forceLight && isDarkMode.val)
|
||||
})
|
||||
|
||||
// Only show the diagram while it corresponds to the current source.
|
||||
@@ -130,8 +137,8 @@
|
||||
</script>
|
||||
|
||||
{#if showSvg}
|
||||
<div class="relative">
|
||||
<div class="absolute top-2 right-2 z-20 flex flex-row gap-1">
|
||||
<div class="relative" data-mermaid-pending={!settled}>
|
||||
<div class="absolute top-2 right-2 z-20 flex flex-row gap-1 print:hidden">
|
||||
<Button
|
||||
onclick={() => copyToClipboard(code)}
|
||||
color="light"
|
||||
@@ -213,5 +220,5 @@
|
||||
</Modal>
|
||||
{:else}
|
||||
<!-- Fallback while loading or when rendering fails: show the raw source -->
|
||||
<pre class="overflow-auto max-h-screen text-xs p-2">{code}</pre>
|
||||
<pre class="overflow-auto max-h-screen text-xs p-2" data-mermaid-pending={!settled}>{code}</pre>
|
||||
{/if}
|
||||
|
||||
Reference in New Issue
Block a user