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
Provenance
- Commit
3a56ec5- Tree
b483815- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
cdd48f4
3 files changed+214 added−3 removed
modified:src/jsx/intrinsic-element/components.ts+7 added-1 removed
1223456796 unmodified lines10410510610710810911011111211311411511665 unmodified linesimport type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'import { JSXNode } from '../base'import { JSXNode, getNameSpaceContext } from '../base'import { useContext } from '../context'import type { Child, Props } from '../base'import type { FC, PropsWithChildren } from '../types'import { raw } from '../../helper/html'import { dataPrecedenceAttr, deDupeKeyMap } from './common'96 unmodified lines }}
export const title: FC<PropsWithChildren> = ({ children, ...props }) => { const nameSpaceContext = getNameSpaceContext() if (nameSpaceContext && useContext(nameSpaceContext) === 'svg') { new JSXNode('title', props, toArray(children ?? []) as Child[]) }
return documentMetadataTag('title', children, props, false)}export const script: FC<PropsWithChildren<IntrinsicElements['script']>> = ({ children,65 unmodified linesmodified:src/jsx/base.ts+30 added-2 removed
1 import { raw } from '../helper/html'2 import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from '../utils/html'3 import type { HtmlEscaped, HtmlEscapedString, StringBufferWithCallbacks } from '../utils/html'4 import type { Context } from './context'5-import { globalContexts } from './context'5+import { createContext, globalContexts, useContext } from './context'6 import { DOM_RENDERER } from './constants'7 import type {8 JSX as HonoJSX,9 IntrinsicElements as IntrinsicElementsDefined,21 unmodified lines31 [tagName: string]: Props32 }33 }34 35+let nameSpaceContext: Context<string> | undefined = undefined36+export const getNameSpaceContext = () => nameSpaceContext37+38+const 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+ : key47+48 const emptyTags = [49 'area',50 'base',51 'br',120 unmodified lines172 let { children } = this173 174 buffer[0] += `<${tag}`175 176+ 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 strings137 unmodified lines323 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 linesmodified:src/jsx/index.test.tsx+177 added
564 unmodified lines565 expect(template.toString()).toBe('<p>1</p><p>2</p>')566 })567 })568 569+describe('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+ })580+581+ 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+ })596+597+ 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+ })662+663+ 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+ })727+728+ 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+})745+746 describe('Context', () => {747 let ThemeContext: Context<string>748 let Consumer: FC749 let ErrorConsumer: FC251 unmodified lines