Skip to content

Commit 9fc9675

Browse files
committed
fix(ui-svg-images): fix inlinesvg parser
1 parent 620d16a commit 9fc9675

2 files changed

Lines changed: 24 additions & 6 deletions

File tree

packages/ui-svg-images/src/InlineSVG/__tests__/InlineSVG.test.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,22 @@ describe('<InlineSVG />', () => {
128128

129129
expect(svg).toHaveAttribute('focusable', 'true')
130130
})
131+
132+
it('should correctly parse hyphenated attributes like stroke-width', () => {
133+
const svgWithHyphenatedAttrs = `<svg stroke-width="2" stroke-linecap="round"><path d="M12 2l3 6"/></svg>`
134+
const { container } = render(<InlineSVG src={svgWithHyphenatedAttrs} />)
135+
const svg = container.querySelector('svg')
136+
137+
expect(svg).toHaveAttribute('stroke-width', '2')
138+
expect(svg).toHaveAttribute('stroke-linecap', 'round')
139+
})
140+
141+
it('should correctly parse unquoted attribute values (non-standard format)', () => {
142+
const svgWithUnquotedAttrs = `<svg stroke=currentColor stroke-width=2><circle cx=12 cy=12 r=10/></svg>`
143+
const { container } = render(<InlineSVG src={svgWithUnquotedAttrs} />)
144+
const svg = container.querySelector('svg')
145+
146+
expect(svg).toHaveAttribute('stroke', 'currentColor')
147+
expect(svg).toHaveAttribute('stroke-width', '2')
148+
})
131149
})

packages/ui-svg-images/src/InlineSVG/index.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,10 @@ class InlineSVG extends Component<InlineSVGProps> {
199199
function parseAttributes(src: InlineSVGProps['src']) {
200200
const attributes: Record<string, string> = {}
201201
const SVGAttributesRegExp = /<svg\s+([^>]*)\s*>/
202-
const namesAndValuesRegExp =
203-
/(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g
202+
// Match either quoted or unquoted attribute values
203+
// Handles both standard format: attr="value" and non-standard: attr=value
204+
// (\S+?) = attribute name, (?:["']([^"']*)["']|(\S+)) = quoted (group 2) OR unquoted (group 3) value
205+
const namesAndValuesRegExp = /(\S+?)=(?:["']([^"']*)["']|(\S+))/g
204206

205207
if (typeof src === 'string') {
206208
const attributesMatches = SVGAttributesRegExp.exec(src)
@@ -211,10 +213,8 @@ function parseAttributes(src: InlineSVGProps['src']) {
211213

212214
while (match != null) {
213215
if (excludes.indexOf(match[1]) === -1) {
214-
attributes[match[1]] =
215-
match[2] ||
216-
(match[3] ? match[3] : match[4] ? match[4] : match[5]) ||
217-
match[1]
216+
// match[1] = attribute name, match[2] = quoted value, match[3] = unquoted value
217+
attributes[match[1]] = match[2] || match[3]
218218
}
219219
match = namesAndValuesRegExp.exec(attributesString)
220220
}

0 commit comments

Comments
 (0)