import { setZi } from "@/consts"; import Chit, { ChitFromDb } from "Modules/Chit" import WYSiWYG from "./WYSiWYG"; export default class Fridge { #chits: Chit[] = []; //@ts-expect-error #wysiwyg: WYSiWYG; #name: string; #counter!: number; #mileage!: number; constructor(wysiwyg: WYSiWYG) { const f = sessionStorage.fridge; this.#name = sessionStorage.name; if (f == null || this.#name == null || this.#name.length === 0) { location.href = "/" return; } sessionStorage.clear() const fdb = JSON.parse(f) as FridgeFromDb; if (fdb.mileage != null && fdb.cs != null) { this.mileage = fdb.mileage; this.counter = fdb.cs.length; for (const c of fdb.cs) { this.#chits.push(new Chit(this, wysiwyg, c)); } if (fdb.cs.length > 0) setZi(Math.max(...fdb.cs.map(c => c.zi)) + 1) } else { this.mileage = 0; this.counter = 0; } this.#wysiwyg = wysiwyg; } #createJson() { const fdb: FridgeFromDb = {}; fdb.mileage = this.#mileage; fdb.cs = []; for (const c of this.#chits) { fdb.cs.push({ top: c.top, left: c.left, txt: c.txt, width: c.width, height: c.height, zi: parseInt(c.zi), }) } return JSON.stringify({ name: this.#name, cs: fdb }); } async saveToDb() { const json = this.#createJson(); await fetch("http://localhost:8001/save-fridge.php", { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: json, }) } resetZi(zi: number) { for (const c of this.#chits) c.div.style.zIndex = (zi++).toString() return zi; } removeChit(ch: Chit) { this.counter = this.#counter - 1; this.#chits = this.#chits.filter(c => c !== ch); this.saveToDb() } makeTrans(except: Chit) { for (const c of this.#chits.filter(c => c !== except)) { c.makeTrans(); } } unmakeTrans() { for (const c of this.#chits) { c.unmakeTrans(); } } createChit() { this.counter = this.#counter + 1; this.mileage = this.#mileage + 1; this.#chits.push(new Chit(this, this.#wysiwyg)) this.saveToDb() } get chits(): Chit[] { return this.#chits; } set mileage(m: number) { this.#mileage = m; (document.querySelector("#mileage") as HTMLSpanElement).innerHTML = m.toString() } set counter(c: number) { this.#counter = c; (document.querySelector("#counter") as HTMLSpanElement).innerHTML = c.toString() } } export type FridgeFromDb = { cs?: ChitFromDb[], mileage?: number };