From f65f3e7b8cb0771832962b581e18a157f2927bbf Mon Sep 17 00:00:00 2001 From: Bastien Chanot Date: Mon, 18 May 2026 21:03:52 +0200 Subject: [PATCH] feat(anatomy): implement loadSvg via fetch + DOMParser --- src/anatomy/svgLoader.ts | 26 ++++++++++++++++---------- tests/unit/anatomy.svgLoader.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) create mode 100644 tests/unit/anatomy.svgLoader.test.ts diff --git a/src/anatomy/svgLoader.ts b/src/anatomy/svgLoader.ts index 802797b0..f561e025 100644 --- a/src/anatomy/svgLoader.ts +++ b/src/anatomy/svgLoader.ts @@ -1,15 +1,21 @@ -/** - * Fetches an SVG file and parses it into a live DOM element. - * Uses DOMParser so the SVG is fully controlled by the app's CSS. - */ -export async function loadSvg(_publicPath: string): Promise { - throw new Error('not implemented') +export async function loadSvg(publicPath: string): Promise { + const resp = await fetch(publicPath) + if (!resp.ok) { + throw new Error(`Failed to load SVG ${publicPath}: HTTP ${resp.status}`) + } + const text = await resp.text() + const doc = new DOMParser().parseFromString(text, 'image/svg+xml') + const parseErr = doc.querySelector('parsererror') + if (parseErr) { + throw new Error(`Invalid SVG at ${publicPath}: ${parseErr.textContent}`) + } + const root = doc.documentElement + if (root.tagName.toLowerCase() !== 'svg') { + throw new Error(`Root element of ${publicPath} is not `) + } + return root as unknown as SVGSVGElement } -/** - * Rasterizes an SVGSVGElement to a PNG data URL at the given scale factor. - * Uses canvg under the hood for A4 print quality. - */ export async function svgToPngDataUrl( _svgEl: SVGSVGElement, _scale: number, diff --git a/tests/unit/anatomy.svgLoader.test.ts b/tests/unit/anatomy.svgLoader.test.ts new file mode 100644 index 00000000..11af451e --- /dev/null +++ b/tests/unit/anatomy.svgLoader.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { loadSvg } from '@/anatomy/svgLoader' + +const SVG = '' + +describe('loadSvg', () => { + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => ({ + ok: true, + text: async () => SVG, + })) as unknown as typeof fetch) + }) + + it('returns an SVGSVGElement', async () => { + const root = await loadSvg('/whatever.svg') + expect(root.tagName.toLowerCase()).toBe('svg') + }) + + it('throws on non-ok response', async () => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch) + await expect(loadSvg('/missing.svg')).rejects.toThrow() + }) +})