Security News
cURL Project and Go Security Teams Reject CVSS as Broken
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
@lit/context
Advanced tools
This module defines an implementation of controllers and decorators for using the Context Protocol as defined by the Web Components Community Group.
This protocol facilitates the communication between components lower in the DOM hierarchy with their ancestors, allowing data to be passed down the tree without having to be passed via 'prop drilling' where each element in the path passes on the data.
For further explanation of the Context Protocol please see the community protocol documentation.
There are several different usages of the Context API.
First lets define a context key we can use elsewhere in our examples:
logger.ts
:import {createContext} from '@lit/context';
export interface Logger {
log: (msg: string) => void;
}
export const loggerContext = createContext<Logger>('logger');
Now we can define a consumer for this context - some component in our app needs the logger.
Here we're using the @consume
property decorator to make a ContextConsumer
controller
and update its value when the context changes:
my-element.ts
:import {LitElement, property} from 'lit';
import {consume} from '@lit/context';
import {Logger, loggerContext} from './logger.js';
export class MyElement extends LitElement {
@consume({context: loggerContext, subscribe: true})
@property({attribute: false})
public logger?: Logger;
private doThing() {
this.logger?.log('a thing was done');
}
}
Another way we can use a context in a component is via the ContextConsumer
controller directly:
my-element.ts
:import {LitElement, property} from 'lit';
import {ContextConsumer} from '@lit/context';
import {Logger, loggerContext} from './logger.js';
export class MyElement extends LitElement {
public logger = new ContextConsumer(
this,
loggerContext,
undefined, // don't need to pass a callback
true // pass true to get updates if the logger changes
);
private doThing() {
this.logger.value?.log('a thing was done');
}
}
Finally we want to be able to provide this context from somewhere higher in the DOM.
Here we're using a @provide
property decorator to make a ContextProvider
controller and update its value when the property value changes.
my-app.ts
:import {LitElement, property, html} from 'lit';
import {provide} from '@lit/context';
import {loggerContext, Logger} from './logger.js';
export class MyApp extends LitElement {
@provide({context: loggerContext})
@property({attribute: false})
public logger: Logger = {
log: (msg) => {
console.log(`[my-app] ${msg}`);
},
});
protected render(): TemplateResult {
return html`<my-thing></my-thing>`;
}
}
We can also use the ContextProvider
controller directly:
my-app.ts
:import {LitElement, html} from 'lit';
import {ContextProvider} from '@lit/context';
import {loggerContext, Logger} from './logger.js';
export class MyApp extends LitElement {
// create a provider controller and a default logger
private provider = new ContextProvider(this, loggerContext, {
log: (msg) => {
console.log(`[my-app] ${msg}`);
},
});
protected render(): TemplateResult {
return html`<my-thing></my-thing>`;
}
public setLogger(newLogger: Logger) {
// update the provider with a new logger value
this.provider.setValue(newLogger);
}
}
In some cases you might have a context providing element that is upgraded late. LightDOM content below this provider may end up requesting a context that is currently not provided by any provider.
To solve this case we provide a ContextRoot
class which can intercept and track unsatisfied context-request
events and then redispatch these requests when providers are updated.
Example usage:
index.ts
:import {ContextRoot} from '@lit/context';
const root = new ContextRoot();
root.attach(document.body);
The ContextRoot
can be attached to any element and it will gather a list of any context requests which are received at the attached element. The ContextProvider
controllers will emit context-provider
events when they are connected to the DOM. These events act as triggers for the ContextRoot
to redispatch these context-request
events from their sources.
This solution has a small overhead, in that if a provider is not within the DOM hierarchy of the unsatisfied requests we are unnecessarily refiring these requests, but this approach is safest and most correct in that it is very hard to manage unstable DOM hierarchies with the semantics of slotting and reparenting that is common in web components implementations.
Note that ContextRoot uses WeakRefs which are not supported in IE11.
You can use the @consume
and @provide
decorators on TypeScript protected
and private
properties, but be aware that there is no type checking between the type of the context and the type of the property. This is because the TypeScript compiler does not make type information for protected or private properties available to decorators. Standard #private
properties are not supported at all.
We expect to fix all of this when we switch to standard decorators. See #3926.
Please see CONTRIBUTING.md.
@lit/reactive-element
- 1.0.0
@lit/reactive-element
is a new package that factors out the base class that provides the reactive update lifecycle based on property/attribute changes to LitElement
(what was previously called UpdatingElement
) into a separate package. LitElement
now extends ReactiveElement
to add lit-html
rendering via the render()
callback. See ReactiveElement API for more details.UpdatingElement
has been renamed to ReactiveElement
.updating-element
package has been renamed to @lit/reactive-element
.@internalProperty
decorator has been renamed to @state
._getUpdateComplete
to getUpdateComplete
.reflect: true
and its toAttribute
function returns undefined
the attribute is now removed where previously it was left unchanged (#872).unhandledrejection
event handler on window.renderRoot
is now created when the element's connectedCallback
is initially run.requestUpdateInternal
. The requestUpdate
method is now identical to this method and should be used instead.initialize
method has been removed. This work is now done in the element constructor.static addInitializer
for adding a function which is called with the element instance when is created. This can be used, for example, to create decorators which hook into element lifecycle by creating a reactive controller (#1663).connectedCallback
, disconnectedCallback
, willUpdate
, update
, and updated
. To ensure it has access to the element lifecycle, a controller should be added in the element's constructor. To add a controller to the element, call addController(controller)
.removeController(controller)
which can be used to remove a controller from a ReactiveElement
.willUpdate(changedProperties)
lifecycle method to UpdatingElement. This is called before the update
method and can be used to compute derived state needed for updating. This method is intended to be called during server side rendering and should not manipulate element DOM.FAQs
Helpers and controllers for using Context protocol
The npm package @lit/context receives a total of 48,181 weekly downloads. As such, @lit/context popularity was classified as popular.
We found that @lit/context demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.