Skip to content
Myr

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

3 files+137 added−10 removed

modified:deno_dist/jsx/dom/render.ts+38 added-5 removed
3 unmodified lines
4import type { Context as JSXContext } from '../context.ts'5import { globalContexts as globalJSXContexts } from '../context.ts'6import type { EffectData } from '../hooks/index.ts'7import { STASH_EFFECT } from '../hooks/index.ts'8import { useContext, createContext } from './index.ts'910const eventAliasMap: Record<string, string> = {11 Change: 'Input',12 DoubleClick: 'DblClick',12}13} as const1415const nameSpaceMap: Record<string, string> = {16 svg: 'http://www.w3.org/2000/svg',17 math: 'http://www.w3.org/1998/Math/MathML',18} as const1920// eslint-disable-next-line @typescript-eslint/no-explicit-any21export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }22// eslint-disable-next-line @typescript-eslint/no-explicit-any23export type ErrorHandler = (error: any, retry: () => void) => Child | undefined2425type Container = HTMLElement | DocumentFragment26type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined27type SupportedElement = HTMLElement | SVGElement | MathMLElement2829export 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-any
39 unmodified lines
81 | []8283export const buildDataStack: [Context, Node][] = []8485let nameSpaceContext: JSXContext<string> | undefined = undefined8687const isNodeString = (node: Node): node is NodeString => Array.isArray(node)8889const getEventSpec = (key: string): [string, boolean] | undefined => {90 const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)
3 unmodified lines
94 }95 return undefined96}9788const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {98const 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 lines
281282 for (let i = 0, len = next.length; i < len; i++, offset++) {283 const child = next[i]284275 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 lines
362 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 }372373 if (!isNodeString(child)) {374 build(context, child, topLevelErrorHandlerNode)
29 unmodified lines
404 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
modified:src/jsx/dom/index.test.tsx+61 added
1062 unmodified lines
1063 await Promise.resolve()1064 expect(root.innerHTML).toBe('<div><p>1</p></div>')1065 })1066 })10671068 describe('SVG', () => {1069 it('simple', () => {1070 const createElementSpy = vi.spyOn(dom.window.document, 'createElement')1071 const createElementNSSpy = vi.spyOn(dom.window.document, 'createElementNS')10721073 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 })10851086 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 })11051106 describe('MathML', () => {1107 it('simple', () => {1108 const createElementSpy = vi.spyOn(dom.window.document, 'createElement')1109 const createElementNSSpy = vi.spyOn(dom.window.document, 'createElementNS')11101111 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>')11221123 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 lines
4import type { Context as JSXContext } from '../context'5import { globalContexts as globalJSXContexts } from '../context'6import type { EffectData } from '../hooks'7import { STASH_EFFECT } from '../hooks'8import { useContext, createContext } from '.'910const eventAliasMap: Record<string, string> = {11 Change: 'Input',12 DoubleClick: 'DblClick',12}13} as const1415const nameSpaceMap: Record<string, string> = {16 svg: 'http://www.w3.org/2000/svg',17 math: 'http://www.w3.org/1998/Math/MathML',18} as const1920// eslint-disable-next-line @typescript-eslint/no-explicit-any21export type HasRenderToDom = FC<any> & { [DOM_RENDERER]: FC<any> }22// eslint-disable-next-line @typescript-eslint/no-explicit-any23export type ErrorHandler = (error: any, retry: () => void) => Child | undefined2425type Container = HTMLElement | DocumentFragment26type LocalJSXContexts = [JSXContext<unknown>, unknown][] | undefined27type SupportedElement = HTMLElement | SVGElement | MathMLElement2829export 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-any
39 unmodified lines
81 | []8283export const buildDataStack: [Context, Node][] = []8485let nameSpaceContext: JSXContext<string> | undefined = undefined8687const isNodeString = (node: Node): node is NodeString => Array.isArray(node)8889const getEventSpec = (key: string): [string, boolean] | undefined => {90 const match = key.match(/^on([A-Z][a-zA-Z]+?)((?<!Pointer)Capture)?$/)
3 unmodified lines
94 }95 return undefined96}9788const applyProps = (container: HTMLElement, attributes: Props, oldAttributes?: Props) => {98const 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 lines
281282 for (let i = 0, len = next.length; i < len; i++, offset++) {283 const child = next[i]284275 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 lines
362 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 }372373 if (!isNodeString(child)) {374 build(context, child, topLevelErrorHandlerNode)
29 unmodified lines
404 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