feat(jsx/dom): support namespace for svg and mathml elements (#2241)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(jsx/dom): support namespace for svg and mathml elements * refactor(jsx/dom): eventAliasMap is readonly * chore: denoify
authored by Taku Amano · committed by GitHub · parent 0b59827 · Browse files · 3 files·+137 added−10 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+137 added−10 removed
- tests:+61 added−0 removed
- other:+76 added−10 removed
Provenance
- Commit
8c40d48- Tree
2ccabaf- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
0b59827
3 files changed+137 added−10 removed
modified:deno_dist/jsx/dom/render.ts+38 added-5 removed
3 unmodified lines4 import type { Context as JSXContext } from '../context.ts'5 import { globalContexts as globalJSXContexts } from '../context.ts'6 import type { EffectData } from '../hooks/index.ts'7 import { STASH_EFFECT } from '../hooks/index.ts'8+import { useContext, createContext } from './index.ts'9 10 const eventAliasMap: Record<string, string> = {11 Change: 'Input',12 DoubleClick: 'DblClick',12-}13+} as const14 15+const nameSpaceMap: Record<string, string> = {16+ svg: 'http://www.w3.org/2000/svg',17+ math: 'http://www.w3.org/1998/Math/MathML',18+} as const19+20 // eslint-disable-next-line @typescript-eslint/no-explicit-any21 export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }22 // eslint-disable-next-line @typescript-eslint/no-explicit-any23 export type ErrorHandler = (error: any, retry: () => void) => Child | undefined24 25 type Container = HTMLElement | DocumentFragment26 type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined27+type SupportedElement = HTMLElement | SVGElement | MathMLElement28 29 export type NodeObject = {30 pP: Props | undefined // previous props31 nN: Node | undefined // next node32 vC: Node[] // virtual dom children33 vR: Node[] // virtual dom children to remove34 s?: Node[] // shadow virtual dom children35+ n?: string // namespace36 c: Container | undefined // container29- e: HTMLElement | Text | undefined // rendered element37+ e: SupportedElement | Text | undefined // rendered element38 [DOM_STASH]:39 | [40 number, // current hook index41 // eslint-disable-next-line @typescript-eslint/no-explicit-any39 unmodified lines81 | []82 83 export const buildDataStack: [Context, Node][] = []84 85+let nameSpaceContext: JSXContext<string> | undefined = undefined86+87 const isNodeString = (node: Node): node is NodeString => Array.isArray(node)88 89 const getEventSpec = (key: string): [string, boolean] | undefined => {90 const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)3 unmodified lines94 }95 return undefined96 }97 88-const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {98+const applyProps = (container: SupportedElement, attributes: Props, oldAttributes?: Props) => {99 attributes ||= {}100 for (const [key, value] of Object.entries(attributes)) {101 if (!oldAttributes || oldAttributes[key] !== value) {102 const eventSpec = getEventSpec(key)178 unmodified lines281 282 for (let i = 0, len = next.length; i < len; i++, offset++) {283 const child = next[i]284 275- let el: HTMLElement | Text285+ let el: SupportedElement | Text286 if (isNodeString(child)) {287 if (child.e) {288 child.e.textContent = child[0]289 }290 el = child.e ||= document.createTextNode(child[0])291 } else {292+ el = child.e ||= child.n293+ ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)282- el = child.e ||= document.createElement(child.tag as string)294+ : document.createElement(child.tag as string)295 applyProps(el as HTMLElement, child.props, child.pP)296 applyNode(child, el as HTMLElement)297 }298 if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {63 unmodified lines362 oldChild.props = child.props363 oldChild.children = child.children364 child = oldChild365 }366+ } else if (!isNodeString(child) && nameSpaceContext) {367+ const ns = useContext(nameSpaceContext)368+ if (ns) {369+ child.n = ns370+ }371 }372 373 if (!isNodeString(child)) {374 build(context, child, topLevelErrorHandlerNode)29 unmodified lines404 return [node.toString()] as NodeString405 } else {406 if (typeof (node as JSXNode).tag === 'function') {407 ;(node as NodeObject)[DOM_STASH] = [0, []]408+ } else {409+ const ns = nameSpaceMap[(node as JSXNode).tag as string]410+ if (ns) {411+ ;(node as NodeObject).n = ns412+ nameSpaceContext ||= createContext('')413+ ;(node as JSXNode).children = [414+ {415+ tag: nameSpaceContext.Provider,416+ props: {417+ value: ns,418+ },419+ children: (node as JSXNode).children,420+ },421+ // eslint-disable-next-line @typescript-eslint/no-explicit-any422+ ] as any423+ }424 }425 return node as NodeObject426 }427 }69 unmodified linesmodified:src/jsx/dom/index.test.tsx+61 added
1062 unmodified lines1063 await Promise.resolve()1064 expect(root.innerHTML).toBe('<div><p>1</p></div>')1065 })1066 })1067+1068+ describe('SVG', () => {1069+ it('simple', () => {1070+ const createElementSpy = vi.spyOn(dom.window.document, 'createElement')1071+ const createElementNSSpy = vi.spyOn(dom.window.document, 'createElementNS')1072+1073+ const App = () => {1074+ return (1075+ <svg>1076+ <circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />1077+ </svg>1078+ )1079+ }1080+ render(<App />, root)1081+ expect(root.innerHTML).toBe(1082+ '<svg><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"></circle></svg>'1083+ )1084+ })1085+1086+ it('title element', () => {1087+ const App = () => {1088+ return (1089+ <>1090+ <title>Document Title</title>1091+ <svg>1092+ <title>SVG Title</title>1093+ </svg>1094+ </>1095+ )1096+ }1097+ render(<App />, root)1098+ expect(root.innerHTML).toBe(1099+ '<title>Document Title</title><svg><title>SVG Title</title></svg>'1100+ )1101+ expect(document.querySelector('title')).toBeInstanceOf(dom.window.HTMLTitleElement)1102+ expect(document.querySelector('svg title')).toBeInstanceOf(dom.window.SVGTitleElement)1103+ })1104+ })1105+1106+ describe('MathML', () => {1107+ it('simple', () => {1108+ const createElementSpy = vi.spyOn(dom.window.document, 'createElement')1109+ const createElementNSSpy = vi.spyOn(dom.window.document, 'createElementNS')1110+1111+ const App = () => {1112+ return (1113+ <math>1114+ <mrow>1115+ <mn>1</mn>1116+ </mrow>1117+ </math>1118+ )1119+ }1120+ render(<App />, root)1121+ expect(root.innerHTML).toBe('<math><mrow><mn>1</mn></mrow></math>')1122+1123+ expect(createElementSpy).not.toHaveBeenCalled()1124+ expect(createElementNSSpy).toHaveBeenCalledWith('http://www.w3.org/1998/Math/MathML', 'math')1125+ expect(createElementNSSpy).toHaveBeenCalledWith('http://www.w3.org/1998/Math/MathML', 'mrow')1126+ })1127+ })1128 })modified:src/jsx/dom/render.ts+38 added-5 removed
3 unmodified lines4 import type { Context as JSXContext } from '../context'5 import { globalContexts as globalJSXContexts } from '../context'6 import type { EffectData } from '../hooks'7 import { STASH_EFFECT } from '../hooks'8+import { useContext, createContext } from '.'9 10 const eventAliasMap: Record<string, string> = {11 Change: 'Input',12 DoubleClick: 'DblClick',12-}13+} as const14 15+const nameSpaceMap: Record<string, string> = {16+ svg: 'http://www.w3.org/2000/svg',17+ math: 'http://www.w3.org/1998/Math/MathML',18+} as const19+20 // eslint-disable-next-line @typescript-eslint/no-explicit-any21 export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }22 // eslint-disable-next-line @typescript-eslint/no-explicit-any23 export type ErrorHandler = (error: any, retry: () => void) => Child | undefined24 25 type Container = HTMLElement | DocumentFragment26 type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined27+type SupportedElement = HTMLElement | SVGElement | MathMLElement28 29 export type NodeObject = {30 pP: Props | undefined // previous props31 nN: Node | undefined // next node32 vC: Node[] // virtual dom children33 vR: Node[] // virtual dom children to remove34 s?: Node[] // shadow virtual dom children35+ n?: string // namespace36 c: Container | undefined // container29- e: HTMLElement | Text | undefined // rendered element37+ e: SupportedElement | Text | undefined // rendered element38 [DOM_STASH]:39 | [40 number, // current hook index41 // eslint-disable-next-line @typescript-eslint/no-explicit-any39 unmodified lines81 | []82 83 export const buildDataStack: [Context, Node][] = []84 85+let nameSpaceContext: JSXContext<string> | undefined = undefined86+87 const isNodeString = (node: Node): node is NodeString => Array.isArray(node)88 89 const getEventSpec = (key: string): [string, boolean] | undefined => {90 const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)3 unmodified lines94 }95 return undefined96 }97 88-const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {98+const applyProps = (container: SupportedElement, attributes: Props, oldAttributes?: Props) => {99 attributes ||= {}100 for (const [key, value] of Object.entries(attributes)) {101 if (!oldAttributes || oldAttributes[key] !== value) {102 const eventSpec = getEventSpec(key)178 unmodified lines281 282 for (let i = 0, len = next.length; i < len; i++, offset++) {283 const child = next[i]284 275- let el: HTMLElement | Text285+ let el: SupportedElement | Text286 if (isNodeString(child)) {287 if (child.e) {288 child.e.textContent = child[0]289 }290 el = child.e ||= document.createTextNode(child[0])291 } else {292+ el = child.e ||= child.n293+ ? (document.createElementNS(child.n, child.tag as string) as SVGElement | MathMLElement)282- el = child.e ||= document.createElement(child.tag as string)294+ : document.createElement(child.tag as string)295 applyProps(el as HTMLElement, child.props, child.pP)296 applyNode(child, el as HTMLElement)297 }298 if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {63 unmodified lines362 oldChild.props = child.props363 oldChild.children = child.children364 child = oldChild365 }366+ } else if (!isNodeString(child) && nameSpaceContext) {367+ const ns = useContext(nameSpaceContext)368+ if (ns) {369+ child.n = ns370+ }371 }372 373 if (!isNodeString(child)) {374 build(context, child, topLevelErrorHandlerNode)29 unmodified lines404 return [node.toString()] as NodeString405 } else {406 if (typeof (node as JSXNode).tag === 'function') {407 ;(node as NodeObject)[DOM_STASH] = [0, []]408+ } else {409+ const ns = nameSpaceMap[(node as JSXNode).tag as string]410+ if (ns) {411+ ;(node as NodeObject).n = ns412+ nameSpaceContext ||= createContext('')413+ ;(node as JSXNode).children = [414+ {415+ tag: nameSpaceContext.Provider,416+ props: {417+ value: ns,418+ },419+ children: (node as JSXNode).children,420+ },421+ // eslint-disable-next-line @typescript-eslint/no-explicit-any422+ ] as any423+ }424 }425 return node as NodeObject426 }427 }69 unmodified lines