From 0561c607d8dbb4e927897066ceccd45269a45cbd Mon Sep 17 00:00:00 2001 From: Joris Date: Sun, 13 Apr 2025 20:13:55 +0200 Subject: Export s function for svg nodes --- src/rx.ts | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/rx.ts b/src/rx.ts index 82e3535..14c3776 100644 --- a/src/rx.ts +++ b/src/rx.ts @@ -22,6 +22,7 @@ export type Html interface Tag { type: 'Tag' tagName: string + isSvg: boolean attributes: Attributes children?: Array onmount?: (element: Element) => void @@ -100,21 +101,40 @@ function isHtml(x: any): x is Html { type ValueOrArray = T | Array> +export function s( + tagName: string, + x?: Attributes | Html, + ...children: Array +): Tag { + return node(true, tagName, x, ...children) +} + export function h( tagName: string, x?: Attributes | Html, ...children: Array +): Tag { + return node(false, tagName, x, ...children) +} + +export function node( + isSvg: boolean, + tagName: string, + x?: Attributes | Html, + ...children: Array ): Tag { if (x === undefined || x == null || x === false) { return { type: 'Tag', tagName, + isSvg, attributes: {} } } else if (isHtml(x)) { return { type: 'Tag', tagName, + isSvg, attributes: {}, children: [x, ...children], } @@ -132,6 +152,7 @@ export function h( return { type: 'Tag', tagName, + isSvg, attributes, children, onmount, @@ -488,16 +509,13 @@ function appendChild(state: State, element: Element, child: Html, lastAdded?: No } else if (typeof child == 'number') { return appendChild(state, element, child.toString(), lastAdded) } else if (isTag(child)) { - const { tagName, attributes, children, onmount, onunmount } = child + const { tagName, isSvg, attributes, children, onmount, onunmount } = child - // TODO: export svg variant of h function - const s = isSvg(tagName) - - const childElement = s + const childElement = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', tagName) : document.createElement(tagName) - const setAttr = s + const setAttr = isSvg ? (key: any, value: any) => childElement.setAttribute(key, value) // @ts-ignore : (key: any, value: any) => childElement[key] = value @@ -704,11 +722,6 @@ function appendChild(state: State, element: Element, child: Html, lastAdded?: No } } -const svgElements = ['svg', 'circle', 'polygon', 'line', 'rect', 'ellipse', 'text', 'path'] -function isSvg(tagName: string): boolean { - return !(svgElements.indexOf(tagName) === -1) -} - function isTag(x: any): x is Tag { return x != null && x.type === 'Tag' } -- cgit v1.2.3