Skip to content
Merged
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
25 changes: 3 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,10 @@ import { effect, Signal, signal } from "@preact/signals-core";
import { reconcile } from "./reconciler/index";
import { ShadowCache } from "./reconciler/utils";
import type { CustomEvents, ForbiddenHTMLProperties, ReadonlyKeys, ShadowElement } from "./types";
import {
connectedCallback,
disconnectedCallback,
parentsCacheSymbol,
PlusnewErrorEvent,
active,
addEventListener,
removeEventListener,
} from "./utils";
import { parentsCacheSymbol, PlusnewErrorEvent, active } from "./utils";

export type { ShadowElement } from "./types";
export { active, connectedCallback, disconnectedCallback } from "./utils";
export { active, WebComponent } from "./utils";

export function mount(render: () => ShadowElement, parent: HTMLElement): () => void {
const shadowResult: ShadowCache = new ShadowCache(false);
Expand All @@ -38,7 +30,7 @@ export function mount(render: () => ShadowElement, parent: HTMLElement): () => v
};
}

export function createComponent<T extends HTMLElement & { render: (this: T) => ShadowElement }>(
export function createComponent<T extends HTMLElement>(
name: string,
Component: { new (): T },
): {
Expand All @@ -60,17 +52,6 @@ export function createComponent<T extends HTMLElement & { render: (this: T) => S
},
): T;
} {
if ("connectedCallback" in Component.prototype === false) {
Component.prototype.connectedCallback = connectedCallback;
}

if ("disconnectedCallback" in Component.prototype === false) {
Component.prototype.disconnectedCallback = disconnectedCallback;
}

Component.prototype.addEventListener = addEventListener;
Component.prototype.removeEventListener = removeEventListener;

customElements.define(name, Component as any);

return name as any;
Expand Down
155 changes: 78 additions & 77 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,101 +33,102 @@ export function dispatchError(element: Element, error: unknown) {
const disconnect = Symbol("disconnect");
const shadowCache = Symbol("shadowCache");
const eventListenerSymbol = Symbol("eventListner");

export const parentsCacheSymbol = Symbol("parentsCache");

export function connectedCallback(
this: HTMLElement & { render: () => ShadowElement },
opt?: { shadowRootInit?: Partial<ShadowRootInit> },
): ShadowRoot {
let shadowRoot: null | ShadowRoot = null;
if (this.shadowRoot === null) {
shadowRoot = this.attachShadow({ mode: "open", ...opt?.shadowRootInit });

(this as any)[parentsCacheSymbol] = new Map();
(this as any)[shadowCache] = new ShadowCache(false);
} else {
shadowRoot = this.shadowRoot;
}
export abstract class WebComponent extends HTMLElement {
abstract render(): ShadowElement;

(this as any)[disconnect] = effect(() => {
batch(() => {
const previousActiveElement = active.parentElement;
let result: ShadowElement;
try {
active.parentElement = this;
result = this.render();
active.parentElement = previousActiveElement;
} catch (error) {
active.parentElement = previousActiveElement;
untracked(() => dispatchError(this, error));

return;
}
connectedCallback(this: WebComponent, opt?: { shadowRootInit?: Partial<ShadowRootInit> }) {
let shadowRoot: null | ShadowRoot = null;
if (this.shadowRoot === null) {
shadowRoot = this.attachShadow({ mode: "open", ...opt?.shadowRootInit });

reconcile({
parentElement: this.shadowRoot as ShadowRoot,
previousSibling: null,
shadowCache: (this as any)[shadowCache],
shadowElement: result,
(this as any)[parentsCacheSymbol] = new Map();
(this as any)[shadowCache] = new ShadowCache(false);
} else {
shadowRoot = this.shadowRoot;
}

(this as any)[disconnect] = effect(() => {
batch(() => {
const previousActiveElement = active.parentElement;
let result: ShadowElement;
try {
active.parentElement = this;
result = this.render();
active.parentElement = previousActiveElement;
} catch (error) {
active.parentElement = previousActiveElement;
untracked(() => dispatchError(this, error));

return;
}

reconcile({
parentElement: this.shadowRoot as ShadowRoot,
previousSibling: null,
shadowCache: (this as any)[shadowCache],
shadowElement: result,
});
});
});
});

return shadowRoot;
}

export function disconnectedCallback(this: HTMLElement & { render: () => ShadowElement }) {
(this as any)[disconnect]();
(this as any)[parentsCacheSymbol].clear();
(this as any)[shadowCache].unmount();
}

export function addEventListener(
this: HTMLElement,
eventName: string,
listener: (event: Event) => unknown,
options?: boolean | AddEventListenerOptions,
) {
if (eventListenerSymbol in this === false) {
(this as any)[eventListenerSymbol] = {};
return shadowRoot;
}
if (eventName in (this as any)[eventListenerSymbol] === false) {
(this as any)[eventListenerSymbol][eventName] = new WeakMap();

disconnectedCallback(this: WebComponent) {
if (disconnect in this) {
(this as any)[disconnect]();
}
if (parentsCacheSymbol in this) {
(this as any)[parentsCacheSymbol].clear();
}
if (shadowCache in this) {
(this as any)[shadowCache].unmount();
}
}

const listenerOverwrite = (evt: Event) => {
if (typeof options === "object" && options !== null && options?.once === true) {
(this as any)[eventListenerSymbol]?.[eventName]?.delete(listener);
addEventListener(
eventName: string,
listener: (event: Event) => unknown,
options?: boolean | AddEventListenerOptions,
) {
if (eventListenerSymbol in this === false) {
(this as any)[eventListenerSymbol] = {};
}
if (eventName in (this as any)[eventListenerSymbol] === false) {
(this as any)[eventListenerSymbol][eventName] = new WeakMap();
}

const result = listener(evt);
const listenerOverwrite = (evt: Event) => {
if (typeof options === "object" && options !== null && options?.once === true) {
(this as any)[eventListenerSymbol]?.[eventName]?.delete(listener);
}

if (result instanceof Promise && active.eventPromises !== null) {
active.eventPromises.push(result);
}
};
const result = listener(evt);

(this as any)[eventListenerSymbol][eventName].set(listener, listenerOverwrite);
if (result instanceof Promise && active.eventPromises !== null) {
active.eventPromises.push(result);
}
};

HTMLElement.prototype.addEventListener.call(this, eventName, listenerOverwrite, options);
}
(this as any)[eventListenerSymbol][eventName].set(listener, listenerOverwrite);

export function removeEventListener(
this: HTMLElement,
eventName: string,
listener: (event: Event) => void,
) {
if (
eventListenerSymbol in this === true &&
eventName in (this as any)[eventListenerSymbol] === true
) {
const listenerOverwrite = (this as any)[eventListenerSymbol][eventName].get(listener);
super.addEventListener(eventName, listenerOverwrite, options);
}

if (listenerOverwrite !== undefined) {
(this as any)[eventListenerSymbol][eventName].delete(listener);
removeEventListener(this: HTMLElement, eventName: string, listener: (event: Event) => void) {
if (
eventListenerSymbol in this === true &&
eventName in (this as any)[eventListenerSymbol] === true
) {
const listenerOverwrite = (this as any)[eventListenerSymbol][eventName].get(listener);

HTMLElement.prototype.removeEventListener.call(this, eventName, listenerOverwrite);
if (listenerOverwrite !== undefined) {
(this as any)[eventListenerSymbol][eventName].delete(listener);

super.removeEventListener(eventName, listenerOverwrite);
}
}
}
}
4 changes: 2 additions & 2 deletions test/async.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from "@esm-bundle/chai";
import { createComponent, mount, dispatchEvent } from "@plusnew/webcomponent";
import { createComponent, mount, dispatchEvent, WebComponent } from "@plusnew/webcomponent";
import { signal } from "@preact/signals-core";

describe("webcomponent", () => {
Expand All @@ -19,7 +19,7 @@ describe("webcomponent", () => {

const Component = createComponent(
"test-async-dispatch",
class Component extends HTMLElement {
class Component extends WebComponent {
onfoo: (evt: CustomEvent<null>) => void;

#loading = signal(false);
Expand Down
16 changes: 8 additions & 8 deletions test/base.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from "@esm-bundle/chai";
import { createComponent, mount, prop } from "@plusnew/webcomponent";
import { createComponent, mount, prop, WebComponent } from "@plusnew/webcomponent";
import type { Signal } from "@preact/signals-core";
import { signal } from "@preact/signals-core";

Expand All @@ -18,7 +18,7 @@ describe("webcomponent", () => {
it("creates basic component and updating its props", () => {
const Component = createComponent(
"test-base",
class Component extends HTMLElement {
class Component extends WebComponent {
@prop() accessor foo: string;

#baz = signal("baz");
Expand Down Expand Up @@ -56,7 +56,7 @@ describe("webcomponent", () => {
it("crates array based on given number", () => {
const Component = createComponent(
"test-array",
class Component extends HTMLElement {
class Component extends WebComponent {
@prop() accessor amount: number;

render() {
Expand Down Expand Up @@ -94,7 +94,7 @@ describe("webcomponent", () => {
it("crates element if needed", () => {
const Component = createComponent(
"test-placeholder",
class Component extends HTMLElement {
class Component extends WebComponent {
@prop() accessor show: boolean;

render() {
Expand Down Expand Up @@ -135,7 +135,7 @@ describe("webcomponent", () => {

const Component = createComponent(
"test-container",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
containerRenderCount++;
return <NestedComponent />;
Expand All @@ -145,7 +145,7 @@ describe("webcomponent", () => {

const NestedComponent = createComponent(
"test-nest",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
nestedRenderCount++;
return `${foo.value}`;
Expand Down Expand Up @@ -180,7 +180,7 @@ describe("webcomponent", () => {

const NestedComponent = createComponent(
"test-counter-constructor",
class Component extends HTMLElement {
class Component extends WebComponent {
#counter: Signal<number>;
constructor() {
super();
Expand All @@ -206,7 +206,7 @@ describe("webcomponent", () => {

const Component = createComponent(
"test-container-rerender",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
containerRenderCounter += 1;
return <NestedComponent />;
Expand Down
12 changes: 6 additions & 6 deletions test/context.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { expect } from "@esm-bundle/chai";
import { mount, createComponent, findParent } from "@plusnew/webcomponent";
import { mount, createComponent, findParent, WebComponent } from "@plusnew/webcomponent";
import { signal } from "@preact/signals-core";

const Provider = createComponent(
"test-provider",
class Component extends HTMLElement {
class Component extends WebComponent {
readonly foo = signal("bar");

render() {
Expand All @@ -15,7 +15,7 @@ const Provider = createComponent(

const Consumer = createComponent(
"test-consumer",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
try {
return findParent(Provider).foo.value;
Expand Down Expand Up @@ -71,7 +71,7 @@ describe("webcomponent", () => {
it("finds context inline", () => {
const Component = createComponent(
"test-inline",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
return <Provider>{findParent(Provider).foo.value}</Provider>;
}
Expand All @@ -97,7 +97,7 @@ describe("webcomponent", () => {
it("finds context in event", () => {
const Component = createComponent(
"test-event",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
return (
<Provider>
Expand Down Expand Up @@ -136,7 +136,7 @@ describe("webcomponent", () => {
it("no context", () => {
const Injection = createComponent(
"test-injection",
class Component extends HTMLElement {
class Component extends WebComponent {
render() {
return (
<Provider>
Expand Down
6 changes: 3 additions & 3 deletions test/error.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from "@esm-bundle/chai";
import { createComponent, mount } from "@plusnew/webcomponent";
import { createComponent, mount, WebComponent } from "@plusnew/webcomponent";
import { signal } from "@preact/signals-core";

function error(): never {
Expand All @@ -21,7 +21,7 @@ describe("webcomponent", () => {
it("creates broken component and should display error", () => {
const Component = createComponent(
"test-broken",
class Component extends HTMLElement {
class Component extends WebComponent {
#hasError = signal(false);
render() {
return this.#hasError.value ? (
Expand Down Expand Up @@ -55,7 +55,7 @@ describe("webcomponent", () => {

// const Component = webcomponent(
// "test-later-broken",
// class Component extends HTMLElement {
// class Component extends WebComponent {
// render() {
// if (foo.value === true) {
// return "good";
Expand Down
Loading
Loading