fix: white background option for export + Firefox download

Fixes two issues reported in #165:

- Export always produced a black background, making prints with a
  white page wasteful/unreadable. Adds a Dark/White background choice
  in the export modal, threaded through both PNG and SVG export.
- Firefox refused the download because the programmatic anchor was not
  attached to the document. The anchor is now appended before click and
  removed after, which Firefox requires.

Closes #165

ha-relevant: yes
This commit is contained in:
Pouzor
2026-06-29 00:47:39 +02:00
parent 8b9972ca78
commit fd2c50c1aa
4 changed files with 129 additions and 13 deletions
+38 -3
View File
@@ -2,7 +2,15 @@ import { useState } from 'react'
import { Download, Loader2 } from 'lucide-react' import { Download, Loader2 } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { exportToPng, exportToSvg, EXPORT_QUALITY_OPTIONS, type ExportQuality, type ExportFormat } from '@/utils/export' import {
exportToPng,
exportToSvg,
EXPORT_QUALITY_OPTIONS,
EXPORT_BACKGROUND_OPTIONS,
type ExportQuality,
type ExportFormat,
type ExportBackground,
} from '@/utils/export'
interface ExportModalProps { interface ExportModalProps {
open: boolean open: boolean
@@ -13,6 +21,7 @@ interface ExportModalProps {
export function ExportModal({ open, onClose, getElement }: ExportModalProps) { export function ExportModal({ open, onClose, getElement }: ExportModalProps) {
const [quality, setQuality] = useState<ExportQuality>('high') const [quality, setQuality] = useState<ExportQuality>('high')
const [format, setFormat] = useState<ExportFormat>('png') const [format, setFormat] = useState<ExportFormat>('png')
const [background, setBackground] = useState<ExportBackground>('dark')
const [exporting, setExporting] = useState(false) const [exporting, setExporting] = useState(false)
const handleExport = async () => { const handleExport = async () => {
@@ -21,9 +30,9 @@ export function ExportModal({ open, onClose, getElement }: ExportModalProps) {
setExporting(true) setExporting(true)
try { try {
if (format === 'svg') { if (format === 'svg') {
await exportToSvg(el) await exportToSvg(el, background)
} else { } else {
await exportToPng(el, quality) await exportToPng(el, quality, background)
} }
onClose() onClose()
} finally { } finally {
@@ -70,6 +79,32 @@ export function ExportModal({ open, onClose, getElement }: ExportModalProps) {
</button> </button>
</div> </div>
<div className="space-y-1.5 pb-2">
<p className="text-xs font-medium text-muted-foreground">Background</p>
<div className="flex gap-2">
{EXPORT_BACKGROUND_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => setBackground(opt.value)}
className={[
'flex-1 flex items-center gap-2 px-3 py-2 rounded-md border text-sm transition-colors',
background === opt.value
? 'border-[#00d4ff] bg-[#00d4ff10] text-foreground'
: 'border-border bg-[#0d1117] text-muted-foreground hover:border-muted-foreground',
].join(' ')}
>
<span
className="h-3.5 w-3.5 rounded-sm border border-border"
style={{ background: opt.color }}
/>
<span className="font-medium">{opt.label}</span>
<span className="text-xs opacity-70">{opt.hint}</span>
</button>
))}
</div>
</div>
<DialogFooter className="gap-2"> <DialogFooter className="gap-2">
<Button variant="ghost" onClick={onClose} disabled={exporting}>Cancel</Button> <Button variant="ghost" onClick={onClose} disabled={exporting}>Cancel</Button>
<Button <Button
@@ -12,6 +12,10 @@ vi.mock('@/utils/export', () => ({
{ value: 'high', label: 'High', pixelRatio: 2, hint: '2× — recommended' }, { value: 'high', label: 'High', pixelRatio: 2, hint: '2× — recommended' },
{ value: 'ultra', label: 'Ultra', pixelRatio: 4, hint: '4× — print quality, large file' }, { value: 'ultra', label: 'Ultra', pixelRatio: 4, hint: '4× — print quality, large file' },
], ],
EXPORT_BACKGROUND_OPTIONS: [
{ value: 'dark', label: 'Dark', color: '#0d1117', hint: 'screen / docs' },
{ value: 'white', label: 'White', color: '#ffffff', hint: 'printing' },
],
})) }))
const el = document.createElement('div') const el = document.createElement('div')
@@ -49,7 +53,7 @@ describe('ExportModal', () => {
render(<ExportModal open onClose={onClose} getElement={getElement} />) render(<ExportModal open onClose={onClose} getElement={getElement} />)
fireEvent.click(screen.getByText('Standard').closest('button')!) fireEvent.click(screen.getByText('Standard').closest('button')!)
fireEvent.click(screen.getByRole('button', { name: /download/i })) fireEvent.click(screen.getByRole('button', { name: /download/i }))
await waitFor(() => expect(mockExportToPng).toHaveBeenCalledWith(el, 'standard')) await waitFor(() => expect(mockExportToPng).toHaveBeenCalledWith(el, 'standard', 'dark'))
}) })
it('renders an SVG option under the quality options', () => { it('renders an SVG option under the quality options', () => {
@@ -62,7 +66,7 @@ describe('ExportModal', () => {
fireEvent.click(screen.getByText('SVG').closest('button')!) fireEvent.click(screen.getByText('SVG').closest('button')!)
expect(screen.getByText('SVG').closest('button')!.className).toContain('border-[#00d4ff]') expect(screen.getByText('SVG').closest('button')!.className).toContain('border-[#00d4ff]')
fireEvent.click(screen.getByRole('button', { name: /download/i })) fireEvent.click(screen.getByRole('button', { name: /download/i }))
await waitFor(() => expect(mockExportToSvg).toHaveBeenCalledWith(el)) await waitFor(() => expect(mockExportToSvg).toHaveBeenCalledWith(el, 'dark'))
expect(mockExportToPng).not.toHaveBeenCalled() expect(mockExportToPng).not.toHaveBeenCalled()
}) })
@@ -74,6 +78,28 @@ describe('ExportModal', () => {
expect(screen.getByText('SVG').closest('button')!.className).not.toContain('border-[#00d4ff]') expect(screen.getByText('SVG').closest('button')!.className).not.toContain('border-[#00d4ff]')
}) })
it('renders dark and white background options, dark selected by default', () => {
render(<ExportModal open onClose={onClose} getElement={getElement} />)
expect(screen.getByText('Dark')).toBeInTheDocument()
expect(screen.getByText('White')).toBeInTheDocument()
expect(screen.getByText('Dark').closest('button')!.className).toContain('border-[#00d4ff]')
})
it('exports with white background when White is selected (printing)', async () => {
render(<ExportModal open onClose={onClose} getElement={getElement} />)
fireEvent.click(screen.getByText('White').closest('button')!)
fireEvent.click(screen.getByRole('button', { name: /download/i }))
await waitFor(() => expect(mockExportToPng).toHaveBeenCalledWith(el, 'high', 'white'))
})
it('applies the background choice to SVG export too', async () => {
render(<ExportModal open onClose={onClose} getElement={getElement} />)
fireEvent.click(screen.getByText('SVG').closest('button')!)
fireEvent.click(screen.getByText('White').closest('button')!)
fireEvent.click(screen.getByRole('button', { name: /download/i }))
await waitFor(() => expect(mockExportToSvg).toHaveBeenCalledWith(el, 'white'))
})
it('closes after successful export', async () => { it('closes after successful export', async () => {
render(<ExportModal open onClose={onClose} getElement={getElement} />) render(<ExportModal open onClose={onClose} getElement={getElement} />)
fireEvent.click(screen.getByRole('button', { name: /download/i })) fireEvent.click(screen.getByRole('button', { name: /download/i }))
+39 -4
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { exportToPng, exportToSvg, EXPORT_QUALITY_OPTIONS } from '../export' import { exportToPng, exportToSvg, EXPORT_QUALITY_OPTIONS, EXPORT_BACKGROUND_OPTIONS } from '../export'
const mockToPng = vi.fn() const mockToPng = vi.fn()
const mockToSvg = vi.fn() const mockToSvg = vi.fn()
@@ -12,6 +12,7 @@ describe('exportToPng', () => {
let el: HTMLElement let el: HTMLElement
let clickSpy: ReturnType<typeof vi.fn> let clickSpy: ReturnType<typeof vi.fn>
let appendSpy: ReturnType<typeof vi.spyOn> let appendSpy: ReturnType<typeof vi.spyOn>
let removeSpy: ReturnType<typeof vi.spyOn>
let createSpy: ReturnType<typeof vi.spyOn> let createSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => { beforeEach(() => {
@@ -21,6 +22,7 @@ describe('exportToPng', () => {
Object.assign(document.createElement('a'), { click: clickSpy }) as HTMLAnchorElement Object.assign(document.createElement('a'), { click: clickSpy }) as HTMLAnchorElement
) )
appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((n) => n) appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((n) => n)
removeSpy = vi.spyOn(document.body, 'removeChild').mockImplementation((n) => n)
mockToPng.mockResolvedValue('data:image/png;base64,abc') mockToPng.mockResolvedValue('data:image/png;base64,abc')
mockToSvg.mockResolvedValue('data:image/svg+xml;base64,abc') mockToSvg.mockResolvedValue('data:image/svg+xml;base64,abc')
}) })
@@ -28,6 +30,7 @@ describe('exportToPng', () => {
afterEach(() => { afterEach(() => {
createSpy.mockRestore() createSpy.mockRestore()
appendSpy.mockRestore() appendSpy.mockRestore()
removeSpy.mockRestore()
}) })
it('calls toPng with pixelRatio 1 for standard quality', async () => { it('calls toPng with pixelRatio 1 for standard quality', async () => {
@@ -55,15 +58,28 @@ describe('exportToPng', () => {
expect(clickSpy).toHaveBeenCalled() expect(clickSpy).toHaveBeenCalled()
}) })
it('passes dark background color', async () => { it('defaults to dark background color', async () => {
await exportToPng(el, 'standard') await exportToPng(el, 'standard')
expect(mockToPng).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#0d1117' })) expect(mockToPng).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#0d1117' }))
}) })
it('uses white background color when white is requested (printing)', async () => {
await exportToPng(el, 'standard', 'white')
expect(mockToPng).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#ffffff' }))
})
it('attaches the download anchor to the DOM so Firefox triggers the download', async () => {
await exportToPng(el, 'high')
expect(appendSpy).toHaveBeenCalled()
expect(removeSpy).toHaveBeenCalled()
})
}) })
describe('exportToSvg', () => { describe('exportToSvg', () => {
let el: HTMLElement let el: HTMLElement
let clickSpy: ReturnType<typeof vi.fn> let clickSpy: ReturnType<typeof vi.fn>
let appendSpy: ReturnType<typeof vi.spyOn>
let removeSpy: ReturnType<typeof vi.spyOn>
let createSpy: ReturnType<typeof vi.spyOn> let createSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => { beforeEach(() => {
@@ -72,18 +88,27 @@ describe('exportToSvg', () => {
createSpy = vi.spyOn(document, 'createElement').mockReturnValue( createSpy = vi.spyOn(document, 'createElement').mockReturnValue(
Object.assign(document.createElement('a'), { click: clickSpy }) as HTMLAnchorElement Object.assign(document.createElement('a'), { click: clickSpy }) as HTMLAnchorElement
) )
appendSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((n) => n)
removeSpy = vi.spyOn(document.body, 'removeChild').mockImplementation((n) => n)
mockToSvg.mockResolvedValue('data:image/svg+xml;base64,abc') mockToSvg.mockResolvedValue('data:image/svg+xml;base64,abc')
}) })
afterEach(() => { afterEach(() => {
createSpy.mockRestore() createSpy.mockRestore()
appendSpy.mockRestore()
removeSpy.mockRestore()
}) })
it('calls toSvg with dark background color', async () => { it('defaults to dark background color', async () => {
await exportToSvg(el) await exportToSvg(el)
expect(mockToSvg).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#0d1117' })) expect(mockToSvg).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#0d1117' }))
}) })
it('uses white background color when white is requested (printing)', async () => {
await exportToSvg(el, 'white')
expect(mockToSvg).toHaveBeenCalledWith(el, expect.objectContaining({ backgroundColor: '#ffffff' }))
})
it('triggers a download', async () => { it('triggers a download', async () => {
await exportToSvg(el) await exportToSvg(el)
expect(clickSpy).toHaveBeenCalled() expect(clickSpy).toHaveBeenCalled()
@@ -103,3 +128,13 @@ describe('EXPORT_QUALITY_OPTIONS', () => {
expect(EXPORT_QUALITY_OPTIONS.map((o) => o.pixelRatio)).toEqual([1, 2, 4]) expect(EXPORT_QUALITY_OPTIONS.map((o) => o.pixelRatio)).toEqual([1, 2, 4])
}) })
}) })
describe('EXPORT_BACKGROUND_OPTIONS', () => {
it('offers dark and white', () => {
expect(EXPORT_BACKGROUND_OPTIONS.map((o) => o.value)).toEqual(['dark', 'white'])
})
it('maps to the expected colors', () => {
expect(EXPORT_BACKGROUND_OPTIONS.map((o) => o.color)).toEqual(['#0d1117', '#ffffff'])
})
})
+24 -4
View File
@@ -2,6 +2,7 @@ import { toPng, toSvg } from 'html-to-image'
export type ExportQuality = 'standard' | 'high' | 'ultra' export type ExportQuality = 'standard' | 'high' | 'ultra'
export type ExportFormat = 'png' | 'svg' export type ExportFormat = 'png' | 'svg'
export type ExportBackground = 'dark' | 'white'
export const EXPORT_QUALITY_OPTIONS: { value: ExportQuality; label: string; pixelRatio: number; hint: string }[] = [ export const EXPORT_QUALITY_OPTIONS: { value: ExportQuality; label: string; pixelRatio: number; hint: string }[] = [
{ value: 'standard', label: 'Standard', pixelRatio: 1, hint: '1× — small file' }, { value: 'standard', label: 'Standard', pixelRatio: 1, hint: '1× — small file' },
@@ -9,10 +10,23 @@ export const EXPORT_QUALITY_OPTIONS: { value: ExportQuality; label: string; pixe
{ value: 'ultra', label: 'Ultra', pixelRatio: 4, hint: '4× — print quality, large file' }, { value: 'ultra', label: 'Ultra', pixelRatio: 4, hint: '4× — print quality, large file' },
] ]
export async function exportToPng(element: HTMLElement, quality: ExportQuality = 'high'): Promise<void> { export const EXPORT_BACKGROUND_OPTIONS: { value: ExportBackground; label: string; color: string; hint: string }[] = [
{ value: 'dark', label: 'Dark', color: '#0d1117', hint: 'screen / docs' },
{ value: 'white', label: 'White', color: '#ffffff', hint: 'printing' },
]
function backgroundColor(background: ExportBackground): string {
return (EXPORT_BACKGROUND_OPTIONS.find((o) => o.value === background) ?? EXPORT_BACKGROUND_OPTIONS[0]).color
}
export async function exportToPng(
element: HTMLElement,
quality: ExportQuality = 'high',
background: ExportBackground = 'dark',
): Promise<void> {
const option = EXPORT_QUALITY_OPTIONS.find((o) => o.value === quality) ?? EXPORT_QUALITY_OPTIONS[1] const option = EXPORT_QUALITY_OPTIONS.find((o) => o.value === quality) ?? EXPORT_QUALITY_OPTIONS[1]
const dataUrl = await toPng(element, { const dataUrl = await toPng(element, {
backgroundColor: '#0d1117', backgroundColor: backgroundColor(background),
pixelRatio: option.pixelRatio, pixelRatio: option.pixelRatio,
style: { style: {
'--xy-controls-display': 'none', '--xy-controls-display': 'none',
@@ -22,9 +36,12 @@ export async function exportToPng(element: HTMLElement, quality: ExportQuality =
triggerDownload(dataUrl, 'homelable-canvas.png') triggerDownload(dataUrl, 'homelable-canvas.png')
} }
export async function exportToSvg(element: HTMLElement): Promise<void> { export async function exportToSvg(
element: HTMLElement,
background: ExportBackground = 'dark',
): Promise<void> {
const dataUrl = await toSvg(element, { const dataUrl = await toSvg(element, {
backgroundColor: '#0d1117', backgroundColor: backgroundColor(background),
style: { style: {
'--xy-controls-display': 'none', '--xy-controls-display': 'none',
} as Partial<CSSStyleDeclaration>, } as Partial<CSSStyleDeclaration>,
@@ -37,5 +54,8 @@ function triggerDownload(dataUrl: string, filename: string): void {
const link = document.createElement('a') const link = document.createElement('a')
link.download = filename link.download = filename
link.href = dataUrl link.href = dataUrl
// Firefox only triggers a programmatic click when the anchor is in the DOM.
document.body.appendChild(link)
link.click() link.click()
document.body.removeChild(link)
} }