context-request-event.d.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license
  3. * Copyright 2021 Google LLC
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. import { ContextType, Context } from './create-context.js';
  7. declare global {
  8. interface HTMLElementEventMap {
  9. /**
  10. * A 'context-request' event can be emitted by any element which desires
  11. * a context value to be injected by an external provider.
  12. */
  13. 'context-request': ContextRequestEvent<Context<unknown, unknown>>;
  14. }
  15. }
  16. /**
  17. * A callback which is provided by a context requester and is called with the value satisfying the request.
  18. * This callback can be called multiple times by context providers as the requested value is changed.
  19. */
  20. export type ContextCallback<ValueType> = (value: ValueType, unsubscribe?: () => void) => void;
  21. /**
  22. * Interface definition for a ContextRequest
  23. */
  24. export interface ContextRequest<C extends Context<unknown, unknown>> {
  25. readonly context: C;
  26. readonly contextTarget: Element;
  27. readonly callback: ContextCallback<ContextType<C>>;
  28. readonly subscribe?: boolean;
  29. }
  30. /**
  31. * An event fired by a context requester to signal it desires a specified context with the given key.
  32. *
  33. * A provider should inspect the `context` property of the event to determine if it has a value that can
  34. * satisfy the request, calling the `callback` with the requested value if so.
  35. *
  36. * If the requested context event contains a truthy `subscribe` value, then a provider can call the callback
  37. * multiple times if the value is changed, if this is the case the provider should pass an `unsubscribe`
  38. * method to the callback which consumers can invoke to indicate they no longer wish to receive these updates.
  39. *
  40. * If no `subscribe` value is present in the event, then the provider can assume that this is a 'one time'
  41. * request for the context and can therefore not track the consumer.
  42. */
  43. export declare class ContextRequestEvent<C extends Context<unknown, unknown>> extends Event implements ContextRequest<C> {
  44. readonly context: C;
  45. readonly contextTarget: Element;
  46. readonly callback: ContextCallback<ContextType<C>>;
  47. readonly subscribe?: boolean;
  48. /**
  49. *
  50. * @param context the context key to request
  51. * @param contextTarget the original context target of the requester
  52. * @param callback the callback that should be invoked when the context with the specified key is available
  53. * @param subscribe when, true indicates we want to subscribe to future updates
  54. */
  55. constructor(context: C, contextTarget: Element, callback: ContextCallback<ContextType<C>>, subscribe?: boolean);
  56. }
  57. //# sourceMappingURL=context-request-event.d.ts.map