Skip to content

Instantly share code, notes, and snippets.

@grimly
Last active July 20, 2023 23:34
Show Gist options
  • Save grimly/b84d48cc8846486f23297b3b1b2d774d to your computer and use it in GitHub Desktop.
Save grimly/b84d48cc8846486f23297b3b1b2d774d to your computer and use it in GitHub Desktop.

Context for the DOM

The goal is to provide a context for a subtree of the DOM. It is inspired by the React Context.

An element that wish to provide a context should set a context value or discard its own.

If the element provides no value, the parent's context is used. If there is no context up the DOM tree, the default value is provided instead.

An element may use the context and fetch an appropriate value. The returned Observable must emit an event immediately upon subscription.

If an element both provide and use the context, the usage will fetch the value from the parent context, thus allowing an immediate mapping of the context.

Implementation tools

The following parts of the DOM API may be used toward a solution.

Bubbling and composed events

An event with {bubble: true, composed: true} options will pass through the DOM hierarchy and the complexity is dealt by the platform.

Mutation observers

Some of the DOM features don't have better option than mutation observers to react for changes. For instance, Shadow DOM and slots may change without any notification to the parents or childrens elements.

export interface Context<T> {
set(provider: Node, value: T): void;
delete(provider: Node): void;
use(consumer: Node): Observable<T>;
}
export function createContext<T>(defaultValue: T): Context<T> {
throw new Error("Not implemented yet!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment