Skip to content

Commit

Permalink
fix: various jsx runtime bugs
Browse files Browse the repository at this point in the history
- Fix `Fragment` not accepting non-array children and not sanitizing children
- Increase jsx robustness against falsy values
- Fix the value 0 not being rendered
  • Loading branch information
Desdaemon committed Jul 22, 2023
1 parent 283eab3 commit 887d7af
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 0.1.2

- Fix `Fragment` not accepting non-array children and not sanitizing children
- Increase jsx robustness against falsy values
- Fix the value 0 not being rendered

## 0.1.1

- Allow `jsx` to process arrays of children, unblocks Bun
Expand Down
16 changes: 9 additions & 7 deletions src/typed-html/jsx-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import { createElement } from "typed-html";

export function Fragment({ children }: { children: any[] }) {
return children.join("");
export function Fragment({ children }: { children?: unknown | unknown[] }): JSX.Element {
if (Array.isArray(children)) return children.map(sanitizer).join('\n');
return sanitizer(children)
}

/**
Expand All @@ -21,9 +22,10 @@ export const config = {
sanitize: false as Sanitizer,
};

function sanitizer(value: {}) {
if (!config.sanitize) return value.toString();
return config.sanitize(value.toString(), typeof value);
function sanitizer(value: unknown): string {
const str = value || value === 0 ? value.toString() : '';
if (!config.sanitize) return str;
return config.sanitize(str, typeof value);
}

type Sanitizer = false | ((raw: string, originalType: string) => string);
Expand All @@ -38,13 +40,13 @@ function expandLiterals(props: Record<string, unknown>) {
}
}

export function jsx(tag: any, { children, ...props }: { children: JSX.Element | JSX.Element[] }): JSX.Element {
export function jsx(tag: any, { children, ...props }: { children?: unknown | unknown[] }): JSX.Element {
expandLiterals(props);
const contents = Array.isArray(children) ? children.map(sanitizer) : [sanitizer(children)];
return createElement(tag, props, ...contents);
}

export function jsxs(tag: any, { children, ...props }: { children: JSX.Element[] }): JSX.Element {
export function jsxs(tag: any, { children, ...props }: { children: unknown[] }): JSX.Element {
expandLiterals(props);
return createElement(tag, props, ...children.map(sanitizer));
}

0 comments on commit 887d7af

Please sign in to comment.