Skip to content

Commit

Permalink
fix(jsx): fix $attrs (#681)
Browse files Browse the repository at this point in the history
  • Loading branch information
krulod authored Oct 20, 2023
1 parent a3ad7d8 commit d21daa1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 24 deletions.
55 changes: 32 additions & 23 deletions packages/jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,39 +43,48 @@ export const reatomJsx = (ctx: Ctx) => {
})
}

let create = (tag: string, props: Rec) => {
let create = (tag: string, attrs: Rec) => {
let element =
tag === 'svg'
? document.createElementNS('http://www.w3.org/2000/svg', tag)
: document.createElement(tag)

for (let k in props) {
if (k === 'children') continue
bindAttr(element, k, props[k])
}
bindAttrs(element, attrs)

render(element, props.children ?? [])
render(element, attrs.children ?? [])

return element
}

const bindAttr = (element: any, key: any, val: any) => {
if (key === '$attrs') {
const recs = Array.isArray(val) ? val : [val]
for (const rec of recs) {
for (const k in rec) bindAttr(element, k, rec[k])
}
} else if (isAtom(val)) {
if (val.__reatom.isAction) {
element[key] = (...args: any) => (val as Action)(ctx, ...args)
} else {
// TODO handle unsubscribe!
var un: undefined | Unsubscribe = ctx.subscribe(val, (val) =>
!un || element.isConnected ? renderAttr(element, key, val) : un(),
)
unlink(element, un)
}
} else renderAttr(element, key, val)
const bindAttrs = (element: Element, attrs: Rec) => {
for (const key in attrs) {
if (key === 'children') continue
const val = attrs[key]

if (key === '$attrs') {
for (const attrs of Array.isArray(val) ? val : []) {
if (isAtom(attrs)) {
var u = ctx.subscribe(attrs, (attrs): void =>
!u || element.isConnected
? bindAttrs(element, attrs as Rec)
: u(),
)
unlink(element, u)
} else bindAttrs(element, attrs)
}
} else if (isAtom(val)) {
if (val.__reatom.isAction) {
;(element as any)[key] = (...args: any) =>
(val as Action)(ctx, ...args)
} else {
// TODO handle unsubscribe!
var un: undefined | Unsubscribe = ctx.subscribe(val, (val) =>
!un || element.isConnected ? renderAttr(element, key, val) : un(),
)
unlink(element, un)
}
} else renderAttr(element, key, val)
}
}

const renderAttr = (element: any, key: any, val: any) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/jsx/src/jsx.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export namespace JSX {
OnAttributes<T>,
OnCaptureAttributes<T>, */
extends CustomEventHandlers<T> {
$attrs?: Atom<this | this[]>
$attrs?: AtomMaybe<this | this[]>
children?: Element
innerHTML?: string
innerText?: string | number
Expand Down

1 comment on commit d21daa1

@vercel
Copy link

@vercel vercel bot commented on d21daa1 Oct 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.