diff options
author | 2022-03-07 15:36:22 -0600 | |
---|---|---|
committer | 2022-03-07 15:36:22 -0600 | |
commit | f18ee36dc0abdc5c8ec87734de7962966d16fe65 (patch) | |
tree | c01a7034186cb0bbe5e1d042f4a5dd09bad21ed5 /packages/webapi/src/lib/ContextEvent.ts | |
parent | 10a9c3412b4f6e8607687a74eafdb150d3222047 (diff) | |
download | astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.tar.gz astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.tar.zst astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.zip |
Add `@astrojs/webapi` package (#2729)@astrojs/webapi@0.11.0
* chore: add @astrojs/webapi
* chore: update package.json
* fix: update file case
* fix: remove lowercase file
* chore: update tests to use mocha
* chore: update LICENSE
Diffstat (limited to 'packages/webapi/src/lib/ContextEvent.ts')
-rw-r--r-- | packages/webapi/src/lib/ContextEvent.ts | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/packages/webapi/src/lib/ContextEvent.ts b/packages/webapi/src/lib/ContextEvent.ts new file mode 100644 index 000000000..98cd72de5 --- /dev/null +++ b/packages/webapi/src/lib/ContextEvent.ts @@ -0,0 +1,52 @@ +import { Event } from 'event-target-shim' + +/** An event fired by a context requester to signal it desires a named context. */ +export class ContextEvent<T = unknown> extends Event<'context-request'> { + constructor(init: ContextEventInit<T>) { + super('context-request', { bubbles: true, composed: true }) + + init = Object(init) as Required<ContextEventInit<T>> + + this.context = init.context + } + + context!: Context<T> + multiple!: boolean + callback!: ContextCallback<Context<T>> +} + +interface ContextEventInit<T = unknown> { + context: Context<T> + multiple?: boolean + callback: ContextCallback<Context<T>> +} + +/** A Context object defines an optional initial value for a Context, as well as a name identifier for debugging purposes. */ +export type Context<T = unknown> = { + name: string + initialValue?: T +} + +/** A helper type which can extract a Context value type from a Context type. */ +export type ContextType<T extends Context> = T extends Context<infer Y> ? Y : never + +/** A function which creates a Context value object */ +export function createContext<T>(name: string, initialValue?: T): Readonly<Context<T>> { + return { + name, + initialValue, + } +} + +/** A callback which is provided by a context requester and is called with the value satisfying the request. */ +export type ContextCallback<ValueType> = ( + value: ValueType, + dispose?: () => void +) => void + +declare global { + interface HTMLElementEventMap { + /** A 'context-request' event can be emitted by any element which desires a context value to be injected by an external provider. */ + 'context-request': ContextEvent + } +} |