Skip to content

Commit

Permalink
fix: handle other elements before the svg element (withastro#12516)
Browse files Browse the repository at this point in the history
* fix multiple root nodes

* add changeset

* remove conditional

* handle no svg case
  • Loading branch information
stramel authored Nov 25, 2024
1 parent 1ec852e commit cb9322c
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/eight-seahorses-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Handle multiple root nodes on SVG files
8 changes: 7 additions & 1 deletion packages/astro/src/assets/utils/svg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import type { ImageMetadata } from '../types.js';

function parseSvg(contents: string) {
const root = parse(contents);
const [{ attributes, children }] = root.children;
const svgNode = root.children.find(
({ name, type }: { name: string; type: number }) => type === 1 /* Element */ && name === 'svg',
);
if (!svgNode) {
throw new Error('SVG file does not contain an <svg> element');
}
const { attributes, children } = svgNode;
const body = renderSync({ ...root, children });

return { attributes, body };
Expand Down
11 changes: 11 additions & 0 deletions packages/astro/test/core-image-svg.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,17 @@ describe('astro:assets - SVG Components', () => {
assert.equal(!!$svg.attr('xmlns:xlink'), false);
assert.equal(!!$svg.attr('version'), false);
});
it('ignores additional root level nodes', () => {
let $svg = $('#additionalNodes');
// Ensure we only have the svg node
assert.equal($svg.children().length, 1);
assert.equal($svg.children()[0].name, 'svg');
$svg = $svg.children('svg');
assert.equal($svg.length, 1);
assert.equal(!!$svg.attr('xmlns'), false);
assert.equal(!!$svg.attr('xmlns:xlink'), false);
assert.equal(!!$svg.attr('version'), false);
});
});
describe('additional props', () => {
let $;
Expand Down
75 changes: 75 additions & 0 deletions packages/astro/test/fixtures/core-image-svg/src/assets/dragon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
import Alpine from '~/assets/alpine-multi-color.svg'
import Dragon from '~/assets/dragon.svg'
---
<html>
<head>
Expand All @@ -9,5 +10,8 @@ import Alpine from '~/assets/alpine-multi-color.svg'
<div id="base">
<Alpine />
</div>
<div id="additionalNodes">
<Dragon />
</div>
</body>
</html>

0 comments on commit cb9322c

Please sign in to comment.