Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move style gathering from class finalization to initialization #866

Merged
merged 5 commits into from
Jan 17, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ dist: xenial
node_js: '10'
addons:
firefox: latest
apt:
sources:
- google-chrome
packages:
- google-chrome-stable
chrome: stable
cache:
directories:
- node_modules
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Fixed
* Properties annotated with the `eventOptions` decorator will now survive property renaming optimizations when used with tsickle and Closure JS Compiler.
* Moved style gathering from `finalize` to `initialize` to be more lazy, and create stylesheets on the first instance initializing [#866](https://github.com/Polymer/lit-element/pull/866).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think it makes sense to add statis getStyles() mention to "Added"?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, will do!


<!-- ### Changed -->

Expand Down
3 changes: 2 additions & 1 deletion src/lib/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ export function eventOptions(options: AddEventListenerOptions) {
* this property should be annotated as `NodeListOf<HTMLElement>`.
*
*/
export function queryAssignedNodes(slotName: string = '', flatten: boolean = false) {
export function queryAssignedNodes(
slotName: string = '', flatten: boolean = false) {
return (protoOrDescriptor: Object|ClassElement,
// tslint:disable-next-line:no-any decorator
name?: PropertyKey): any => {
Expand Down
3 changes: 2 additions & 1 deletion src/lib/updating-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ type AttributeMap = Map<string, PropertyKey>;
* interface corresponding to the declared element properties.
*/
// tslint:disable-next-line:no-any
export type PropertyValues<T = any> = keyof T extends PropertyKey ? Map<keyof T, unknown> : never;
export type PropertyValues<T = any> =
keyof T extends PropertyKey ? Map<keyof T, unknown>: never;

export const defaultConverter: ComplexAttributeConverter = {

Expand Down
41 changes: 23 additions & 18 deletions src/lit-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,29 +63,32 @@ export class LitElement extends UpdatingElement {

private static _styles: CSSResult[]|undefined;

/** @nocollapse */
protected static finalize() {
// The Closure JS Compiler does not always preserve the correct "this"
// when calling static super methods (b/137460243), so explicitly bind.
super.finalize.call(this);
// Prepare styling that is stamped at first render time. Styling
// is built from user provided `styles` or is inherited from the superclass.
this._styles =
this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
/**
* Return the array of styles to apply to the element.
* Override this method to integrate into a style management system.
*
* @nocollapse
*/
static getStyles(): CSSResult|CSSResultArray|undefined {
return this.styles;
}

/** @nocollapse */
private static _getUniqueStyles(): CSSResult[] {
// Take care not to call `this.styles` multiple times since this generates
// new CSSResults each time.
private static _getUniqueStyles() {
// Only gather styles once per class
if (this.hasOwnProperty(JSCompiler_renameProperty('_styles', this))) {
return;
}
// Take care not to call `this.getStyles()` multiple times since this
// generates new CSSResults each time.
// TODO(sorvell): Since we do not cache CSSResults by input, any
// shared styles will generate new stylesheet objects, which is wasteful.
// This should be addressed when a browser ships constructable
// stylesheets.
const userStyles = this.styles!;
if (Array.isArray(userStyles)) {
const userStyles = this.getStyles();
if (userStyles === undefined) {
this._styles = [];
} else if (Array.isArray(userStyles)) {
// De-duplicate styles preserving the _last_ instance in the set.
// This is a performance optimization to avoid duplicated styles that can
// occur especially when composing via subclassing.
Expand All @@ -104,9 +107,10 @@ export class LitElement extends UpdatingElement {
const set = addStyles(userStyles, new Set<CSSResult>());
const styles: CSSResult[] = [];
set.forEach((v) => styles.unshift(v));
return styles;
this._styles = styles;
} else {
this._styles = [userStyles];
}
return [userStyles];
}

private _needsShimAdoptedStyleSheets?: boolean;
Expand All @@ -124,6 +128,7 @@ export class LitElement extends UpdatingElement {
*/
protected initialize() {
super.initialize();
(this.constructor as typeof LitElement)._getUniqueStyles();
(this as {renderRoot: Element | DocumentFragment}).renderRoot =
this.createRenderRoot();
// Note, if renderRoot is not a shadowRoot, styles would/could apply to the
Expand Down
3 changes: 2 additions & 1 deletion src/test/lib/decorators_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {eventOptions, property} from '../../lib/decorators.js';
import {customElement, html, LitElement, PropertyValues, query, queryAll, queryAssignedNodes} from '../../lit-element.js';
import {generateElementName} from '../test-helpers.js';

const flush = window.ShadyDOM && window.ShadyDOM.flush ? window.ShadyDOM.flush : () => {};
const flush =
window.ShadyDOM && window.ShadyDOM.flush ? window.ShadyDOM.flush : () => {};

// tslint:disable:no-any ok in tests

Expand Down
34 changes: 34 additions & 0 deletions src/test/lit-element_styling_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,40 @@ suite('Static get styles', () => {
'4px');
});

test('element class only gathers styles once', async () => {
const base = generateElementName();
let styleCounter = 0;
customElements.define(base, class extends LitElement {
static get styles() {
styleCounter++;
return css`:host {
border: 10px solid black;
}`;
}
render() {
return htmlWithStyles`<div>styled</div>`;
}
});
const el1 = document.createElement(base);
const el2 = document.createElement(base);
container.appendChild(el1);
container.appendChild(el2);
await Promise.all([
(el1 as LitElement).updateComplete,
(el2 as LitElement).updateComplete
]);
assert.equal(
getComputedStyle(el1).getPropertyValue('border-top-width').trim(),
'10px',
'el1 styled correctly');
assert.equal(
getComputedStyle(el2).getPropertyValue('border-top-width').trim(),
'10px',
'el2 styled correctly');
assert.equal(
styleCounter, 1, 'styles property should only be accessed once');
});

test(
'`CSSResult` allows for String type coercion via toString()',
async () => {
Expand Down