// The rules as the fields say them (M1-UI-008, M1-UI-015). // // The server holds the authoritative draft, but typing has to go somewhere // between keystrokes, and rebuilding the fields from every response would take // the cursor with it. So the page keeps its own copy, and remembers what the // server was last told, to know whether the results on screen are for it. import { emptyRule } from "./rule.js"; export class Draft { rules = []; // The body the server last accepted, or null before the first load. #applied = null; // The exact bytes a push would send, so "what the server was told" and "what // the fields say" are compared in one shape. get body() { return JSON.stringify({ rules: this.rules }); } get loaded() { return this.#applied !== null; } // Anything typed since the server last accepted a draft: the results on // screen are not for what is in the fields. get stale() { return this.loaded && this.body !== this.#applied; } // The session's rules, which the server already holds. Copied, so an edit // changes this draft and nothing the payload still refers to. load(rules) { this.rules = rules.map((rule) => ({ ...rule })); this.#applied = this.body; } // The server took `body`. It may not be the current one, since typing goes // on while a push is out. accepted(body) { this.#applied = body; } // A new rule, empty but for any `fields` it starts with (D12). add(fields = {}) { this.rules.push({ ...emptyRule(), ...fields }); } } // M1-UI-015: what the fields say, what the results are for, and whether any of // it has reached the file yet -- all three, because they can differ. `latest` // is the last state payload, null until one arrives. export function stateText({ busy, stale, latest }) { const words = []; if (busy) words.push("evaluating…"); else if (stale) words.push("results are for your last finished edit"); if (latest && latest.dirty) words.push("unsaved changes"); else if (latest) words.push("saved"); return words.join(" · "); }