1.0.1
This commit is contained in:
+219
-100
@@ -24,7 +24,7 @@ export type RemovalSubscription<T> = (removedItem: T) => void;
|
||||
|
||||
export class State<T> {
|
||||
private _value: T;
|
||||
private _bindings = new Set<StateSubscription<T>>();
|
||||
_bindings = new Set<StateSubscription<T>>();
|
||||
|
||||
// init
|
||||
constructor(initialValue: T) {
|
||||
@@ -37,7 +37,6 @@ export class State<T> {
|
||||
}
|
||||
|
||||
set value(newValue: T) {
|
||||
if (this._value == newValue) return;
|
||||
this._value = newValue;
|
||||
this.callSubscriptions();
|
||||
}
|
||||
@@ -52,6 +51,10 @@ export class State<T> {
|
||||
fn(this._value);
|
||||
}
|
||||
|
||||
subscribeSilent(fn: (newValue: T) => void): void {
|
||||
this._bindings.add(fn);
|
||||
}
|
||||
|
||||
// stringify
|
||||
toString(): string {
|
||||
return JSON.stringify(this._value);
|
||||
@@ -60,7 +63,8 @@ export class State<T> {
|
||||
|
||||
export class ListState<T> extends State<Set<T>> {
|
||||
private additionHandlers = new Set<AdditionSubscription<T>>();
|
||||
private removalHandlers = new Map<T, RemovalSubscription<T>>();
|
||||
private removalHandlers = new Map<T, Set<RemovalSubscription<T>>>();
|
||||
private genericRemovalHandlers = new Set<RemovalSubscription<T>>();
|
||||
|
||||
// init
|
||||
constructor(initialItems?: T[]) {
|
||||
@@ -70,6 +74,7 @@ export class ListState<T> extends State<Set<T>> {
|
||||
// list
|
||||
add(...items: T[]): void {
|
||||
items.forEach((item) => {
|
||||
if (this.value.has(item)) return;
|
||||
this.value.add(item);
|
||||
this.additionHandlers.forEach((handler) => handler(item));
|
||||
});
|
||||
@@ -80,8 +85,9 @@ export class ListState<T> extends State<Set<T>> {
|
||||
items.forEach((item) => {
|
||||
this.value.delete(item);
|
||||
|
||||
this.genericRemovalHandlers.forEach(handler => handler(item));
|
||||
if (!this.removalHandlers.has(item)) return;
|
||||
this.removalHandlers.get(item)!(item);
|
||||
this.removalHandlers.get(item)!.forEach((handler) => handler(item));
|
||||
this.removalHandlers.delete(item);
|
||||
});
|
||||
this.callSubscriptions();
|
||||
@@ -98,17 +104,82 @@ export class ListState<T> extends State<Set<T>> {
|
||||
}
|
||||
|
||||
handleRemoval(item: T, handler: RemovalSubscription<T>): void {
|
||||
this.removalHandlers.set(item, handler);
|
||||
if (!this.removalHandlers.has(item))
|
||||
this.removalHandlers.set(item, new Set());
|
||||
this.removalHandlers.get(item)!.add(handler);
|
||||
}
|
||||
|
||||
handleRemovals(handler: RemovalSubscription<T>): void {
|
||||
this.genericRemovalHandlers.add(handler);
|
||||
}
|
||||
|
||||
// stringification
|
||||
toString(): string {
|
||||
const array = [...this.value];
|
||||
const array = [...this.value.values()];
|
||||
const json = JSON.stringify(array);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
export class MapState<T> extends State<Map<string, T>> {
|
||||
private additionHandlers = new Set<AdditionSubscription<T>>();
|
||||
private removalHandlers = new Map<T, Set<RemovalSubscription<T>>>();
|
||||
private genericRemovalHandlers = new Set<RemovalSubscription<T>>();
|
||||
|
||||
// init
|
||||
constructor(initialItems?: [string, T][]) {
|
||||
super(new Map<string, T>(initialItems));
|
||||
}
|
||||
|
||||
// list
|
||||
set(key: string, item: T): void {
|
||||
this.remove(key);
|
||||
this.value.set(key, item);
|
||||
this.additionHandlers.forEach((handler) => handler(item));
|
||||
this.callSubscriptions();
|
||||
}
|
||||
|
||||
remove(key: string): void {
|
||||
const item = this.value.get(key);
|
||||
if (!item) return;
|
||||
|
||||
this.value.delete(key);
|
||||
this.callSubscriptions();
|
||||
|
||||
this.genericRemovalHandlers.forEach(handler => handler(item));
|
||||
if (!this.removalHandlers.has(item)) return;
|
||||
this.removalHandlers.get(item)!.forEach((handler) => handler(item));
|
||||
this.removalHandlers.delete(item);
|
||||
}
|
||||
|
||||
clear() {
|
||||
[...this.value.keys()].forEach((key) => this.remove(key));
|
||||
}
|
||||
|
||||
// handlers
|
||||
handleAddition(handler: AdditionSubscription<T>): void {
|
||||
this.additionHandlers.add(handler);
|
||||
[...this.value.values()].forEach(handler);
|
||||
}
|
||||
|
||||
handleRemoval(item: T, handler: RemovalSubscription<T>): void {
|
||||
if (!this.removalHandlers.has(item))
|
||||
this.removalHandlers.set(item, new Set());
|
||||
this.removalHandlers.get(item)!.add(handler);
|
||||
}
|
||||
|
||||
handleRemovals(handler: RemovalSubscription<T>): void {
|
||||
this.genericRemovalHandlers.add(handler);
|
||||
}
|
||||
|
||||
// stringification
|
||||
toString(): string {
|
||||
const array = [...this.value.entries()];
|
||||
const json = JSON.stringify(array);
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
// UTILITY
|
||||
export function createProxyState<T>(
|
||||
statesToSubscibe: State<any>[],
|
||||
@@ -116,15 +187,22 @@ export function createProxyState<T>(
|
||||
): State<T> {
|
||||
const proxyState = new State<T>(fn());
|
||||
statesToSubscibe.forEach((state) =>
|
||||
state.subscribe(() => (proxyState.value = fn()))
|
||||
state.subscribeSilent(() => (proxyState.value = fn()))
|
||||
);
|
||||
return proxyState;
|
||||
}
|
||||
|
||||
export function bulkSubscribe(
|
||||
statesToSubscibe: State<any>[],
|
||||
fn: () => void
|
||||
): void {
|
||||
statesToSubscibe.forEach((state) => state.subscribeSilent(fn));
|
||||
}
|
||||
|
||||
function persistState(localStorageKey: string, state: State<any>) {
|
||||
state.subscribe(() => {
|
||||
const stringifiedValue = state.toString();
|
||||
localStorage.setItem(localStorageKey, stringifiedValue);
|
||||
const stringifiedValue = state.toString();
|
||||
localStorage.setItem(localStorageKey, stringifiedValue);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -133,8 +211,8 @@ export function restoreState<T>(
|
||||
initialStateValue: T
|
||||
): State<T> {
|
||||
const storedString =
|
||||
localStorage.getItem(localStorageKey) ??
|
||||
JSON.stringify(initialStateValue);
|
||||
localStorage.getItem(localStorageKey) ??
|
||||
JSON.stringify(initialStateValue);
|
||||
const convertedValue = JSON.parse(storedString);
|
||||
|
||||
const state = new State(convertedValue);
|
||||
@@ -144,16 +222,15 @@ export function restoreState<T>(
|
||||
}
|
||||
|
||||
export function restoreListState<T>(
|
||||
localStorageKey: string
|
||||
localStorageKey: string,
|
||||
initialItems: any[] = []
|
||||
): ListState<T> {
|
||||
const storedString = localStorage.getItem(localStorageKey) ?? "";
|
||||
|
||||
let initialItems: any[] = [];
|
||||
|
||||
try {
|
||||
const array = JSON.parse(storedString);
|
||||
if (!Array.isArray(array)) throw "";
|
||||
initialItems = array;
|
||||
const array = JSON.parse(storedString);
|
||||
if (!Array.isArray(array)) throw "";
|
||||
initialItems = array;
|
||||
} catch {}
|
||||
|
||||
const state = new ListState<T>(initialItems);
|
||||
@@ -162,13 +239,29 @@ export function restoreListState<T>(
|
||||
return state;
|
||||
}
|
||||
|
||||
export type ListItemConverter<T> = (
|
||||
item: T
|
||||
) => HTMLElement;
|
||||
export function restoreMapState<T>(
|
||||
localStorageKey: string,
|
||||
initialItems: [string, any][] = []
|
||||
): MapState<T> {
|
||||
const storedString = localStorage.getItem(localStorageKey) ?? "";
|
||||
|
||||
try {
|
||||
const array = JSON.parse(storedString);
|
||||
if (!Array.isArray(array)) throw "";
|
||||
initialItems = array;
|
||||
} catch {}
|
||||
|
||||
const state = new MapState<T>(initialItems);
|
||||
persistState(localStorageKey, state);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export type StateItemConverter<T> = (item: T) => HTMLElement;
|
||||
|
||||
/*
|
||||
JSX
|
||||
*/
|
||||
*/
|
||||
|
||||
export function createElement(
|
||||
tagName: keyof HTMLElementTagNameMap,
|
||||
@@ -178,87 +271,113 @@ export function createElement(
|
||||
const element = document.createElement(tagName);
|
||||
|
||||
if (attributes != null)
|
||||
Object.entries(attributes).forEach((entry) => {
|
||||
const [attributename, value] = entry;
|
||||
const [directiveKey, directiveValue] = attributename.split(":");
|
||||
Object.entries(attributes).forEach((entry) => {
|
||||
const [attributename, value] = entry;
|
||||
const [directiveKey, directiveValue] = attributename.split(":");
|
||||
|
||||
switch (directiveKey) {
|
||||
case "on": {
|
||||
switch (directiveValue) {
|
||||
case "enter": {
|
||||
element.addEventListener("keydown", (e) => {
|
||||
if ((e as KeyboardEvent).key != "Enter") return;
|
||||
value();
|
||||
});
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
element.addEventListener(directiveValue, value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "subscribe": {
|
||||
if (directiveValue == "children") {
|
||||
element.style.scrollBehavior = "smooth";
|
||||
try {
|
||||
const [listState, toElement] = value as [
|
||||
listState: ListState<any>,
|
||||
ListItemConverter<any>
|
||||
];
|
||||
switch (directiveKey) {
|
||||
case "on": {
|
||||
switch (directiveValue) {
|
||||
case "enter": {
|
||||
element.addEventListener("keydown", (e: KeyboardEvent) => {
|
||||
if (e.key != "Enter") return;
|
||||
value(e);
|
||||
});
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
element.addEventListener(directiveValue, value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "keystroke": {
|
||||
element.addEventListener("keydown", (e: KeyboardEvent) => {
|
||||
if (e.metaKey == false && e.ctrlKey == false) return;
|
||||
if (e.key != directiveValue) return;
|
||||
value(e);
|
||||
})
|
||||
break;
|
||||
}
|
||||
case "subscribe": {
|
||||
const state = value as State<any>;
|
||||
state.subscribe(
|
||||
(newValue) => (element[directiveValue] = newValue)
|
||||
);
|
||||
|
||||
listState.handleAddition((newItem) => {
|
||||
const child = toElement(newItem);
|
||||
listState.handleRemoval(newItem, () =>
|
||||
child.remove()
|
||||
);
|
||||
element.append(child);
|
||||
element.scrollTop = element.scrollHeight;
|
||||
});
|
||||
} catch {
|
||||
throw `error: cannot process subscribe:children directive because ListItemConverter is not defined. Usage: "subscribe:children={[list, converter]}"; you can find a more detailed example in the documentation`;
|
||||
}
|
||||
} else {
|
||||
const state = value as State<any>;
|
||||
state.subscribe(
|
||||
(newValue) => (element[directiveValue] = newValue)
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "bind": {
|
||||
const state = value as State<any>;
|
||||
state.subscribe(
|
||||
(newValue) => (element[directiveValue] = newValue)
|
||||
);
|
||||
element.addEventListener(
|
||||
"input",
|
||||
() => (state.value = (element as any)[directiveValue])
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "toggle": {
|
||||
if (value.subscribe) {
|
||||
const state = value as State<any>;
|
||||
state.subscribe((newValue) =>
|
||||
element.toggleAttribute(directiveValue, newValue)
|
||||
);
|
||||
} else {
|
||||
element.toggleAttribute(directiveValue, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "set": {
|
||||
const state = value as State<any>;
|
||||
state.subscribe((newValue) =>
|
||||
element.setAttribute(directiveValue, newValue)
|
||||
);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
element.setAttribute(attributename, value);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "bind": {
|
||||
const state = value as State<any>;
|
||||
state.subscribe(
|
||||
(newValue) => (element[directiveValue] = newValue)
|
||||
);
|
||||
element.addEventListener(
|
||||
"input",
|
||||
() => (state.value = (element as any)[directiveValue])
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "toggle": {
|
||||
if (value.subscribe) {
|
||||
const state = value as State<any>;
|
||||
state.subscribe((newValue) =>
|
||||
element.toggleAttribute(directiveValue, newValue)
|
||||
);
|
||||
} else {
|
||||
element.toggleAttribute(directiveValue, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "set": {
|
||||
const state = value as State<any>;
|
||||
state.subscribe((newValue) =>
|
||||
element.setAttribute(directiveValue, newValue)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "children": {
|
||||
switch (directiveValue) {
|
||||
case "set": {
|
||||
const state = value as State<Node | Node[]>;
|
||||
state.subscribe((newValue) => {
|
||||
element.innerHTML = "";
|
||||
element.append(...[newValue].flat());
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "append":
|
||||
case "prepend": {
|
||||
try {
|
||||
const [listState, toElement] = value as [
|
||||
listState: ListState<any>,
|
||||
StateItemConverter<any>
|
||||
];
|
||||
|
||||
listState.handleAddition((newItem) => {
|
||||
const child = toElement(newItem);
|
||||
listState.handleRemoval(newItem, () =>
|
||||
child.remove()
|
||||
);
|
||||
|
||||
if (directiveValue == "append") {
|
||||
element.append(child);
|
||||
} else if (directiveValue == "prepend") {
|
||||
element.prepend(child);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw `error: cannot process subscribe:children directive. \n Usage: "children:append={[list, converter]}"; you can find a more detailed example in the documentation.`;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
element.setAttribute(attributename, value);
|
||||
}
|
||||
});
|
||||
|
||||
children.filter((x) => x).forEach((child) => element.append(child));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user