Skip to content

Commit

Permalink
Update event handling logic and add todo list example (#4)
Browse files Browse the repository at this point in the history
* Move event listener code to constructor and update ts annotations

* Update tsconfig

* Create todo list example
  • Loading branch information
hawkticehurst authored Dec 7, 2023
1 parent 9855c79 commit 7ee9d03
Show file tree
Hide file tree
Showing 3 changed files with 177 additions and 27 deletions.
156 changes: 156 additions & 0 deletions examples/todo-list/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todo List</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: system-ui, sans-serif;
font-weight: 500;
display: grid;
place-content: center;
height: 100vh;
margin: 0;
padding: 0;
}
todo-list input {
font-family: inherit;
font-size: inherit;
font-weight: inherit;
color: black;
background-color: #efefef;
border: 2px solid #000;
border-radius: 6px;
padding: 6px 10px;
}
todo-list .todos {
margin: 20px 0;
display: flex;
flex-direction: column;
gap: 10px;
}
todo-list .todo {
display: flex;
align-items: center;
gap: 4px;
cursor: pointer;
}
:root {
--checkbox-color: #000;
--checkbox-disabled-color: #858585;
--checkbox-size: 24px;
}
todo-list input[type='checkbox'] {
-webkit-appearance: none;
appearance: none;
margin: 0;
width: var(--checkbox-size);
height: var(--checkbox-size);
border: 2px solid var(--checkbox-color);
border-radius: 6px;
display: grid;
place-content: center;
cursor: pointer;
}
todo-list input[type='checkbox']::before {
--checkmark-size: 12px;
content: '';
box-shadow: inset var(--checkmark-size) var(--checkmark-size)
var(--checkbox-color);
background-color: CanvasText;
width: var(--checkmark-size);
height: var(--checkmark-size);
clip-path: polygon(
12.08% 50.81%,
0.24% 67.73%,
42.23% 97.13%,
99.25% 15.68%,
81.01% 2.91%,
35.84% 67.44%
);
transform: scale(0);
transition: transform 100ms ease-in-out;
}
todo-list input[type='checkbox']:checked::before {
transform: scale(1);
}
todo-list input[type='checkbox']:focus-visible {
outline: none;
border-color: #015fcc;
}
todo-list label:has(input[type="checkbox"]:checked) {
text-decoration: line-through;
}
todo-list button {
font-family: inherit;
font-size: 0.9rem;
font-weight: inherit;
color: black;
background-color: #efefef;
border: 2px solid #000;
border-radius: 8px;
padding: 4px 8px;
}
todo-list button:hover,
todo-list button:active {
cursor: pointer;
background-color: #e6e6e6;
}
</style>
</head>
<body>
<todo-list>
<input type="text" @keydown="addTodo" placeholder="Add todo item">
<section :ref="todos" class="todos" @change="updateRemainder">
<label class="todo">
<input type="checkbox"> Pick up groceries
</label>
<label class="todo">
<input type="checkbox"> Go on a walk
</label>
</section>
<p><span $state="remaining">2</span> remaining</p>
<button @click="clearTodos">Clear completed</button>
<template>
<label class="todo">
<input type="checkbox">
</label>
</template>
</todo-list>
<script type="module">
import { Stellar } from 'https://www.unpkg.com/stellar-element@0.3.0/build/index.js';
class TodoList extends Stellar {
constructor() {
super();
this.template = this.querySelector('template');
}
addTodo = (event) => {
if (event.key !== "Enter") return;
const todo = this.template.content.cloneNode(true);
const text = document.createTextNode(event.target.value);
todo.children[0].appendChild(text);
this.refs.todos.appendChild(todo);
event.target.value = "";
this.updateRemainder();
}
clearTodos = () => {
const completed = this.refs.todos.querySelectorAll('input[type="checkbox"]:checked');
for (const todo of completed) {
this.refs.todos.removeChild(todo.parentNode);
}
this.updateRemainder();
}
updateRemainder = () => {
const remaining = this.refs.todos.querySelectorAll('input[type="checkbox"]:not(:checked)');
this.remaining = remaining.length;
}
}
customElements.define('todo-list', TodoList);
</script>
</body>
</html>
42 changes: 18 additions & 24 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class Stellar extends HTMLElement {
private _tracked: { elem: HTMLElement; event: string; fn: EventListener }[];
private _bind: { elem: HTMLElement; name: string; property: string }[];
private _derived: { elem: HTMLElement; method: string; vars: string[] }[];
protected refs: Record<string, HTMLElement>;
public refs: Record<string, HTMLElement>;
constructor() {
super();
this._tracked = [];
Expand Down Expand Up @@ -52,38 +52,32 @@ export class Stellar extends HTMLElement {
for (const attr of node.attributes) {
switch (true) {
case attr.name === ':ref':
changes.push(() => this.#setRef(attr));
changes.push(() => this.setRef(attr));
break;
case attr.name.startsWith('$bind'):
this.#bindProperty(attr);
this.bindProperty(attr);
break;
case attr.name === '$derive':
this.#deriveState(attr);
this.deriveState(attr);
break;
case attr.name.startsWith('$'):
changes.push(() => this.#setState(attr));
changes.push(() => this.setState(attr));
break;
case attr.name.startsWith('@'):
changes.push(() => this.#setEventHandler(attr));
changes.push(() => this.setEventHandler(attr));
break;
}
}
}
for (const change of changes) {
change();
}
}
connectedCallback() {
// Attach event listeners
for (const { elem, event, fn } of this._tracked) {
elem?.addEventListener(event, fn);
}
}
disconnectedCallback() {
for (const { elem, event, fn } of this._tracked) {
elem?.removeEventListener(event, fn);
}
}
#setEventHandler(attr: Attr) {
private setEventHandler(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const { name: event, value: method } = attr;
this._tracked.push({
Expand All @@ -93,7 +87,7 @@ export class Stellar extends HTMLElement {
});
removeAttribute(elem, attr);
}
#setState(attr: Attr) {
private setState(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const stateName = attr.value;
const bound: ((value: any) => void)[] = [];
Expand Down Expand Up @@ -141,7 +135,7 @@ export class Stellar extends HTMLElement {
},
enumerable: true,
});
this.#initState(elem.textContent, stateName);
this.initState(elem.textContent, stateName);
} else if (attr.name === '$state:value' || attr.name === '$value') {
if (
elem instanceof HTMLInputElement ||
Expand All @@ -157,7 +151,7 @@ export class Stellar extends HTMLElement {
},
enumerable: true,
});
this.#initState(elem.value, stateName);
this.initState(elem.value, stateName);
} else {
console.error(
'Error: Attribute `$state:value` can only be set on elements that have a `value` property.'
Expand All @@ -173,7 +167,7 @@ export class Stellar extends HTMLElement {
},
enumerable: true,
});
this.#initState(elem.innerHTML, stateName);
this.initState(elem.innerHTML, stateName);
} else if (attr.name === '$state:disabled' || attr.name === '$disabled') {
if (
elem instanceof HTMLButtonElement ||
Expand All @@ -193,7 +187,7 @@ export class Stellar extends HTMLElement {
},
enumerable: true,
});
this.#initState(elem.disabled, stateName);
this.initState(elem.disabled, stateName);
}
} else if (attr.name === '$state:checked' || attr.name === '$checked') {
if (elem instanceof HTMLInputElement) {
Expand All @@ -206,17 +200,17 @@ export class Stellar extends HTMLElement {
},
enumerable: true,
});
this.#initState(elem.checked, stateName);
this.initState(elem.checked, stateName);
}
}
removeAttribute(elem, attr);
}
#initState(initial: string | boolean | null, stateName: string) {
private initState(initial: string | boolean | null, stateName: string) {
if (initial) {
(this as any)[stateName] = initial;
}
}
#setRef(attr: Attr) {
private setRef(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const refName = attr.value;
Object.defineProperty(this.refs, refName, {
Expand All @@ -227,7 +221,7 @@ export class Stellar extends HTMLElement {
});
removeAttribute(elem, attr);
}
#bindProperty(attr: Attr) {
private bindProperty(attr: Attr) {
// Todo: Abstract function to bind any property
const elem = attr.ownerElement as HTMLElement;
if (attr.name === '$bind') {
Expand All @@ -250,7 +244,7 @@ export class Stellar extends HTMLElement {
}
removeAttribute(elem, attr);
}
#deriveState(attr: Attr) {
private deriveState(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const value = attr.value.split('(');
const method = value[0];
Expand Down
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "esnext",
"target": "ESNext",
"module": "ESNext",
"outDir": "build",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"declaration": true,
"strict": true,
"allowJs": true,
Expand Down

0 comments on commit 7ee9d03

Please sign in to comment.