https://github.com/open-wc/context-protocol
A Lit compatible implementation of the context-protocol community protocol
https://github.com/open-wc/context-protocol
Last synced: 2 months ago
JSON representation
A Lit compatible implementation of the context-protocol community protocol
- Host: GitHub
- URL: https://github.com/open-wc/context-protocol
- Owner: open-wc
- Created: 2024-03-29T10:23:50.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-05-23T09:01:07.000Z (about 1 year ago)
- Last Synced: 2025-03-27T05:26:40.067Z (3 months ago)
- Language: TypeScript
- Size: 132 KB
- Stars: 9
- Watchers: 2
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# @open-wc/context-protocol
A Lit compatible implementation of the [context-protocol community protocol](https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md).
## Installation
```sh
npm install --save @open-wc/context-protocol
```## Usage
A component that implements the ProviderMixin will become a _Provider_ of data and a component that implements the ConsumerMixin will become a _Consumer_ of data.
```ts
import { ProviderMixin } from "@open-wc/context-protocol";export class ProviderElement extends ProviderMixin(HTMLElement) {
// Set any data contexts here.
contexts = {
"number-of-unread-messages": () => {
return 0;
},
};async connectedCallback() {
// It's also possible to provide context at any point using `updateContext`.const response = await fetch("/api/messages/");
const data = await response.json();
this.updateContext("number-of-unread-messages", data.unreadCount);
}
}
``````ts
import { ConsumerMixin } from "@open-wc/context-protocol";export class ConsumerElement extends ConsumerMixin(HTMLElement) {
contexts = {
// Fetch contexts that we care about and subscribe to any changes.
"number-of-unread-messages": (count: number) => {
this.textContent = `${count} unread messages!`;
},
};connectedCallback() {
// It's also possible to get any context on demand without subscribing.
this.textContent = this.getContext("number-of-unread-messages");
}
}
```