Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/svg-download-inline-images.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lglab/react-qr-code': patch
---

Embed images in SVG downloads as data URLs, so a downloaded SVG with an image still shows it offline and when printed. If the image can't be fetched (for example because of CORS), the original URL is kept.
1 change: 1 addition & 0 deletions apps/docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@radix-ui/react-accordion": "^1.2.21",
"@radix-ui/react-checkbox": "^1.3.12",
"@radix-ui/react-dialog": "^1.2.0",
"@radix-ui/react-dropdown-menu": "^2.1.25",
"@radix-ui/react-label": "^2.1.16",
"@radix-ui/react-popover": "^1.2.0",
"@radix-ui/react-select": "^2.3.8",
Expand Down
1 change: 1 addition & 0 deletions apps/docs/public/images/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 31 additions & 8 deletions apps/docs/src/components/demo/demo.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use client'

import {
type DownloadFileFormat,
type FrameSettings,
ReactQRCode,
type ReactQRCodeProps,
type ReactQRCodeRef,
} from '@lglab/react-qr-code'
import { ChevronDown } from 'lucide-react'
import { type PropsWithChildren, useRef, useState } from 'react'

import {
Expand All @@ -15,6 +17,12 @@ import {
AccordionTrigger,
} from '@/components/ui/accordion'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

import { Colors } from './colors'
import { DataModules } from './data-modules'
Expand All @@ -25,7 +33,7 @@ import { ImageSettingsDemo } from './image-settings'
import { MainSettings } from './main-settings'

export const defaultImageSettings = {
src: 'https://reactqrcode.com/images/logo-60.png',
src: 'https://reactqrcode.com/images/logo.svg',
width: 60,
height: 60,
excavate: true,
Expand Down Expand Up @@ -88,6 +96,9 @@ export const Demo = () => {
imageSettings: defaultImageSettings,
})

const download = (format: DownloadFileFormat) =>
qrRef.current?.download({ name: 'qr-code', format, size: 1000 })

return (
<div className='grid grid-cols-1 gap-4 sm:grid-cols-5'>
<div className='sm:col-span-3'>
Expand Down Expand Up @@ -138,13 +149,25 @@ export const Demo = () => {
</div>
<div className='flex flex-col items-center gap-3 sm:col-span-2 [&>svg]:h-auto'>
<ReactQRCode {...qrProps} ref={qrRef} />
<Button
onClick={() =>
qrRef.current?.download({ name: 'qr-code', format: 'png', size: 1000 })
}
>
Download PNG
</Button>
<div className='flex'>
<Button className='rounded-r-none' onClick={() => download('png')}>
Download PNG
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
aria-label='More download formats'
className='rounded-l-none border-l border-primary-foreground/20 px-2'
>
<ChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align='end'>
<DropdownMenuItem onSelect={() => download('png')}>PNG</DropdownMenuItem>
<DropdownMenuItem onSelect={() => download('svg')}>SVG</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
)
Expand Down
45 changes: 45 additions & 0 deletions apps/docs/src/components/ui/dropdown-menu.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'use client'

import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'
import * as React from 'react'

import { cn } from '@/lib/utils'

const DropdownMenu = DropdownMenuPrimitive.Root

const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger

const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName

const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
className,
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName

export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem }
2 changes: 1 addition & 1 deletion packages/react-qr-code/src/react-qr-code.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const ReactQRCode = forwardRef<ReactQRCodeRef, ReactQRCodeProps>((props, ref) =>
if (!svgRef.current) return

if (fileFormat === 'svg') {
downloadSVG({ svgRef, fileSize, fileName })
void downloadSVG({ svgRef, fileSize, fileName })
} else {
downloadRaster({
svgRef,
Expand Down
69 changes: 68 additions & 1 deletion packages/react-qr-code/src/utils/download.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'

import { DEFAULT_BGCOLOR } from '../constants'
import type { DownloadFileFormat } from '../types/lib'
import { downloadRaster, getFileHeight } from './download'
import { downloadRaster, getFileHeight, inlineImages } from './download'

const svgWithViewBox = (width: number, height: number) =>
({ viewBox: { baseVal: { width, height } } }) as unknown as SVGSVGElement
Expand Down Expand Up @@ -70,3 +70,70 @@ describe('downloadRaster', () => {
expect(ctx.fillRect).not.toHaveBeenCalled()
})
})

describe('inlineImages', () => {
const svgWithImage = (href: string) => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image')
image.setAttribute('href', href)
svg.appendChild(image)
return { svg, image }
}

afterEach(() => {
vi.unstubAllGlobals()
})

it('replaces linked images with data URLs', async () => {
const blob = new Blob(['<svg/>'], { type: 'image/svg+xml' })
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: true, blob: async () => blob })),
)
const { svg, image } = svgWithImage('https://example.com/logo.svg')
await inlineImages(svg)
expect(image.getAttribute('href')).toMatch(/^data:image\/svg\+xml;base64,/)
})

