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
64 changes: 23 additions & 41 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
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 { parentsCacheSymbol, PlusnewErrorEvent, active } from "./utils";
import type { CustomEvents, PropertyDescriptor, ShadowElement } from "./types";
import { parentsCacheSymbol, active } from "./utils";

export type { ShadowElement } from "./types";
export { active, WebComponent } from "./utils";
export type { ShadowElement, PropertyDescriptor } from "./types";
export { active, WebComponent, type BasePropsType, type PropType } from "./utils";

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

export function createComponent<T extends HTMLElement>(
export function define(name: string): ClassDecorator {
return (Component) => {
customElements.define(name, Component as any);

return Component;
};
}

export function createComponent<T extends new (...args: any[]) => HTMLElement>(
name: string,
Component: { new (): T },
): {
new (
properties: Omit<
{ [K in keyof T]?: T[K] } & {
[
K in keyof T as undefined extends T[K] ? never : K extends keyof HTMLElement ? never : K
]-?: T[K];
},
| ReadonlyKeys<T>
| ForbiddenHTMLProperties
| "render"
| "connectedCallback"
| "disconnectedCallback"
> & {
children?: ShadowElement;
onplusnewerror?: (evt: PlusnewErrorEvent) => void;
},
): T;
} {
Component: T,
): T {
customElements.define(name, Component as any);

return name as any;
Expand Down Expand Up @@ -141,24 +131,16 @@ export function dispatchEvent<T extends HTMLElement, U extends keyof CustomEvent
return eventPromises;
}

export function prop() {
return <T, U>(
decoratorTarget: ClassAccessorDecoratorTarget<T, U>,
accessor: ClassAccessorDecoratorContext<T, U>,
): ClassAccessorDecoratorResult<T, U> => {
export function prop<T>(): () => PropertyDescriptor<T> {
return () => {
const signalValue = signal<T>() as Signal<T>;

return {
set: function (value) {
if (accessor.access.has(this)) {
(decoratorTarget.get.call(this) as Signal<U>).value = value;
} else {
decoratorTarget.set.call(this, signal(value) as U);
}
},
get: function () {
return (decoratorTarget.get.call(this) as Signal<U>).value;
get: () => {
return signalValue.value;
},
init(value) {
return signal(value) as U;
set: (value) => {
signalValue.value = value;
},
};
};
Expand Down
14 changes: 13 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,24 @@ export function Fragment(props: { children: ShadowElement }) {
return props.children;
}

export interface PropertyDescriptor<T> {
configurable?: boolean;
enumerable?: boolean;
value?: T;
writable?: boolean;
get?(): T;
set?(v: T): void;
}

export type PropertyDescriptorType<T extends PropertyDescriptor<any>> =
T extends PropertyDescriptor<infer R> ? R : never;

// type Expect<T extends true> = T;

type IsEqual<CheckA, CheckB, Then, Else> =
(<T>() => T extends CheckA ? 1 : 2) extends <T>() => T extends CheckB ? 1 : 2 ? Then : Else;

export type ReadonlyKeys<T> = {
type ReadonlyKeys<T> = {
[P in keyof T]-?: IsEqual<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P>;
}[keyof T];

Expand Down
193 changes: 119 additions & 74 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { batch, effect, untracked } from "@preact/signals-core";
import { ShadowCache } from "./reconciler/utils";
import type { ShadowElement } from "./types";
import type {
ForbiddenHTMLProperties,
PropertyDescriptor,
PropertyDescriptorType,
ShadowElement,
} from "./types";
import { reconcile } from "./reconciler";

const ERROR = "plusnewerror";
Expand Down Expand Up @@ -35,100 +40,140 @@ const shadowCache = Symbol("shadowCache");
const eventListenerSymbol = Symbol("eventListner");
export const parentsCacheSymbol = Symbol("parentsCache");

export abstract class WebComponent extends HTMLElement {
abstract render(): ShadowElement;
export type BasePropsType = Omit<Partial<HTMLElement>, ForbiddenHTMLProperties | "children"> & {
children?: ShadowElement;
};

export type PropType<T extends { [key: string]: () => PropertyDescriptor<any> }> = {
[
Prop in keyof T as undefined extends PropertyDescriptorType<ReturnType<T[Prop]>> ? Prop : never
]?: Exclude<PropertyDescriptorType<ReturnType<T[Prop]>>, undefined>;
} & {
[
Prop in keyof T as undefined extends PropertyDescriptorType<ReturnType<T[Prop]>> ? never : Prop
]: PropertyDescriptorType<ReturnType<T[Prop]>>;
};

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

(this as any)[parentsCacheSymbol] = new Map();
(this as any)[shadowCache] = new ShadowCache(false);
} else {
shadowRoot = this.shadowRoot;
export function WebComponent<T extends { [key: string]: () => PropertyDescriptor<any> } = {}>(
props?: T,
): abstract new (props: PropType<T> & BasePropsType) => PropType<T> & IComponent {
abstract class Component extends HTMLElement implements IComponent {
constructor(_props: PropType<T> & BasePropsType) {
super();
if (props !== undefined) {
Object.defineProperties(
this,
Object.fromEntries(
Object.entries(props).map(([key, propertyDescriptorFactory]) => [
key,
propertyDescriptorFactory(),
]),
),
);
}
}

(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;
}
abstract render(): ShadowElement;

reconcile({
parentElement: this.shadowRoot as ShadowRoot,
previousSibling: null,
shadowCache: (this as any)[shadowCache],
shadowElement: result,
connectedCallback(opt?: { shadowRootInit?: Partial<ShadowRootInit> }) {
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;
}

(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;
}

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

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();
disconnectedCallback() {
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);
}
};

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

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);

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

super.removeEventListener(eventName, listenerOverwrite);
}
}
}
}

return Component as any;
}
Loading
Loading