Skip to content

Commit

Permalink
Reduce some bytes from the createCallable return structure
Browse files Browse the repository at this point in the history
  • Loading branch information
desko27 committed Aug 19, 2024
1 parent b576ccf commit 94d1a54
Showing 1 changed file with 36 additions and 38 deletions.
74 changes: 36 additions & 38 deletions lib/createCallable/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useState, useEffect } from 'react'
import type {
CallFunction,
UserComponent as UserComponentType,
PrivateStackState,
PrivateStackStateSetter,
Expand All @@ -13,45 +12,44 @@ export function createCallable<Props = void, Response = void, RootProps = {}>(
let $setStack: PrivateStackStateSetter<Props, Response> | null = null
let $nextKey = 0

const call: CallFunction<Props, Response> = (props) => {
if ($setStack === null) throw new Error('No <Root> found!')
return {
call: (props) => {
if ($setStack === null) throw new Error('No <Root> found!')

const key = String($nextKey++)
const promise = Promise.withResolvers<Response>()
const key = String($nextKey++)
const promise = Promise.withResolvers<Response>()

const end = (response: Response) => {
if ($setStack === null) return
promise.resolve(response)
$setStack((prev) => prev.filter((c) => c.key !== key))
}

const nextCall = { key, props, end }
$setStack((prev) => [...prev, nextCall])

return promise.promise
}

function Root(rootProps: RootProps) {
const [stack, setStack] = useState<PrivateStackState<Props, Response>>([])

useEffect(() => {
if ($setStack !== null)
throw new Error('Multiple instances of <Root> found!')
$setStack = setStack
return () => {
$setStack = null
$nextKey = 0
const end = (response: Response) => {
if ($setStack === null) return
promise.resolve(response)
$setStack((prev) => prev.filter((c) => c.key !== key))
}
}, [])

return stack.map(({ props, ...call }) => (
<UserComponent
{...props}
key={call.key}
call={{ ...call, root: rootProps }}
/>
))
}

return { Root, call }
const nextCall = { key, props, end }
$setStack((prev) => [...prev, nextCall])

return promise.promise
},
Root: (rootProps: RootProps) => {
const [stack, setStack] = useState<PrivateStackState<Props, Response>>([])

useEffect(() => {
if ($setStack !== null)
throw new Error('Multiple instances of <Root> found!')
$setStack = setStack
return () => {
$setStack = null
$nextKey = 0
}
}, [])

return stack.map(({ props, ...call }) => (
<UserComponent
{...props}
key={call.key}
call={{ ...call, root: rootProps }}
/>
))
},
}
}

0 comments on commit 94d1a54

Please sign in to comment.