it('keeps the original href when the fetch fails', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => {
throw new TypeError('Failed to fetch')
}),
)
const { svg, image } = svgWithImage('https://example.com/logo.svg')
await inlineImages(svg)
expect(image.getAttribute('href')).toBe('https://example.com/logo.svg')
})

it('keeps the original href on an HTTP error', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 404 })),
)
const { svg, image } = svgWithImage('https://example.com/missing.svg')
await inlineImages(svg)
expect(image.getAttribute('href')).toBe('https://example.com/missing.svg')
})

it('sends credentials when the image uses use-credentials', async () => {
const blob = new Blob(['<svg/>'], { type: 'image/svg+xml' })
const fetchMock = vi.fn(async () => ({ ok: true, blob: async () => blob }))
vi.stubGlobal('fetch', fetchMock)
const { svg, image } = svgWithImage('https://example.com/logo.svg')
image.setAttribute('crossorigin', 'use-credentials')
await inlineImages(svg)
expect(fetchMock).toHaveBeenCalledWith('https://example.com/logo.svg', {
credentials: 'include',
})
})

it('leaves data URLs untouched', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const { svg } = svgWithImage('data:image/png;base64,AAAA')
await inlineImages(svg)
expect(fetchMock).not.toHaveBeenCalled()
})
})
35 changes: 34 additions & 1 deletion packages/react-qr-code/src/utils/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,45 @@ export const getFileHeight = (svg: SVGSVGElement, fileSize: number) => {
return width && height ? Math.round((fileSize * height) / width) : fileSize
}

export const downloadSVG = ({ svgRef, fileSize, fileName }: DownloadSVGProps) => {
const toDataURL = async (src: string, credentials: RequestCredentials) => {
const response = await fetch(src, { credentials })
if (!response.ok) throw new Error(`Failed to fetch ${src}: ${response.status}`)
const blob = await response.blob()
return new Promise<string>((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(reader.error)
reader.readAsDataURL(blob)
})
}

// Embed linked images so the downloaded file works offline; keep the link if the fetch fails (e.g. CORS).
export const inlineImages = async (svg: SVGSVGElement) => {
const images = Array.from(svg.querySelectorAll('image'))
await Promise.all(
images.map(async (image) => {
const href = image.getAttribute('href')
if (!href || href.startsWith('data:')) return
try {
const credentials =
image.getAttribute('crossorigin') === 'use-credentials'
? 'include'
: 'same-origin'
image.setAttribute('href', await toDataURL(href, credentials))
} catch {
// Keep the original href
}
}),
)
}

export const downloadSVG = async ({ svgRef, fileSize, fileName }: DownloadSVGProps) => {
if (!svgRef.current) return

const clonedSvg = svgRef.current.cloneNode(true) as SVGSVGElement
clonedSvg.setAttribute('width', fileSize.toString())
clonedSvg.setAttribute('height', getFileHeight(svgRef.current, fileSize).toString())
await inlineImages(clonedSvg)

const serializer = new XMLSerializer()
const svgBlob = new Blob([serializer.serializeToString(clonedSvg)], {
Expand Down
70 changes: 70 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading