{"version":3,"sources":["../../../src/utils/createContextAndHook.ts"],"sourcesContent":["import React from 'react';\n\nexport function assertContextExists(contextVal: unknown, msgOrCtx: string | React.Context<any>): asserts contextVal {\n  if (!contextVal) {\n    throw typeof msgOrCtx === 'string' ? new Error(msgOrCtx) : new Error(`${msgOrCtx.displayName} not found`);\n  }\n}\n\ntype Options = { assertCtxFn?: (v: unknown, msg: string) => void };\ntype ContextOf<T> = React.Context<{ value: T } | undefined>;\ntype UseCtxFn<T> = () => T;\n\n/**\n * Creates and returns a Context and two hooks that return the context value.\n * The Context type is derived from the type passed in by the user.\n * The first hook returned guarantees that the context exists so the returned value is always CtxValue\n * The second hook makes no guarantees, so the returned value can be CtxValue | undefined\n */\nexport const createContextAndHook = <CtxVal>(\n  displayName: string,\n  options?: Options\n): [ContextOf<CtxVal>, UseCtxFn<CtxVal>, UseCtxFn<CtxVal | Partial<CtxVal>>] => {\n  const { assertCtxFn = assertContextExists } = options || {};\n  const Ctx = React.createContext<{ value: CtxVal } | undefined>(undefined);\n  Ctx.displayName = displayName;\n\n  const useCtx = () => {\n    const ctx = React.useContext(Ctx);\n    assertCtxFn(ctx, `Component must be wrapped with ${Ctx.displayName}`);\n\n    return (ctx as any).value as CtxVal;\n  };\n\n  const useCtxWithoutGuarantee = () => {\n    const ctx = React.useContext(Ctx);\n\n    return ctx ? ctx.value : {};\n  };\n\n  return [Ctx, useCtx, useCtxWithoutGuarantee];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAEX,SAAS,oBAAoB,YAAqB,UAA2D;AAClH,MAAI,CAAC,YAAY;AACf,UAAM,OAAO,aAAa,WAAW,IAAI,MAAM,QAAQ,IAAI,IAAI,MAAM,GAAG,SAAS,WAAW,YAAY;AAAA,EAC1G;AACF;AAYO,IAAM,uBAAuB,CAClC,aACA,YAC8E;AAC9E,QAAM,EAAE,cAAc,oBAAoB,IAAI,WAAW,CAAC;AAC1D,QAAM,MAAM,aAAAA,QAAM,cAA6C,MAAS;AACxE,MAAI,cAAc;AAElB,QAAM,SAAS,MAAM;AACnB,UAAM,MAAM,aAAAA,QAAM,WAAW,GAAG;AAChC,gBAAY,KAAK,kCAAkC,IAAI,WAAW,EAAE;AAEpE,WAAQ,IAAY;AAAA,EACtB;AAEA,QAAM,yBAAyB,MAAM;AACnC,UAAM,MAAM,aAAAA,QAAM,WAAW,GAAG;AAEhC,WAAO,MAAM,IAAI,QAAQ,CAAC;AAAA,EAC5B;AAEA,SAAO,CAAC,KAAK,QAAQ,sBAAsB;AAC7C;","names":["React"]}