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

Clear component contents before first render #445

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions src/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,22 @@ interface Options<P> {
function makeComponent(render: RenderFunction): Creator {
class Scheduler<P extends object> extends BaseScheduler<P, HTMLElement, Renderer<P>, Component<P>> {
frag: DocumentFragment | HTMLElement;
isFirstRender: boolean;

constructor(renderer: Renderer<P>, frag: DocumentFragment, host: HTMLElement);
constructor(renderer: Renderer<P>, host: HTMLElement);
constructor(renderer: Renderer<P>, frag: DocumentFragment | HTMLElement, host?: HTMLElement) {
super(renderer, (host || frag) as Component<P>);
this.frag = frag;
this.isFirstRender = true;
}

commit(result: unknown): void {
// Clear component's content before first render
// Needed by lit-html v2. See https://lit.dev/docs/releases/upgrade/#lit-html
if (this.isFirstRender) clearContent(this.frag);
render(result, this.frag);
this.isFirstRender = false;
}
}

Expand Down Expand Up @@ -150,4 +156,14 @@ function makeComponent(render: RenderFunction): Creator {
return component;
}

// Clear content of element or fragment
// Same as element.innerHTML = '', but works on fragments as well
function clearContent(frag: DocumentFragment | HTMLElement) {
if (frag.replaceChildren) {
frag.replaceChildren() // New API
} else {
while (frag.firstChild) frag.removeChild(frag.lastChild!); // Fallback for old browsers
}
}

export { makeComponent, Component, Constructor as ComponentConstructor, Creator as ComponentCreator };
15 changes: 15 additions & 0 deletions test/first-render.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { component, html } from '../src/haunted.js';
import { fixture, expect } from '@open-wc/testing';

describe('First Render', () => {
it('should clear content', async () => {
customElements.define('no-shadow-test', component(() => {
return html`Template Content`;
}, HTMLElement, {useShadowDOM: false}));

// This "Loading..." text should be cleared after first render
const el = await fixture<HTMLElement>(html`<no-shadow-test>Loading...</no-shadow-test>`);

expect(el.innerText).to.equal('Template Content');
});
})