Skip to content
Myr

fix(jsx): fix handling of SVG elements in JSX. (#3204)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(jsx): preserve "title" element position in SVG * fix(jsx): convert SVG attribute name from camelCase to kebab-case

authored by Taku Amano · committed by GitHub · parent cdd48f4 · Browse files · 3 files+214 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+214 added−3 removed

  • tests:+177 added−0 removed
  • other:+37 added−3 removed

3 files+214 added−3 removed

modified:src/jsx/intrinsic-element/components.ts+7 added-1 removed
modified:src/jsx/base.ts+30 added-2 removed
1import { raw } from '../helper/html'2import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'3import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'4import type { Context } from './context'5import { globalContexts } from './context'5import { createContext, globalContexts, useContext } from './context'6import { DOM_RENDERER } from './constants'7import type {8 JSX as HonoJSX,9 IntrinsicElements as IntrinsicElementsDefined,
21 unmodified lines
31 [tagName: string]: Props32 }33}3435let nameSpaceContext: Context<string> | undefined = undefined36export const getNameSpaceContext = () => nameSpaceContext3738const toSVGAttributeName = (key: string): string =>39 /[A-Z]/.test(key) &&40 // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.41 // Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc.42 key.match(43 /^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/44 )45 ? key.replace(/([A-Z])/g, '-$1').toLowerCase()46 : key4748const emptyTags = [49 'area',50 'base',51 'br',
120 unmodified lines
172 let { children } = this173174 buffer[0] += `<${tag}`175176 const normalizeKey: (key: string) => string =177 nameSpaceContext && useContext(nameSpaceContext) === 'svg'178 ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key))179 : (key) => normalizeIntrinsicElementKey(key)180 for (let [key, v] of Object.entries(props)) {164 key = normalizeIntrinsicElementKey(key)181 key = normalizeKey(key)182 if (key === 'children') {183 // skip children184 } else if (key === 'style' && typeof v === 'object') {185 // object to style strings
137 unmodified lines
323 intrinsicElementTags[tag as keyof typeof intrinsicElementTags],324 props,325 children326 )327 } else if (tag === 'svg') {328 nameSpaceContext ||= createContext('')329 return new JSXNode(tag, props, [330 new JSXFunctionNode(331 nameSpaceContext,332 {333 value: tag,334 },335 children336 ),337 ])338 } else {339 return new JSXNode(tag, props, children)340 }341}
75 unmodified lines
modified:src/jsx/index.test.tsx+177 added
564 unmodified lines
565 expect(template.toString()).toBe('<p>1</p><p>2</p>')566 })567})568569describe('SVG', () => {570 it('simple', () => {571 const template = (572 <svg>573 <circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />574 </svg>575 )576 expect(template.toString()).toBe(577 '<svg><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></circle></svg>'578 )579 })580581 it('title element', () => {582 const template = (583 <>584 <head>585 <title>Document Title</title>586 </head>587 <svg>588 <title>SVG Title</title>589 </svg>590 </>591 )592 expect(template.toString()).toBe(593 '<head><title>Document Title</title></head><svg><title>SVG Title</title></svg>'594 )595 })596597 describe('attribute', () => {598 describe('camelCase', () => {599 test.each`600 key601 ${'attributeName'}602 ${'baseFrequency'}603 ${'calcMode'}604 ${'clipPathUnits'}605 ${'diffuseConstant'}606 ${'edgeMode'}607 ${'filterUnits'}608 ${'gradientTransform'}609 ${'gradientUnits'}610 ${'kernelMatrix'}611 ${'kernelUnitLength'}612 ${'keyPoints'}613 ${'keySplines'}614 ${'keyTimes'}615 ${'lengthAdjust'}616 ${'limitingConeAngle'}617 ${'markerHeight'}618 ${'markerUnits'}619 ${'markerWidth'}620 ${'maskContentUnits'}621 ${'maskUnits'}622 ${'numOctaves'}623 ${'pathLength'}624 ${'patternContentUnits'}625 ${'patternTransform'}626 ${'patternUnits'}627 ${'pointsAtX'}628 ${'pointsAtY'}629 ${'pointsAtZ'}630 ${'preserveAlpha'}631 ${'preserveAspectRatio'}632 ${'primitiveUnits'}633 ${'refX'}634 ${'refY'}635 ${'repeatCount'}636 ${'repeatDur'}637 ${'specularConstant'}638 ${'specularExponent'}639 ${'spreadMethod'}640 ${'startOffset'}641 ${'stdDeviation'}642 ${'stitchTiles'}643 ${'surfaceScale'}644 ${'crossorigin'}645 ${'systemLanguage'}646 ${'tableValues'}647 ${'targetX'}648 ${'targetY'}649 ${'textLength'}650 ${'viewBox'}651 ${'xChannelSelector'}652 ${'yChannelSelector'}653 `('$key', ({ key }) => {654 const template = (655 <svg>656 <g {...{ [key]: 'test' }} />657 </svg>658 )659 expect(template.toString()).toBe(`<svg><g ${key}="test"></g></svg>`)660 })661 })662663 describe('kebab-case', () => {664 test.each`665 key666 ${'alignmentBaseline'}667 ${'baselineShift'}668 ${'clipPath'}669 ${'clipRule'}670 ${'colorInterpolation'}671 ${'colorInterpolationFilters'}672 ${'dominantBaseline'}673 ${'fillOpacity'}674 ${'fillRule'}675 ${'floodColor'}676 ${'floodOpacity'}677 ${'fontFamily'}678 ${'fontSize'}679 ${'fontSizeAdjust'}680 ${'fontStretch'}681 ${'fontStyle'}682 ${'fontVariant'}683 ${'fontWeight'}684 ${'imageRendering'}685 ${'letterSpacing'}686 ${'lightingColor'}687 ${'markerEnd'}688 ${'markerMid'}689 ${'markerStart'}690 ${'overlinePosition'}691 ${'overlineThickness'}692 ${'paintOrder'}693 ${'pointerEvents'}694 ${'shapeRendering'}695 ${'stopColor'}696 ${'stopOpacity'}697 ${'strikethroughPosition'}698 ${'strikethroughThickness'}699 ${'strokeDasharray'}700 ${'strokeDashoffset'}701 ${'strokeLinecap'}702 ${'strokeLinejoin'}703 ${'strokeMiterlimit'}704 ${'strokeOpacity'}705 ${'strokeWidth'}706 ${'textAnchor'}707 ${'textDecoration'}708 ${'textRendering'}709 ${'transformOrigin'}710 ${'underlinePosition'}711 ${'underlineThickness'}712 ${'unicodeBidi'}713 ${'vectorEffect'}714 ${'wordSpacing'}715 ${'writingMode'}716 `('$key', ({ key }) => {717 const template = (718 <svg>719 <g {...{ [key]: 'test' }} />720 </svg>721 )722 expect(template.toString()).toBe(723 `<svg><g ${key.replace(/([A-Z])/g, '-$1').toLowerCase()}="test"></g></svg>`724 )725 })726 })727728 describe('data-*', () => {729 test.each`730 key731 ${'data-foo'}732 ${'data-foo-bar'}733 ${'data-fooBar'}734 `('$key', ({ key }) => {735 const template = (736 <svg>737 <g {...{ [key]: 'test' }} />738 </svg>739 )740 expect(template.toString()).toBe(`<svg><g ${key}="test"></g></svg>`)741 })742 })743 })744})745746describe('Context', () => {747 let ThemeContext: Context<string>748 let Consumer: FC749 let ErrorConsumer: FC
251 unmodified lines