Socket
Socket
Sign inDemoInstall

lit-element

Package Overview
Dependencies
Maintainers
5
Versions
83
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lit-element - npm Package Compare versions

Comparing version 1.0.0 to 2.0.0-rc.1

CHANGELOG.md

213

lit-element.js

@@ -1,71 +0,158 @@

import { html, render as litRender } from '../lit-html/lit-html.js'
export default class LitElement extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: "open"});
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import { TemplateResult } from 'lit-html';
import { render } from 'lit-html/lib/shady-render';
import { UpdatingElement } from './lib/updating-element.js';
export * from './lib/updating-element.js';
export * from './lib/decorators.js';
export { html, svg, TemplateResult, SVGTemplateResult } from 'lit-html/lit-html';
import { supportsAdoptingStyleSheets } from './lib/css-tag.js';
export * from './lib/css-tag.js';
export class LitElement extends UpdatingElement {
/**
* Array of styles to apply to the element. The styles should be defined
* using the `css` tag function.
*/
static get styles() { return []; }
static get _uniqueStyles() {
if (this._styles === undefined) {
const styles = this.styles;
// As a performance optimization to avoid duplicated styling that can
// occur especially when composing via subclassing, de-duplicate styles
// preserving the last item in the list. The last item is kept to
// try to preserve cascade order with the assumption that it's most
// important that last added styles override previous styles.
const styleSet = styles.reduceRight((set, s) => {
set.add(s);
// on IE set.add does not return the set.
return set;
}, new Set());
// Array.form does not work on Set in IE
this._styles = [];
styleSet.forEach((v) => this._styles.unshift(v));
}
return this._styles;
}
connectedCallback() {
const props = this.constructor.properties;
for(let prop in props) {
if(typeof props[prop] === 'object') {
this._makeComplexGetterSetter(prop, props[prop])
} else {
this._makeGetterSetter(prop, props[prop])
}
/**
* Performs element initialization. By default this calls `createRenderRoot`
* to create the element `renderRoot` node and captures any pre-set values for
* registered properties.
*/
initialize() {
super.initialize();
this.renderRoot = this.createRenderRoot();
// Note, if renderRoot is not a shadowRoot, styles would/could apply to the
// element's getRootNode(). While this could be done, we're choosing not to
// support this now since it would require different logic around de-duping.
if (window.ShadowRoot && this.renderRoot instanceof window.ShadowRoot) {
this.adoptStyles();
}
litRender(this.render(), this.shadowRoot);
}
_makeGetterSetter(prop, val) {
if(!this.__data)
this.__data = {};
Object.defineProperty(this, prop, {
get() {
return this.__data[prop]
},
set(val) {
this.__data[prop] = val;
this._propertiesChanged()
}
})
this[prop] = undefined;
/**
* Returns the node into which the element should render and by default
* creates and returns an open shadowRoot. Implement to customize where the
* element's DOM is rendered. For example, to render into the element's
* childNodes, return `this`.
* @returns {Element|DocumentFragment} Returns a node into which to render.
*/
createRenderRoot() {
return this.attachShadow({ mode: 'open' });
}
_makeComplexGetterSetter(prop, info) {
if(!this.__data)
this.__data = {};
Object.defineProperty(this, prop, {
get() {
if(info.reflectToAttribute) {
if(info.type === Object || info.type === Array)
console.warn('Rich Data shouldn\'t be set as attribte!')
return this.getAttribute(prop);
} else return this.__data[prop];
},
set(val) {
if(info.reflectToAttribute) {
if(info.type === Object || info.type === Array)
console.warn('Rich Data shouldn\'t be set as attribte!')
this.setAttribute(prop, val);
} else this.__data[prop] = val;
this._propertiesChanged();
}
});
if(info.value) {
typeof info.value === 'function'
? this[prop] = info.value()
: this[prop] = info.value;
/**
* Applies styling to the element shadowRoot using the `static get styles`
* property. Styling will apply using `shadowRoot.adoptedStyleSheets` where
* available and will fallback otherwise. When Shadow DOM is polyfilled,
* ShadyCSS scopes styles and adds them to the document. When Shadow DOM
* is available but `adoptedStyleSheets` is not, styles are appended to the
* end of the `shadowRoot` to [mimic spec
* behavior](https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets).
*/
adoptStyles() {
const styles = this.constructor._uniqueStyles;
if (styles.length === 0) {
return;
}
// There are three separate cases here based on Shadow DOM support.
// (1) shadowRoot polyfilled: use ShadyCSS
// (2) shadowRoot.adoptedStyleSheets available: use it.
// (3) shadowRoot.adoptedStyleSheets polyfilled: append styles after
// rendering
if (window.ShadyCSS !== undefined && !window.ShadyCSS.nativeShadow) {
window.ShadyCSS.ScopingShim.prepareAdoptedCssText(styles.map((s) => s.cssText), this.localName);
}
else if (supportsAdoptingStyleSheets) {
this.renderRoot.adoptedStyleSheets =
styles.map((s) => s.styleSheet);
}
else {
// This must be done after rendering so the actual style insertion is done
// in `update`.
this._needsShimAdoptedStyleSheets = true;
}
}
_propertiesChanged() {
litRender(this.render(), this.shadowRoot)
connectedCallback() {
super.connectedCallback();
// Note, first update/render handles styleElement so we only call this if
// connected after first update.
if (this.hasUpdated && window.ShadyCSS !== undefined) {
window.ShadyCSS.styleElement(this);
}
}
render() {
return html`Render Function not defined`
/**
* Updates the element. This method reflects property values to attributes
* and calls `render` to render DOM via lit-html. Setting properties inside
* this method will *not* trigger another update.
* * @param _changedProperties Map of changed properties with old values
*/
update(changedProperties) {
super.update(changedProperties);
const templateResult = this.render();
if (templateResult instanceof TemplateResult) {
this.constructor
.render(templateResult, this.renderRoot, { scopeName: this.localName, eventContext: this });
}
// When native Shadow DOM is used but adoptedStyles are not supported,
// insert styling after rendering to ensure adoptedStyles have highest
// priority.
if (this._needsShimAdoptedStyleSheets) {
this._needsShimAdoptedStyleSheets = false;
this.constructor._uniqueStyles.forEach((s) => {
const style = document.createElement('style');
style.textContent = s.cssText;
this.renderRoot.appendChild(style);
});
}
}
}
/**
* Invoked on each update to perform rendering tasks. This method must return
* a lit-html TemplateResult. Setting properties inside this method will *not*
* trigger the element to update.
*/
render() { }
}
/**
* Ensure this class is marked as `finalized` as an optimization ensuring
* it will not needlessly try to `finalize`.
*/
LitElement.finalized = true;
/**
* Render method used to render the lit-html TemplateResult to the element's
* DOM.
* @param {TemplateResult} Template to render.
* @param {Element|DocumentFragment} Node into which to render.
* @param {String} Element name.
* @nocollapse
*/
LitElement.render = render;
//# sourceMappingURL=lit-element.js.map
{
"name": "lit-element",
"version": "2.0.0-rc.1",
"description": "Polymer based lit-html custom element",
"license": "BSD-3-Clause",
"repository": "Polymer/lit-element",
"main": "lit-element.js",
"module": "lit-element.js",
"directories": {
"test": "test"
},
"files": [
"/lib/",
"/src/",
"!/src/demo/",
"!/src/test/",
"/lit-element.d.ts",
"/lit-element.d.ts.map",
"/lit-element.js",
"/lit-element.js.map"
],
"scripts": {
"build": "tsc",
"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",
"test": "npm run build && npm run build:babel-test && wct",
"checksize": "rollup -c ; rm lit-element.bundled.js",
"format": "find src test | grep '\\.js$\\|\\.ts$' | xargs clang-format --style=file -i",
"lint": "tslint --project ./",
"prepublishOnly": "npm run build",
"regen-package-lock": "rm -rf node_modules package-lock.json; npm install"
},
"author": "The Polymer Authors",
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/plugin-proposal-class-properties": "^7.2.3",
"@babel/plugin-proposal-decorators": "^7.2.3",
"@babel/plugin-transform-typescript": "^7.2.0",
"@types/chai": "^4.0.1",
"@types/mocha": "^5.2.4",
"@webcomponents/shadycss": "^1.8.0",
"@webcomponents/webcomponentsjs": "^2.2.3",
"chai": "^4.0.2",
"mocha": "^5.0.5",
"rollup": "^0.64.1",
"rollup-plugin-filesize": "^4.0.1",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-terser": "^1.0.1",
"tslint": "^5.12.0",
"typedoc": "^0.8.0",
"typescript": "^3.2.2",
"uglify-es": "^3.3.9",
"wct-mocha": "^1.0.0",
"web-component-tester": "^6.9.2"
},
"typings": "lit-element.d.ts",
"dependencies": {
"lit-html": "^0.6.0"
"lit-html": "^1.0.0-rc.2"
},
"name": "lit-element",
"version": "1.0.0",
"description": "Implements lit-html via a LitElement class. Made for custom Elements.",
"main": "lit-element.js",
"repository": "https://github.com/DiiLord/lit-element.git",
"author": "DiiLord <d.drodt@gmx.de>",
"license": "MIT"
"publishConfig": {
"access": "public"
}
}

@@ -1,41 +0,289 @@

# lit-element
Implements [lit-html](https://github.com/PolymerLabs/lit-html) via a LitElement class. Made for custom Elements.
# LitElement
## Default Usage
[![Published on npm](https://img.shields.io/npm/v/@polymer/lit-element.svg)](https://www.npmjs.com/package/lit-element)
[![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://www.webcomponents.org/element/lit-element)
[![Mentioned in Awesome lit-html](https://awesome.re/mentioned-badge.svg)](https://github.com/web-padawan/awesome-lit-html)
```javascript
// import html from lit-html
import {html} from '../node-modules/lit-html/lit-html.js'
## A simple base class for creating fast, lightweight web components
// import lit-element
import LitElement from './lit-element.js'
LitElement uses [lit-html](https://github.com/Polymer/lit-html) to render into the
element's [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM)
and adds API to help manage element properties and attributes. LitElement reacts to changes in properties
and renders declaratively using `lit-html`. See the [lit-html guide](https://lit-html.polymer-project.org/guide)
for additional information on how to create templates for lit-element.
// define Custom Element
* **Setup properties:** LitElement supports observable properties that cause the element to update.
These properties can be declared in a few ways:
* 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.
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: {...} }`.
Property options include:
* `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/rzhofu81/), [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 @polymer/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/@polymer/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 '@polymer/lit-element';
class MyElement extends LitElement {
static get properties() {
return {
mood: {type: String}
};
}
constructor() {
super();
this.mood = 'happy';
}
render() {
return html`<style> .mood { color: green; } </style>
Web Components are <span class="mood">${this.mood}</span>!`;
}
}
customElements.define('my-element', MyElement);
</script>
<my-element mood="happy"></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).
```ts
import {LitElement, html, property} from '@polymer/lit-element';
class MyElement extends LitElement {
// define properties similiar to Polymer 2/3
static get properties() {
return {
title: String,
body: {
type: String,
value: 'That is a cool LitElement'
}
// Public property API that triggers re-render (synced with attributes)
@property()
foo = 'foo';
@property({type: Number})
whales = 5;
constructor() {
super();
this.addEventListener('click', async (e) => {
this.whales++;
await this.updateComplete;
this.dispatchEvent(new CustomEvent('whales', {detail: {whales: this.whales}}))
});
}
// Render method should return a `TemplateResult` using the provided lit-html `html` tag function
render() {
return html`
<style>
:host {
display: block;
}
}
// define your template in render
render() {
this.title = 'This is lit';
return html`
<h1>${this.title}</h1>
<p>${this.body}</h1>
`;
}
:host([hidden]) {
display: none;
}
</style>
<h4>Foo: ${this.foo}</h4>
<div>whales: ${'🐳'.repeat(this.whales)}</div>
<slot></slot>
`;
}
}
customElements.define('my-element', MyElement);
```
## Notes
```html
<my-element whales="5">hi</my-element>
```
- This Element does not use Polymer, just Polymer-like syntax for properties.
- Currently only `reflectToAttribute` and `value` are supported for properties.
## Supported Browsers
The last 2 versions of all modern browsers are supported, including
Chrome, Safari, Opera, Firefox, Edge. In addition, Internet Explorer 11 is also supported.
## Known Issues
* 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).
SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc