Skip to content

Commit

Permalink
lib - hooks can now provide a 'debug' fn to provider better info to d…
Browse files Browse the repository at this point in the history
…evtools
  • Loading branch information
LankyMoose committed Apr 13, 2024
1 parent 875c195 commit 370e47d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 27 deletions.
48 changes: 24 additions & 24 deletions packages/lib/src/hooks/useContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,41 @@ export function useContext<T>(context: Kaioken.Context<T>): T {
ctxNode: undefined as ContextNode<T> | undefined,
},
({ hook, oldHook, vNode }) => {
if (oldHook) {
if (!oldHook.ctxNode) {
warnProviderNotFound()
return context.default() as T
}
return oldHook.ctxNode.props[contextDataSymbol].value
}
if (!oldHook) {
hook.debug = () => ({
value: hook.ctxNode
? hook.ctxNode.props[contextDataSymbol].value
: context.default(),
})

let n = vNode.parent
while (n) {
if (contextDataSymbol in n.props) {
const ctxNodeData = n.props[
contextDataSymbol
] as ContextNode<T>["props"]
if (ctxNodeData.ctx === context) {
hook.ctxNode = n as ContextNode<T>
return (n.props[contextDataSymbol] as ContextNode<T>["props"]).value
let n = vNode.parent
while (n) {
if (contextDataSymbol in n.props) {
const ctxNodeData = n.props[
contextDataSymbol
] as ContextNode<T>["props"]
if (ctxNodeData.ctx === context) {
hook.ctxNode = n as ContextNode<T>
return (n.props[contextDataSymbol] as ContextNode<T>["props"])
.value
}
}
n = n.parent
}
n = n.parent
}

warnProviderNotFound()
return context.default() as T
if (!hook.ctxNode) {
warnProviderNotFound()
return context.default() as T
}
return hook.ctxNode.props[contextDataSymbol].value
}
)
}

let hasWarned = false
function warnProviderNotFound() {
if (!hasWarned) {
console.warn(
`[kaioken]: Unable to find context in parent nodes. Did you forget to use the context provider?`,
new Error()
)
console.warn(`[kaioken]: Unable to find context provider`, new Error())
hasWarned = true
}
}
10 changes: 7 additions & 3 deletions packages/lib/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ declare global {
type FC<T = {}> = (props: FCProps<T>) => JSX.Element
type FCProps<T = {}> = T & { children?: JSX.Element[] }

type Hook<T> = T & { cleanup?: () => void; name?: string }
type Hook<T> = T & {
cleanup?: () => void
debug?: () => Record<string, any>
name?: string
}

type InternalProps = { ref?: Kaioken.Ref<Element>; key?: JSX.ElementKey }

Expand All @@ -65,8 +69,8 @@ declare global {

type Signal<T> = {
value: T
subscribe: (fn: (value: T) => void) => () => void,
notify: () => void;
subscribe: (fn: (value: T) => void) => () => void
notify: () => void
}

type VNode = {
Expand Down

0 comments on commit 370e47d

Please sign in to comment.