Skip to content

Commit

Permalink
feat(jsx): handle falsy like React
Browse files Browse the repository at this point in the history
  • Loading branch information
kasperskei committed Jun 6, 2024
1 parent fc58024 commit 6ac9e60
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
31 changes: 31 additions & 0 deletions packages/jsx/src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,4 +262,35 @@ test('linked list', () => {
// assert.not.ok(isConnected(ctx, jsxList))
})

test('boolean, null, null and empty string children', () => {
const { h, hf } = setup()

const emptyAtom = atom('', 'empty')
const emptyValue = ''
const trueAtom = atom(true, 'true')
const trueValue = true
const falseAtom = atom(false, 'false')
const falseValue = false
const nullAtom = atom(null, 'null')
const nullValue = null
const undefinedAtom = atom(undefined, 'undefined')
const undefinedValue = undefined

const element = <div>
{emptyAtom}
{emptyValue}
{trueAtom}
{trueValue}
{falseAtom}
{falseValue}
{nullAtom}
{nullValue}
{undefinedAtom}
{undefinedValue}
</div>

assert.is(element.childNodes.length, 5)
assert.is(element.textContent, '')
})

test.run()
6 changes: 4 additions & 2 deletions packages/jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ type DomApis = Pick<
| 'DocumentFragment'
>

const isFalsy = (value: unknown): value is JSX.Falsy => typeof value === 'boolean' || value === '' || value == null

let unsubscribesMap = new WeakMap<HTMLElement, Array<Fn>>()
let unlink = (parent: any, un: Unsubscribe) => {
// check the connection in the next tick
Expand Down Expand Up @@ -241,7 +243,7 @@ export const reatomJsx = (ctx: Ctx, DOM: DomApis = globalThis.window) => {
}
} else {
// TODO more tests
innerChild.textContent = String(v)
innerChild.textContent = isFalsy(v) ? '' : String(v)
}
}
} catch (e) {
Expand All @@ -251,7 +253,7 @@ export const reatomJsx = (ctx: Ctx, DOM: DomApis = globalThis.window) => {
if (error) throw error
unlink(element, un)
element.appendChild(innerChild)
} else {
} else if (!isFalsy(child)) {
element.appendChild(
isObject(child) && 'nodeType' in child
? (child as JSX.Element)
Expand Down
4 changes: 3 additions & 1 deletion packages/jsx/src/jsx.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
Respectfully copied from https://github.com/ryansolid/dom-expressions/blob/ae71a417aa13b33517082628aff09513629df8b2/packages/dom-expressions/src/jsx.d.ts
*/

Expand All @@ -17,6 +17,8 @@ type ElementsAttributesAtomMaybe<T extends Record<keyof any, any>> = {
}

export namespace JSX {
type Falsy = boolean | '' | null | undefined

type Element = HTMLElement | SVGElement

type ElementPrimitiveChildren =
Expand Down

0 comments on commit 6ac9e60

Please sign in to comment.