Socket
Socket
Sign inDemoInstall

lit-element

Package Overview
Dependencies
1
Maintainers
5
Versions
82
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.0.0-dev.aa290cf to 2.0.0-dev.daf5276

12

CHANGELOG.md

@@ -17,5 +17,16 @@ # Change Log

## Unreleased
### Changed
* [Breaking] Renamed `unsafeCss` to `unsafeCSS` for consistency with lit-html's `unsafeHTML`
### Fixed
* Adds a check to ensure `CSSStyleSheet` is constructable ([#525](https://github.com/Polymer/lit-element/issues/525)).
## [2.0.0-rc.5] - 2019-01-24
### Fixed
* Fixed a bug causing duplicate styles when an array was returned from `static get styles` ([#480](https://github.com/Polymer/lit-element/issues/480)).
## [2.0.0-rc.4] - 2019-01-24
### Added
* [Maintenance] Added script to publish dev releases automatically ([#476](https://github.com/Polymer/lit-element/pull/476)).
* Adds `unsafeCss` for composing "unsafe" values into `css`. Note, `CSSResult` is no longer constructable. ([#451](https://github.com/Polymer/lit-element/issues/451) and [#471](https://github.com/Polymer/lit-element/issues/471)).

@@ -25,2 +36,3 @@ ### Fixed

* Fixed an issue with inheriting from `styles` property when extending a superclass that is never instanced. ([#470](https://github.com/Polymer/lit-element/pull/470)).
* Fixed an issue with Closure Compiler and ([#470](https://github.com/Polymer/lit-element/pull/470)) ([#476](https://github.com/Polymer/lit-element/pull/476)).

@@ -27,0 +39,0 @@ ## [2.0.0-rc.3] - 2019-01-18

17

lib/css-tag.d.ts

@@ -15,6 +15,21 @@ /**

readonly cssText: string;
constructor(cssText: string);
constructor(cssText: string, safeToken: symbol);
readonly styleSheet: CSSStyleSheet | null;
toString(): String;
}
/**
* Wrap a value for interpolation in a css tagged template literal.
*
* This is unsafe because untrusted CSS text can be used to phone home
* or exfiltrate data to an attacker controlled site. Take care to only use
* this with trusted input.
*/
export declare const unsafeCSS: (value: unknown) => CSSResult;
/**
* Template tag which which can be used with LitElement's `style` property to
* set element styles. For security reasons, only literal string values may be
* used. To incorporate non-literal values `unsafeCSS` may be used inside a
* template string part.
*/
export declare const css: (strings: TemplateStringsArray, ...values: CSSResult[]) => CSSResult;
//# sourceMappingURL=css-tag.d.ts.map

@@ -11,5 +11,12 @@ /**

*/
export const supportsAdoptingStyleSheets = ('adoptedStyleSheets' in Document.prototype);
export const supportsAdoptingStyleSheets = ('adoptedStyleSheets' in Document.prototype) &&
('replace' in CSSStyleSheet.prototype);
const constructionToken = Symbol();
export class CSSResult {
constructor(cssText) { this.cssText = cssText; }
constructor(cssText, safeToken) {
if (safeToken !== constructionToken) {
throw new Error('CSSResult is not constructable. Use `unsafeCSS` or `css` instead.');
}
this.cssText = cssText;
}
// Note, this is a getter so that it's lazy. In practice, this means

@@ -31,3 +38,16 @@ // stylesheets are not created until the first element instance is made.

}
toString() {
return this.cssText;
}
}
/**
* Wrap a value for interpolation in a css tagged template literal.
*
* This is unsafe because untrusted CSS text can be used to phone home
* or exfiltrate data to an attacker controlled site. Take care to only use
* this with trusted input.
*/
export const unsafeCSS = (value) => {
return new CSSResult(String(value), constructionToken);
};
const textFromCSSResult = (value) => {

@@ -38,9 +58,16 @@ if (value instanceof CSSResult) {

else {
throw new Error(`Value passed to 'css' function must be a 'css' function result: ${value}.`);
throw new Error(`Value passed to 'css' function must be a 'css' function result: ${value}. Use 'unsafeCSS' to pass non-literal values, but
take care to ensure page security.`);
}
};
/**
* Template tag which which can be used with LitElement's `style` property to
* set element styles. For security reasons, only literal string values may be
* used. To incorporate non-literal values `unsafeCSS` may be used inside a
* template string part.
*/
export const css = (strings, ...values) => {
const cssText = values.reduce((acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1], strings[0]);
return new CSSResult(cssText);
return new CSSResult(cssText, constructionToken);
};
//# sourceMappingURL=css-tag.js.map

14

lib/decorators.d.ts

@@ -36,16 +36,2 @@ /**

* @param tagName the name of the custom element to define
*
* In TypeScript, the `tagName` passed to `customElement` should be a key of the
* `HTMLElementTagNameMap` interface. To add your element to the interface,
* declare the interface in this module:
*
* @customElement('my-element')
* export class MyElement extends LitElement {}
*
* declare global {
* interface HTMLElementTagNameMap {
* 'my-element': MyElement;
* }
* }
*
*/

@@ -52,0 +38,0 @@ export declare const customElement: (tagName: string) => (classOrDescriptor: ClassDescriptor | Constructor<HTMLElement>) => any;

@@ -38,20 +38,6 @@ /**

* @param tagName the name of the custom element to define
*
* In TypeScript, the `tagName` passed to `customElement` should be a key of the
* `HTMLElementTagNameMap` interface. To add your element to the interface,
* declare the interface in this module:
*
* @customElement('my-element')
* export class MyElement extends LitElement {}
*
* declare global {
* interface HTMLElementTagNameMap {
* 'my-element': MyElement;
* }
* }
*
*/
export const customElement = (tagName) => (classOrDescriptor) => (typeof classOrDescriptor === 'function')
? legacyCustomElement(tagName, classOrDescriptor)
: standardCustomElement(tagName, classOrDescriptor);
export const customElement = (tagName) => (classOrDescriptor) => (typeof classOrDescriptor === 'function') ?
legacyCustomElement(tagName, classOrDescriptor) :
standardCustomElement(tagName, classOrDescriptor);
const standardProperty = (options, element) => {

@@ -97,3 +83,4 @@ // When decorating an accessor, pass it through and add property metadata.

const legacyProperty = (options, proto, name) => {
proto.constructor.createProperty(name, options);
proto.constructor
.createProperty(name, options);
};

@@ -108,5 +95,5 @@ /**

export function property(options) {
return (protoOrDescriptor, name) => (name !== undefined)
? legacyProperty(options, protoOrDescriptor, name)
: standardProperty(options, protoOrDescriptor);
return (protoOrDescriptor, name) => (name !== undefined) ?
legacyProperty(options, protoOrDescriptor, name) :
standardProperty(options, protoOrDescriptor);
}

@@ -123,3 +110,5 @@ /**

export const queryAll = _query((target, selector) => target.querySelectorAll(selector));
const legacyQuery = (descriptor, proto, name) => { Object.defineProperty(proto, name, descriptor); };
const legacyQuery = (descriptor, proto, name) => {
Object.defineProperty(proto, name, descriptor);
};
const standardQuery = (descriptor, element) => ({

@@ -142,9 +131,11 @@ kind: 'method',

const descriptor = {
get() { return queryFn(this.renderRoot, selector); },
get() {
return queryFn(this.renderRoot, selector);
},
enumerable: true,
configurable: true,
};
return (name !== undefined)
? legacyQuery(descriptor, protoOrDescriptor, name)
: standardQuery(descriptor, protoOrDescriptor);
return (name !== undefined) ?
legacyQuery(descriptor, protoOrDescriptor, name) :
standardQuery(descriptor, protoOrDescriptor);
};

@@ -157,3 +148,5 @@ }

};
const legacyEventOptions = (options, proto, name) => { Object.assign(proto[name], options); };
const legacyEventOptions = (options, proto, name) => {
Object.assign(proto[name], options);
};
/**

@@ -191,5 +184,5 @@ * Adds event listener options to a method used as an event listener in a

// the others
((protoOrDescriptor, name) => (name !== undefined)
? legacyEventOptions(options, protoOrDescriptor, name)
: standardEventOptions(options, protoOrDescriptor));
((protoOrDescriptor, name) => (name !== undefined) ?
legacyEventOptions(options, protoOrDescriptor, name) :
standardEventOptions(options, protoOrDescriptor));
//# sourceMappingURL=decorators.js.map

@@ -151,3 +151,5 @@ /**

Object.defineProperty(this.prototype, name, {
get() { return this[key]; },
get() {
return this[key];
},
set(value) {

@@ -190,5 +192,5 @@ const oldValue = this[name];

...Object.getOwnPropertyNames(props),
...(typeof Object.getOwnPropertySymbols === 'function')
? Object.getOwnPropertySymbols(props)
: []
...(typeof Object.getOwnPropertySymbols === 'function') ?
Object.getOwnPropertySymbols(props) :
[]
];

@@ -209,8 +211,7 @@ // This for/of is ok because propKeys is an array

const attribute = options.attribute;
return attribute === false
? undefined
: (typeof attribute === 'string'
? attribute
: (typeof name === 'string' ? name.toLowerCase()
: undefined));
return attribute === false ?
undefined :
(typeof attribute === 'string' ?
attribute :
(typeof name === 'string' ? name.toLowerCase() : undefined));
}

@@ -260,3 +261,5 @@ /**

*/
initialize() { this._saveInstanceProperties(); }
initialize() {
this._saveInstanceProperties();
}
/**

@@ -317,3 +320,4 @@ * Fixes any properties set on the instance before upgrade time.

*/
disconnectedCallback() { }
disconnectedCallback() {
}
/**

@@ -446,3 +450,5 @@ * Synchronizes property values when attributes change.

}
get hasUpdated() { return (this._updateState & STATE_HAS_UPDATED); }
get hasUpdated() {
return (this._updateState & STATE_HAS_UPDATED);
}
/**

@@ -496,3 +502,5 @@ * Performs an element update.

*/
get updateComplete() { return this._updatePromise; }
get updateComplete() {
return this._updatePromise;
}
/**

@@ -534,3 +542,4 @@ * Controls whether or not `update` should be called when the element requests

*/
updated(_changedProperties) { }
updated(_changedProperties) {
}
/**

@@ -545,3 +554,4 @@ * Invoked when the element is first updated. Implement to perform one time

*/
firstUpdated(_changedProperties) { }
firstUpdated(_changedProperties) {
}
}

@@ -548,0 +558,0 @@ /**

@@ -21,2 +21,7 @@ /**

export * from './lib/css-tag.js';
declare global {
interface Window {
litElementVersions: string[];
}
}
export interface CSSResultArray extends Array<CSSResult | CSSResultArray> {

@@ -45,3 +50,5 @@ }

private static _styles;
/** @nocollapse */
protected static finalize(): void;
/** @nocollapse */
private static _getUniqueStyles;

@@ -48,0 +55,0 @@ private _needsShimAdoptedStyleSheets?;

@@ -22,2 +22,7 @@ /**

export * from './lib/css-tag.js';
// IMPORTANT: do not change the property name or the assignment expression.
// This line will be used in regexes to search for LitElement usage.
// TODO(justinfagnani): inject version number at build time
(window['litElementVersions'] || (window['litElementVersions'] = []))
.push('2.0.0');
/**

@@ -43,2 +48,3 @@ * Minimal implementation of Array.prototype.flat

export class LitElement extends UpdatingElement {
/** @nocollapse */
static finalize() {

@@ -48,6 +54,8 @@ super.finalize();

// is built from user provided `styles` or is inherited from the superclass.
this._styles = this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
this._styles =
this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
}
/** @nocollapse */
static _getUniqueStyles() {

@@ -61,5 +69,5 @@ // Take care not to call `this.styles` multiple times since this generates

const userStyles = this.styles;
let styles = [];
const styles = [];
if (Array.isArray(userStyles)) {
styles = flattenStyles(userStyles);
const flatStyles = flattenStyles(userStyles);
// As a performance optimization to avoid duplicated styling that can

@@ -70,3 +78,3 @@ // occur especially when composing via subclassing, de-duplicate styles

// important that last added styles override previous styles.
const styleSet = styles.reduceRight((set, s) => {
const styleSet = flatStyles.reduceRight((set, s) => {
set.add(s);

@@ -80,3 +88,3 @@ // on IE set.add does not return the set.

else if (userStyles) {
styles = [userStyles];
styles.push(userStyles);
}

@@ -180,3 +188,4 @@ return styles;

*/
render() { }
render() {
}
}

@@ -183,0 +192,0 @@ /**

{
"name": "lit-element",
"version": "2.0.0-dev.aa290cf",
"version": "2.0.0-dev.daf5276",
"description": "Polymer based lit-html custom element",

@@ -25,3 +25,3 @@ "license": "BSD-3-Clause",

"build:babel-test": "babel src/test/lib/decorators_test.ts --out-file test/lib/decorators-babel_test.js",
"gen-docs": "typedoc --readme docs/_api/api-readme.md --tsconfig tsconfig_apidoc.json --mode modules --theme docs/_api/theme --excludeNotExported --excludePrivate --ignoreCompilerErrors --exclude '{**/*test*,**/node_modules/**,**/test/**}' --out ./docs/api src/**/*.ts",
"gen-docs": "typedoc --readme docs/_api/api-readme.md --tsconfig tsconfig_apidoc.json --mode modules --theme docs/_api/theme --excludeNotExported --excludePrivate --ignoreCompilerErrors --exclude '{**/*test*,**/node_modules/**,**/test/**}' --out ./docs/api --gaID UA-39334307-23 src/**/*.ts",
"test": "npm run build && npm run build:babel-test && wct",

@@ -32,2 +32,3 @@ "checksize": "rollup -c ; rm lit-element.bundled.js",

"prepublishOnly": "npm run build",
"prepare": "npm run build",
"regen-package-lock": "rm -rf node_modules package-lock.json; npm install",

@@ -61,3 +62,3 @@ "publish-dev": "npm test && VERSION=${npm_package_version%-*}-dev.`git rev-parse --short HEAD` && npm version --no-git-tag-version $VERSION && npm publish --tag dev"

"dependencies": {
"lit-html": "^1.0.0-rc.2"
"lit-html": "^1.0.0-dev.c8753bc"
},

@@ -64,0 +65,0 @@ "publishConfig": {

# LitElement
A simple base class for creating fast, lightweight web components with [lit-html](https://lit-html.polymer-project.org/).
[![Build Status](https://travis-ci.org/Polymer/lit-element.svg?branch=master)](https://travis-ci.org/Polymer/lit-element)
[![Published on npm](https://img.shields.io/npm/v/lit-element.svg)](https://www.npmjs.com/package/lit-element)

@@ -7,5 +9,9 @@ [![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://www.webcomponents.org/element/lit-element)

## A simple base class for creating fast, lightweight web components
## Documentation
LitElement uses [lit-html](https://github.com/Polymer/lit-html) to render into the
Full documentation is available at [lit-element.polymer-project.org](https://lit-element.polymer-project.org).
## Overview
LitElement uses [lit-html](https://lit-html.polymer-project.org/) to render into the
element's [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM)

@@ -16,263 +22,55 @@ and adds API to help manage element properties and attributes. LitElement reacts to changes in properties

* **Setup properties:** LitElement supports observable properties that cause the element to update.
These properties can be declared in a few ways:
```ts
import {LitElement, html, css, customElement, property} from 'lit-element';
* As class fields with the `@property()` [decorator](https://github.com/tc39/proposal-decorators#decorators),
if you're using a compiler that supports them, like [TypeScript](https://www.typescriptlang.org/) or [Babel](https://babeljs.io/docs/en/babel-plugin-proposal-decorators).
* With a static `properties` getter.
* By manually writing getters and setters. This can be useful if tasks should
be performed when a property is set, for example validation. Call `requestUpdate(name, oldValue)`
in the setter to trigger an update and use any configured property options.
// This decorator defines the element.
@customElement('my-element');
export class MyElement extends LitElement {
Properties can be given an `options` argument which is an object that describes how to
process the property. This can be done either in the `@property({...})` decorator or in the
object returned from the `properties` getter, e.g. `static get properties { return { foo: {...} }`.
// This decorator creates a property accessor that triggers rendering and
// an observed attribute.
@property()
mood = 'great';
Property options include:
static styles = css`
span {
color: green;
}`;
* `attribute`: Indicates how and whether the property becomes an observed attribute.
If the value is `false`, the property is not added to the static `observedAttributes` getter.
If `true` or absent, the lowercased property name is observed (e.g. `fooBar` becomes `foobar`).
If a string, the string value is observed (e.g `attribute: 'foo-bar'`).
* `converter`: Indicates how to convert the attribute to/from a property.
The value can be a function used for both serialization and deserialization, or it can
be an object with individual functions via the optional keys, `fromAttribute` and `toAttribute`.
A default `converter` is used if none is provided; it supports
`Boolean`, `String`, `Number`, `Object`, and `Array`.
* `type`: Indicates the type of the property. This is used only as a hint for the
`converter` to determine how to convert the attribute
to/from a property. Note, when a property changes and the converter is used
to update the attribute, the property is never updated again as a result of
the attribute changing, and vice versa.
* `reflect`: Indicates whether the property should reflect to its associated
attribute (as determined by the attribute option). If `true`, when the
property is set, the attribute which name is determined according to the
rules for the `attribute` property option will be set to the value of the
property converted using the rules from the `type` and `converter`
property options.
* `hasChanged`: A function that indicates whether a property should be considered
changed when it is set and thus result in an update. The function should take the
`newValue` and `oldValue` and return `true` if an update should be requested.
* **React to changes:** LitElement reacts to changes in properties and attributes by
asynchronously rendering, ensuring changes are batched. This reduces overhead
and maintains consistent state.
* **Declarative rendering** LitElement uses `lit-html` to declaratively describe
how an element should render. Then `lit-html` ensures that updates
are fast by creating the static DOM once and smartly updating only the parts of
the DOM that change. Pass a JavaScript string to the `html` tag function,
describing dynamic parts with standard JavaScript template expressions:
* static elements: ``` html`<div>Hi</div>` ```
* expression: ``` html`<div>${this.disabled ? 'Off' : 'On'}</div>` ```
* property: ``` html`<x-foo .bar="${this.bar}"></x-foo>` ```
* attribute: ``` html`<div class="${this.color} special"></div>` ```
* boolean attribute: ``` html`<input type="checkbox" ?checked=${checked}>` ```
* event handler: ``` html`<button @click="${this._clickHandler}"></button>` ```
## Getting started
* The easiest way to try out LitElement is to use one of these online tools:
* Runs in all [supported](#supported-browsers) browsers: [Glitch](https://glitch.com/edit/#!/hello-lit-element?path=index.html)
* Runs in browsers with [JavaScript Modules](https://caniuse.com/#search=modules): [JSFiddle](https://jsfiddle.net/sorvell1/801f9cdu/), [JSBin](http://jsbin.com/vecuyan/edit?html,output),
[CodePen](https://codepen.io/sorvell/pen/RYQyoe?editors=1000).
* You can also copy [this HTML file](https://gist.githubusercontent.com/sorvell/48f4b7be35c8748e8f6db5c66d36ee29/raw/2427328cf1ebae5077902a6bff5ddd8db45e83e4/index.html) into a local file and run it in any browser that supports [JavaScript Modules]((https://caniuse.com/#search=modules)).
* When you're ready to use LitElement in a project, install it via [npm](https://www.npmjs.com/). To run the project in the browser, a module-compatible toolchain is required. We recommend installing the [Polymer CLI](https://github.com/Polymer/polymer-cli) and using its development server as follows.
1. Add LitElement to your project:
```npm i lit-element```
1. Install the webcomponents polyfill. If you're developing a reusable package, this should be a dev dependency which you load in your tests, demos, etc.
```npm i -D @webcomponents/webcomponentsjs```
1. Create an element by extending LitElement and calling `customElements.define` with your class (see the examples below).
1. Install the Polymer CLI:
```npm i -g polymer-cli```
1. Run the development server and open a browser pointing to its URL:
```polymer serve```
> LitElement is published on [npm](https://www.npmjs.com/package/lit-element) using JavaScript Modules.
This means it can take advantage of the standard native JavaScript module loader available in all current major browsers.
>
> However, since LitElement uses npm convention to reference dependencies by name, a light transform to rewrite specifiers to URLs is required to get it to run in the browser. The polymer-cli's development server `polymer serve` automatically handles this transform.
Tools like [WebPack](https://webpack.js.org/) and [Rollup](https://rollupjs.org/) can also be used to serve and/or bundle LitElement.
## Minimal Example
1. Create a class that extends `LitElement`.
1. Use a `@property` decorator to create a property (or implement a static `properties`
getter that returns the element's properties). (which automatically become observed attributes).
1. Then implement a `render()` method and use the element's
current properties to return a `lit-html` template result to render
into the element.
```html
<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
<script type="module">
import {LitElement, html} from 'lit-element';
class MyElement extends LitElement {
static get properties() {
return {
mood: {type: String}
};
}
constructor() {
super();
this.mood = 'happy';
}
// Render element DOM by returning a `lit-html` template.
render() {
return html`<style> .mood { color: green; } </style>
Web Components are <span class="mood">${this.mood}</span>!`;
return html`Web Components are <span>${this.mood}</span>!`;
}
}
```
customElements.define('my-element', MyElement);
</script>
<my-element mood="happy"></my-element>
```html
<my-element mood="awesome"></my-element>
```
## API Documentation
* `render()` (protected): Implement to describe the element's DOM using `lit-html`. Ideally,
the `render` implementation is a [pure function](https://en.wikipedia.org/wiki/Pure_function) using only the element's current properties to describe the element template. Note, since
`render()` is called by `update()`, setting properties does not trigger an
update, allowing property values to be computed and validated.
* `shouldUpdate(changedProperties)` (protected): Implement to control if updating and rendering
should occur when property values change or `requestUpdate()` is called. The `changedProperties`
argument is a Map with keys for the changed properties pointing to their previous values.
By default, this method always returns `true`, but this can be customized as
an optimization to avoid updating work when changes occur, which should not be rendered.
* `performUpdate()` (protected): Implement to control the timing of an update, for example
to integrate with a scheduler. If a Promise is returned from `performUpdate` it will be
awaited before finishing the update.
* `update(changedProperties)` (protected): This method calls `render()` and then uses `lit-html`
in order to render the template DOM. It also updates any reflected attributes based on
property values. Setting properties inside this method will *not* trigger another update.
* `firstUpdated(changedProperties)`: (protected) Called after the element's DOM has been
updated the first time, immediately before `updated()` is called.
This method can be useful for capturing references to rendered static nodes that
must be directly acted upon, for example in `updated()`.
Setting properties inside this method will trigger the element to update.
* `updated(changedProperties)`: (protected) Called whenever the element's DOM has been
updated and rendered. Implement to perform post updating tasks via DOM APIs, for example,
focusing an element. Setting properties inside this method will trigger the element to update.
* `updateComplete`: Returns a Promise that resolves when the element has completed
updating. The Promise value is a boolean that is `true` if the element completed the
update without triggering another update. The Promise result is `false` if a
property was set inside `updated()`. This getter can be implemented to await additional state.
For example, it is sometimes useful to await a rendered element before fulfilling
this Promise. To do this, first await `super.updateComplete` then any subsequent state.
* `requestUpdate(name?, oldValue?)`: Call to request the element to asynchronously
update regardless of whether or not any property changes are pending. This should
be called when an element should update based on some state not triggered
by setting a property. In this case, pass no arguments. It should also be called
when manually implementing a property setter. In this case, pass the property
`name` and `oldValue` to ensure that any configured property options are honored.
Returns the `updateComplete` Promise which is resolved when the update completes.
* `createRenderRoot()` (protected): Implement to customize where the
element's template is rendered by returning an element into which to
render. By default this creates a shadowRoot for the element.
To render into the element's childNodes, return `this`.
## Advanced: Update Lifecycle
* A property is set (e.g. `element.foo = 5`).
* If the property's `hasChanged(value, oldValue)` returns `false`, the element does not
update. If it returns `true`, `requestUpdate()` is called to schedule an update.
* `requestUpdate()`: Updates the element after awaiting a [microtask](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) (at the end
of the event loop, before the next paint).
* `performUpdate()`: Performs the update, calling the rest of the update API.
* `shouldUpdate(changedProperties)`: The update proceeds if this returns `true`, which
it does by default.
* `update(changedProperties)`: Updates the element. Setting properties inside this
method will *not* trigger another update.
* `render()`: Returns a `lit-html` TemplateResult (e.g. <code>html\`Hello ${world}\`</code>)
to render element DOM. Setting properties inside this method will *not* trigger
the element to update.
* `firstUpdated(changedProperties)`: Called after the element is updated the first time,
immediately before `updated` is called. Setting properties inside this method will
trigger the element to update.
* `updated(changedProperties)`: Called whenever the element is updated.
Setting properties inside this method will trigger the element to update.
* `updateComplete` Promise is resolved with a boolean that is `true` if the
element is not pending another update, and any code awaiting the element's
`updateComplete` Promise runs and observes the element in the updated state.
## Bigger Example
Note, this example uses decorators to create properties. Decorators are a proposed
standard currently available in [TypeScript](https://www.typescriptlang.org/) or [Babel](https://babeljs.io/docs/en/babel-plugin-proposal-decorators).
standard currently available in [TypeScript](https://www.typescriptlang.org/) or [Babel](https://babeljs.io/docs/en/babel-plugin-proposal-decorators). LitElement also supports a [vanilla JavaScript method](https://lit-element.polymer-project.org/guide/properties#declare) of declaring reactive properties.
```ts
import {LitElement, html, property} from 'lit-element';
## Examples
class MyElement extends LitElement {
* Runs in all [supported](#supported-browsers) browsers: [Glitch](https://glitch.com/edit/#!/hello-lit-element?path=index.html)
// Public property API that triggers re-render (synced with attributes)
@property()
foo = 'foo';
* Runs in browsers with [JavaScript Modules](https://caniuse.com/#search=modules): [Stackblitz](https://stackblitz.com/edit/lit-element-demo?file=src%2Fmy-element.js), [JSFiddle](https://jsfiddle.net/sorvell1/801f9cdu/), [JSBin](http://jsbin.com/vecuyan/edit?html,output),
[CodePen](https://codepen.io/sorvell/pen/RYQyoe?editors=1000).
@property({type: Number})
whales = 5;
* You can also copy [this HTML file](https://gist.githubusercontent.com/sorvell/48f4b7be35c8748e8f6db5c66d36ee29/raw/67346e4e8bc4c81d5a7968d18f0a6a8bc00d792e/index.html) into a local file and run it in any browser that supports [JavaScript Modules]((https://caniuse.com/#search=modules)).
constructor() {
super();
this.addEventListener('click', async (e) => {
this.whales++;
await this.updateComplete;
this.dispatchEvent(new CustomEvent('whales', {detail: {whales: this.whales}}))
});
}
## Installation
// Render method should return a `TemplateResult` using the provided lit-html `html` tag function
render() {
return html`
<style>
:host {
display: block;
}
:host([hidden]) {
display: none;
}
</style>
<h4>Foo: ${this.foo}</h4>
<div>whales: ${'🐳'.repeat(this.whales)}</div>
<slot></slot>
`;
}
From inside your project folder, run:
}
customElements.define('my-element', MyElement);
```bash
$ npm install lit-element
```
```html
<my-element whales="5">hi</my-element>
To install the web components polyfills needed for older browsers:
```bash
$ npm i -D @webcomponents/webcomponentsjs
```

@@ -285,8 +83,6 @@

## Known Issues
Edge and Internet Explorer 11 require the web components polyfills.
* On very old versions of Safari (<=9) or Chrome (<=41), properties created for native
platform properties like (`id` or `name`) may not have default values set in the element constructor.
On these browsers native properties appear on instances and therefore their default value
will overwrite any element default (e.g. if the element sets this.id = 'id' in the constructor,
the 'id' will become '' since this is the native platform default).
## Contributing
Please see [CONTRIBUTING.md](./CONTRIBUTING.md).

@@ -23,3 +23,3 @@ interface ShadyCSS {

declare var ShadowRoot: {prototype: ShadowRoot; new () : ShadowRoot;}
declare var ShadowRoot: {prototype: ShadowRoot; new (): ShadowRoot;}

@@ -26,0 +26,0 @@ interface CSSStyleSheet {

@@ -13,6 +13,8 @@ /**

export const supportsAdoptingStyleSheets =
('adoptedStyleSheets' in Document.prototype);
('adoptedStyleSheets' in Document.prototype) &&
('replace' in CSSStyleSheet.prototype);
const constructionToken = Symbol();
export class CSSResult {
_styleSheet?: CSSStyleSheet|null;

@@ -22,3 +24,9 @@

constructor(cssText: string) { this.cssText = cssText; }
constructor(cssText: string, safeToken: symbol) {
if (safeToken !== constructionToken) {
throw new Error(
'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.');
}
this.cssText = cssText;
}

@@ -40,4 +48,19 @@ // Note, this is a getter so that it's lazy. In practice, this means

}
toString(): String {
return this.cssText;
}
}
/**
* Wrap a value for interpolation in a css tagged template literal.
*
* This is unsafe because untrusted CSS text can be used to phone home
* or exfiltrate data to an attacker controlled site. Take care to only use
* this with trusted input.
*/
export const unsafeCSS = (value: unknown) => {
return new CSSResult(String(value), constructionToken);
};
const textFromCSSResult = (value: CSSResult) => {

@@ -49,12 +72,18 @@ if (value instanceof CSSResult) {

`Value passed to 'css' function must be a 'css' function result: ${
value}.`);
value}. Use 'unsafeCSS' to pass non-literal values, but
take care to ensure page security.`);
}
};
export const css =
(strings: TemplateStringsArray, ...values: CSSResult[]): CSSResult => {
const cssText = values.reduce(
(acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],
strings[0]);
return new CSSResult(cssText);
};
/**
* Template tag which which can be used with LitElement's `style` property to
* set element styles. For security reasons, only literal string values may be
* used. To incorporate non-literal values `unsafeCSS` may be used inside a
* template string part.
*/
export const css = (strings: TemplateStringsArray, ...values: CSSResult[]) => {
const cssText = values.reduce(
(acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],
strings[0]);
return new CSSResult(cssText, constructionToken);
};

@@ -70,23 +70,9 @@

* @param tagName the name of the custom element to define
*
* In TypeScript, the `tagName` passed to `customElement` should be a key of the
* `HTMLElementTagNameMap` interface. To add your element to the interface,
* declare the interface in this module:
*
* @customElement('my-element')
* export class MyElement extends LitElement {}
*
* declare global {
* interface HTMLElementTagNameMap {
* 'my-element': MyElement;
* }
* }
*
*/
export const customElement = (tagName: string) => (
classOrDescriptor: Constructor<HTMLElement>|ClassDescriptor) =>
(typeof classOrDescriptor === 'function')
? legacyCustomElement(tagName,
classOrDescriptor as Constructor<HTMLElement>)
: standardCustomElement(tagName, classOrDescriptor as ClassDescriptor);
export const customElement = (tagName: string) =>
(classOrDescriptor: Constructor<HTMLElement>|ClassDescriptor) =>
(typeof classOrDescriptor === 'function') ?
legacyCustomElement(
tagName, classOrDescriptor as Constructor<HTMLElement>) :
standardCustomElement(tagName, classOrDescriptor as ClassDescriptor);

@@ -111,6 +97,6 @@ const standardProperty =

return {
kind : 'field',
key : Symbol(),
placement : 'own',
descriptor : {},
kind: 'field',
key: Symbol(),
placement: 'own',
descriptor: {},
// When @babel/plugin-proposal-decorators implements initializers,

@@ -137,6 +123,7 @@ // do this instead of the initializer below. See:

const legacyProperty = (options: PropertyDeclaration, proto: Object,
name: PropertyKey) => {
(proto.constructor as typeof UpdatingElement).createProperty(name!, options);
};
const legacyProperty =
(options: PropertyDeclaration, proto: Object, name: PropertyKey) => {
(proto.constructor as typeof UpdatingElement)
.createProperty(name!, options);
};

@@ -152,6 +139,5 @@ /**

return (protoOrDescriptor: Object|ClassElement, name?: PropertyKey): any =>
(name !== undefined)
? legacyProperty(options!, protoOrDescriptor as Object, name)
: standardProperty(options!,
protoOrDescriptor as ClassElement);
(name !== undefined) ?
legacyProperty(options!, protoOrDescriptor as Object, name) :
standardProperty(options!, protoOrDescriptor as ClassElement);
}

@@ -163,4 +149,4 @@

*/
export const query = _query((target: NodeSelector, selector: string) =>
target.querySelector(selector));
export const query = _query(
(target: NodeSelector, selector: string) => target.querySelector(selector));

@@ -171,14 +157,16 @@ /**

*/
export const queryAll = _query((target: NodeSelector, selector: string) =>
target.querySelectorAll(selector));
export const queryAll = _query(
(target: NodeSelector, selector: string) =>
target.querySelectorAll(selector));
const legacyQuery =
(descriptor: PropertyDescriptor, proto: Object,
name: PropertyKey) => { Object.defineProperty(proto, name, descriptor); };
(descriptor: PropertyDescriptor, proto: Object, name: PropertyKey) => {
Object.defineProperty(proto, name, descriptor);
};
const standardQuery = (descriptor: PropertyDescriptor, element: ClassElement) =>
({
kind : 'method',
placement : 'prototype',
key : element.key,
kind: 'method',
placement: 'prototype',
key: element.key,
descriptor,

@@ -196,13 +184,16 @@ });

function _query<T>(queryFn: (target: NodeSelector, selector: string) => T) {
return (selector: string) => (protoOrDescriptor: Object|ClassElement,
name?: PropertyKey): any => {
const descriptor = {
get(this: LitElement) { return queryFn(this.renderRoot!, selector); },
enumerable : true,
configurable : true,
};
return (name !== undefined)
? legacyQuery(descriptor, protoOrDescriptor as Object, name)
: standardQuery(descriptor, protoOrDescriptor as ClassElement);
};
return (selector: string) =>
(protoOrDescriptor: Object|ClassElement,
name?: PropertyKey): any => {
const descriptor = {
get(this: LitElement) {
return queryFn(this.renderRoot!, selector);
},
enumerable: true,
configurable: true,
};
return (name !== undefined) ?
legacyQuery(descriptor, protoOrDescriptor as Object, name) :
standardQuery(descriptor, protoOrDescriptor as ClassElement);
};
}

@@ -215,4 +206,4 @@

finisher(clazz: typeof UpdatingElement) {
Object.assign(clazz.prototype[element.key as keyof UpdatingElement],
options);
Object.assign(
clazz.prototype[element.key as keyof UpdatingElement], options);
}

@@ -223,4 +214,5 @@ };

const legacyEventOptions =
(options: AddEventListenerOptions, proto: any,
name: PropertyKey) => { Object.assign(proto[name], options); };
(options: AddEventListenerOptions, proto: any, name: PropertyKey) => {
Object.assign(proto[name], options);
};

@@ -260,5 +252,5 @@ /**

((protoOrDescriptor: Object|ClassElement, name?: string) =>
(name !== undefined)
? legacyEventOptions(options, protoOrDescriptor as Object, name)
: standardEventOptions(options,
protoOrDescriptor as ClassElement)) as any;
(name !== undefined) ?
legacyEventOptions(options, protoOrDescriptor as Object, name) :
standardEventOptions(options, protoOrDescriptor as ClassElement)) as
any;

@@ -37,3 +37,2 @@ /**

export interface ComplexAttributeConverter<Type = any, TypeHint = any> {
/**

@@ -59,3 +58,2 @@ * Function called to convert an attribute value to a property

export interface PropertyDeclaration<Type = any, TypeHint = any> {
/**

@@ -137,9 +135,9 @@ * Indicates how and whether the property becomes an observed attribute.

switch (type) {
case Boolean:
return value ? '' : null;
case Object:
case Array:
// if the value is `null` or `undefined` pass this through
// to allow removing/no change behavior.
return value == null ? value : JSON.stringify(value);
case Boolean:
return value ? '' : null;
case Object:
case Array:
// if the value is `null` or `undefined` pass this through
// to allow removing/no change behavior.
return value == null ? value : JSON.stringify(value);
}

@@ -151,9 +149,9 @@ return value;

switch (type) {
case Boolean:
return value !== null;
case Number:
return value === null ? null : Number(value);
case Object:
case Array:
return JSON.parse(value);
case Boolean:
return value !== null;
case Number:
return value === null ? null : Number(value);
case Object:
case Array:
return JSON.parse(value);
}

@@ -179,7 +177,7 @@ return value;

const defaultPropertyDeclaration: PropertyDeclaration = {
attribute : true,
type : String,
converter : defaultConverter,
reflect : false,
hasChanged : notEqual
attribute: true,
type: String,
converter: defaultConverter,
reflect: false,
hasChanged: notEqual
};

@@ -204,3 +202,2 @@

export abstract class UpdatingElement extends HTMLElement {
/*

@@ -270,4 +267,4 @@ * Due to closure compiler ES6 compilation bugs, @nocollapse is required on

if (superProperties !== undefined) {
superProperties.forEach((v: any, k: PropertyKey) =>
this._classProperties!.set(k, v));
superProperties.forEach(
(v: any, k: PropertyKey) => this._classProperties!.set(k, v));
}

@@ -284,5 +281,5 @@ }

*/
static createProperty(name: PropertyKey,
options:
PropertyDeclaration = defaultPropertyDeclaration) {
static createProperty(
name: PropertyKey,
options: PropertyDeclaration = defaultPropertyDeclaration) {
// Note, since this can be called by the `@property` decorator which

@@ -303,12 +300,13 @@ // is called before `finalize`, we ensure storage exists for property

Object.defineProperty(this.prototype, name, {
get(): any { return (this as any)[key]; },
get(): any {
return (this as any)[key];
},
set(this: UpdatingElement, value: any) {
const oldValue = (this as any)[name];
(this as any)[key] = value;
this.requestUpdate(name, oldValue);
},
configurable : true,
enumerable : true
}
);
this.requestUpdate(name, oldValue);
},
configurable: true,
enumerable: true
});
}

@@ -344,5 +342,5 @@

...Object.getOwnPropertyNames(props),
...(typeof Object.getOwnPropertySymbols === 'function')
? Object.getOwnPropertySymbols(props)
: []
...(typeof Object.getOwnPropertySymbols === 'function') ?
Object.getOwnPropertySymbols(props) :
[]
];

@@ -362,11 +360,10 @@ // This for/of is ok because propKeys is an array

*/
private static _attributeNameForProperty(name: PropertyKey,
options: PropertyDeclaration) {
private static _attributeNameForProperty(
name: PropertyKey, options: PropertyDeclaration) {
const attribute = options.attribute;
return attribute === false
? undefined
: (typeof attribute === 'string'
? attribute
: (typeof name === 'string' ? name.toLowerCase()
: undefined));
return attribute === false ?
undefined :
(typeof attribute === 'string' ?
attribute :
(typeof name === 'string' ? name.toLowerCase() : undefined));
}

@@ -380,4 +377,4 @@

*/
private static _valueHasChanged(value: unknown, old: unknown,
hasChanged: HasChanged = notEqual) {
private static _valueHasChanged(
value: unknown, old: unknown, hasChanged: HasChanged = notEqual) {
return hasChanged(value, old);

@@ -392,4 +389,4 @@ }

*/
private static _propertyValueFromAttribute(value: string,
options: PropertyDeclaration) {
private static _propertyValueFromAttribute(
value: string, options: PropertyDeclaration) {
const type = options.type;

@@ -410,4 +407,4 @@ const converter = options.converter || defaultConverter;

*/
private static _propertyValueToAttribute(value: unknown,
options: PropertyDeclaration) {
private static _propertyValueToAttribute(
value: unknown, options: PropertyDeclaration) {
if (options.reflect === undefined) {

@@ -450,3 +447,5 @@ return;

*/
protected initialize() { this._saveInstanceProperties(); }
protected initialize() {
this._saveInstanceProperties();
}

@@ -510,3 +509,4 @@ /**

*/
disconnectedCallback() {}
disconnectedCallback() {
}

@@ -592,4 +592,4 @@ /**

ctor._classProperties!.get(name) || defaultPropertyDeclaration;
if (ctor._valueHasChanged(this[name as keyof this], oldValue,
options.hasChanged)) {
if (ctor._valueHasChanged(
this[name as keyof this], oldValue, options.hasChanged)) {
// track old value when changing.

@@ -651,3 +651,5 @@ this._changedProperties.set(name, oldValue);

protected get hasUpdated() { return (this._updateState & STATE_HAS_UPDATED); }
protected get hasUpdated() {
return (this._updateState & STATE_HAS_UPDATED);
}

@@ -703,3 +705,5 @@ /**

*/
get updateComplete() { return this._updatePromise; }
get updateComplete() {
return this._updatePromise;
}

@@ -745,3 +749,4 @@ /**

*/
protected updated(_changedProperties: PropertyValues) {}
protected updated(_changedProperties: PropertyValues) {
}

@@ -757,3 +762,4 @@ /**

*/
protected firstUpdated(_changedProperties: PropertyValues) {}
protected firstUpdated(_changedProperties: PropertyValues) {
}
}

@@ -25,4 +25,16 @@ /**

export interface CSSResultArray extends Array<CSSResult | CSSResultArray> {}
declare global {
interface Window {
litElementVersions: string[];
}
}
// IMPORTANT: do not change the property name or the assignment expression.
// This line will be used in regexes to search for LitElement usage.
// TODO(justinfagnani): inject version number at build time
(window['litElementVersions'] || (window['litElementVersions'] = []))
.push('2.0.0');
export interface CSSResultArray extends Array<CSSResult|CSSResultArray> {}
/**

@@ -33,3 +45,4 @@ * Minimal implementation of Array.prototype.flat

*/
function arrayFlat(styles: CSSResultArray, result: CSSResult[] = []): CSSResult[] {
function arrayFlat(
styles: CSSResultArray, result: CSSResult[] = []): CSSResult[] {
for (let i = 0, length = styles.length; i < length; i++) {

@@ -47,6 +60,6 @@ const value = styles[i];

/** Deeply flattens styles array. Uses native flat if available. */
const flattenStyles = (styles: CSSResultArray): CSSResult[] => styles.flat ? styles.flat(Infinity) : arrayFlat(styles);
const flattenStyles = (styles: CSSResultArray): CSSResult[] =>
styles.flat ? styles.flat(Infinity) : arrayFlat(styles);
export class LitElement extends UpdatingElement {
/**

@@ -72,6 +85,7 @@ * Ensure this class is marked as `finalized` as an optimization ensuring

*/
static styles?: CSSResult | CSSResultArray;
static styles?: CSSResult|CSSResultArray;
private static _styles: CSSResult[]|undefined;
/** @nocollapse */
protected static finalize() {

@@ -81,7 +95,9 @@ super.finalize();

// is built from user provided `styles` or is inherited from the superclass.
this._styles = this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
this._styles =
this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
}
/** @nocollapse */
private static _getUniqueStyles(): CSSResult[] {

@@ -95,5 +111,5 @@ // Take care not to call `this.styles` multiple times since this generates

const userStyles = this.styles;
let styles: CSSResult[] = [];
const styles: CSSResult[] = [];
if (Array.isArray(userStyles)) {
styles = flattenStyles(userStyles);
const flatStyles = flattenStyles(userStyles);
// As a performance optimization to avoid duplicated styling that can

@@ -104,3 +120,3 @@ // occur especially when composing via subclassing, de-duplicate styles

// important that last added styles override previous styles.
const styleSet = styles.reduceRight((set, s) => {
const styleSet = flatStyles.reduceRight((set, s) => {
set.add(s);

@@ -113,3 +129,3 @@ // on IE set.add does not return the set.

} else if (userStyles) {
styles = [userStyles];
styles.push(userStyles);
}

@@ -151,3 +167,3 @@ return styles;

protected createRenderRoot(): Element|ShadowRoot {
return this.attachShadow({mode : 'open'});
return this.attachShadow({mode: 'open'});
}

@@ -207,4 +223,6 @@

(this.constructor as typeof LitElement)
.render(templateResult, this.renderRoot!,
{scopeName : this.localName!, eventContext : this});
.render(
templateResult,
this.renderRoot!,
{scopeName: this.localName!, eventContext: this});
}

@@ -229,3 +247,4 @@ // When native Shadow DOM is used but adoptedStyles are not supported,

*/
protected render(): TemplateResult|void {}
protected render(): TemplateResult|void {
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc