Skip to content
Draft
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
5 changes: 5 additions & 0 deletions src/component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GenericRenderer, RenderFunction, RenderResult } from "./core";
import { BaseScheduler } from "./scheduler";
import { reflectingSymbol } from "./symbols";
import { sheets } from "./util";

const toCamelCase = (val = ""): string =>
Expand Down Expand Up @@ -143,7 +144,11 @@ function makeComponent(render: RenderFunction): Creator {
if (oldValue === newValue) {
return;
}
if ((this as any)[reflectingSymbol]) {
return;
}
let val = newValue === "" ? true : newValue;
if (val === null) val = false;
Reflect.set(this, toCamelCase(name), val);
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/symbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const layoutEffectsSymbol = Symbol("haunted.layoutEffects");
type EffectsSymbols = typeof effectsSymbol | typeof layoutEffectsSymbol;
type Phase = typeof updateSymbol | typeof commitSymbol | typeof effectsSymbol;

const reflectingSymbol = Symbol("haunted.reflecting");

const contextEvent = "haunted.context";

export {
Expand All @@ -18,6 +20,7 @@ export {
commitSymbol,
effectsSymbol,
layoutEffectsSymbol,
reflectingSymbol,
contextEvent,
Phase,
EffectsSymbols,
Expand Down
63 changes: 59 additions & 4 deletions src/use-property.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,51 @@
import { hook, Hook } from "./hook";
import { State } from "./state";
import { reflectingSymbol } from "./symbols";
import type {
InitialState,
NewState,
StateUpdater,
StateTuple,
} from "./use-state";

type Host<T> = Element & { [key: string]: T };
type Host<T> = Element & { [key: string]: T } & {
[reflectingSymbol]?: boolean;
};
type ChangeEvent<T> = {
value: T;
path: string;
};

export interface UsePropertyOptions {
reflect?: boolean;
}

export interface UseProperty {
<T>(property: string): StateTuple<T | undefined>;
<T>(property: string, value?: InitialState<T>): StateTuple<T>;
<T>(
property: string,
value: InitialState<T>,
options: UsePropertyOptions
): StateTuple<T>;
}

const UPPER = /([A-Z])/gu;

export const useProperty = hook(
class<T> extends Hook<[string, T], StateTuple<T>, Host<T>> {
class<T> extends Hook<[string, T, UsePropertyOptions?], StateTuple<T>, Host<T>> {
property: string;
eventName: string;
attrName: string;
reflect: boolean;
lastReflected: T | undefined;

constructor(
id: number,
state: State<Host<T>>,
property: string,
initialValue: InitialState<T>
initialValue: InitialState<T>,
options?: UsePropertyOptions
) {
super(id, state);

Expand All @@ -39,8 +55,20 @@

this.updater = this.updater.bind(this);
this.property = property;
this.reflect = options?.reflect ?? false;
this.eventName =
property.replace(UPPER, "-$1").toLowerCase() + "-changed";
this.attrName = property.replace(UPPER, "-$1").toLowerCase();

// If reflecting, read initial value from attribute if present
if (this.reflect && this.state.host.hasAttribute(this.attrName)) {
const attrVal = this.state.host.getAttribute(this.attrName);
const coerced = (attrVal === "" ? true : attrVal) as T;
if (this.state.host[this.property] == null) {
this.updateProp(coerced);
return;
}

Check warning on line 70 in src/use-property.ts

View workflow job for this annotation

GitHub Actions / Test: ubuntu-latest (node@22)

This hunk is not covered

Check warning on line 70 in src/use-property.ts

View workflow job for this annotation

GitHub Actions / Test: ubuntu-latest (node@22)

This hunk is not covered
}

// set the initial value only if it was not already set by the parent
if (this.state.host[this.property] != null) return;
Expand All @@ -55,7 +83,13 @@
this.updateProp(initialValue);
}

update(ignored: string, ignored2: T): StateTuple<T> {
update(ignored: string, ignored2: T, ignored3?: UsePropertyOptions): StateTuple<T> {
if (this.reflect) {
const currentValue = this.state.host[this.property];
if (!Object.is(currentValue, this.lastReflected)) {
this.reflectToAttribute(currentValue);
}
}
return [this.state.host[this.property], this.updater];
}

Expand All @@ -78,6 +112,27 @@
const ev = this.notify(value);
if (ev.defaultPrevented) return;
this.state.host[this.property] = value;

if (this.reflect) {
this.reflectToAttribute(value);
}
}

reflectToAttribute(value: T): void {
const host = this.state.host;
this.lastReflected = value;
host[reflectingSymbol] = true;
try {
if (value == null || value === false) {
host.removeAttribute(this.attrName);
} else if (value === true) {
host.setAttribute(this.attrName, "");
} else {
host.setAttribute(this.attrName, String(value));
}
} finally {
host[reflectingSymbol] = false;
}
}

notify(value: T) {
Expand Down
31 changes: 31 additions & 0 deletions test/attrs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,37 @@ describe("Observed attributes", () => {
expect(div.textContent).to.equal("test test");
});

it("Attribute removal sets property to false", async () => {
const tag = "attrs-removal-test";
let val: unknown;

interface Props {
open: boolean;
}

function Drawer({ open }) {
val = open;
return html`Test`;
}

customElements.define(
tag,
component<HTMLElement & Props>(Drawer, { observedAttributes: ["open"] })
);

const el = (await fixture(
html`<attrs-removal-test open></attrs-removal-test>`
)) as HTMLElement & Props;

expect(el.open).to.be.true;
expect(val).to.be.true;

el.removeAttribute("open");
await nextFrame();
expect(el.open).to.equal(false);
expect(val).to.equal(false);
});

it("observed attribute names turn into camelCase props", async () => {
const tag = "attrs-camelcase-test";
let el;
Expand Down
Loading