feat: things are happening...

This commit is contained in:
Daniel Ledda
2022-07-10 23:26:51 +02:00
parent fb9f78caf7
commit c9f2d2720c

View File

@@ -1,8 +1,29 @@
import {h, frag, Rung, RungOptions, Capsule} from "@djledda/ladder"; import {h, frag, Rung, RungOptions, Capsule, ICapsule} from "@djledda/ladder";
function list<Item extends any, Transform extends Element>(list: ICapsule<Item[]>, transform: (item: Item) => Transform, reuse?: (old: Transform) => Transform) {
let items: (Comment | Transform)[] = list.val.map(item => transform(item));
list.watch((newList) => {
const firstItem = items[0];
if (!firstItem) {
return;
}
const newItems = newList.map(item => transform(item));
for (const item of newItems) {
firstItem.parentElement?.replaceChildren(...newItems);
}
items = newItems;
if (items.length < 1) {
items.push(document.createComment("<!-- placeholder -->"));
}
});
if (items.length < 1) {
items.push(document.createComment("<!-- placeholder -->"));
}
return items;
}
export default class IngredientsPage extends Rung { export default class IngredientsPage extends Rung {
private ingredients: any[] = []; private ingredients = Capsule.new<any[]>([]);
private list = Capsule.new<HTMLDivElement | null>(null);
private ingredientInput = Capsule.new<HTMLInputElement | null>(null); private ingredientInput = Capsule.new<HTMLInputElement | null>(null);
constructor(options: RungOptions) { constructor(options: RungOptions) {
@@ -14,30 +35,22 @@ export default class IngredientsPage extends Rung {
body: this.ingredientInput.val?.value ?? "{}", body: this.ingredientInput.val?.value ?? "{}",
method: "POST", method: "POST",
}); });
this.ingredients.push(JSON.parse(this.ingredientInput.val?.value ?? "{}")); this.ingredients.val.push(JSON.parse(this.ingredientInput.val?.value ?? "{}"));
this.refreshList(); this.ingredients.val = this.ingredients.val;
} }
async getIngredients() { async getIngredients() {
const result = await (await fetch("http://localhost:8080/ingredients/all")).json(); const result = await (await fetch("http://localhost:8080/ingredients/all")).json();
this.ingredients = result.data.ingredients; this.ingredients.val = result.data.ingredients;
this.refreshList();
}
refreshList() {
this.list.val?.replaceWith(<this.List />);
}
List = (): HTMLUListElement => {
const thing = <div saveTo={this.list}>{...this.ingredients.map((ingredient) => {
return <div>{ingredient.displayNameDE}, hinzugefügt von {`${ingredient.addedBy}`}</div>;
})}</div> as HTMLUListElement;
return thing;
} }
build(): Node { build(): Node {
const node = <> const node = <>
<this.List saveTo={this.list} /> <ul>
{...list(this.ingredients, _ =>
<li>{_.displayNameDE}, hinzugefügt von {`${_.addedBy}`}</li> as HTMLDivElement)
}
</ul>
<input type={"text"} saveTo={this.ingredientInput} /> <input type={"text"} saveTo={this.ingredientInput} />
<button onclick={() => this.addIngredient()}>Submit!</button> <button onclick={() => this.addIngredient()}>Submit!</button>
</>; </>;