-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui-fields.js
More file actions
291 lines (273 loc) · 11.2 KB
/
Copy pathui-fields.js
File metadata and controls
291 lines (273 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Shared form-field helpers used by every calculator module.
//
// Centralizes the input/select/checkbox/output line builders so each
// calc-*.js does not redeclare them. Copy buttons emit "Copied"
// announcements through clipboard.js for consistent screen-reader
// behavior. textContent / createElement only - never innerHTML.
import { copyText } from "./clipboard.js";
export const DEBOUNCE_MS = 50;
export function debounce(fn, ms = DEBOUNCE_MS) {
let t = 0;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
}
export function fmt(n, digits = 2) {
if (n === null || n === undefined || !Number.isFinite(Number(n))) return "-";
return Number(n).toFixed(digits);
}
export function makeNumber(label, id, attrs = {}) {
const wrap = document.createElement("div");
wrap.className = "field";
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = label;
const input = document.createElement("input");
input.type = "number";
input.id = id;
input.inputMode = "decimal";
input.autocomplete = "off";
for (const [k, v] of Object.entries(attrs)) input.setAttribute(k, String(v));
wrap.appendChild(lab);
wrap.appendChild(input);
return { wrap, input };
}
// A repeated row -- a timesheet day, a catch can, a panel circuit -- builds
// its inputs by hand and leans on the placeholder to say what each box is.
// The placeholder disappears the instant a value lands, and "Test with
// example" fills every box at once, so the first thing a user does is erase
// every label on the screen and leave a column of bare numbers. This is
// makeNumber's layout at a smaller weight: a caption that stays put.
export function makeRowField(label, id, attrs = {}) {
const wrap = document.createElement("div");
wrap.className = "row-field";
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = label;
const input = document.createElement("input");
input.type = "number";
input.id = id;
input.inputMode = "decimal";
input.autocomplete = "off";
for (const [k, v] of Object.entries(attrs)) input.setAttribute(k, String(v));
wrap.appendChild(lab);
wrap.appendChild(input);
return { wrap, input };
}
export function makeText(label, id, attrs = {}) {
const wrap = document.createElement("div");
wrap.className = "field";
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = label;
const input = document.createElement("input");
input.type = "text";
input.id = id;
input.autocomplete = "off";
for (const [k, v] of Object.entries(attrs)) input.setAttribute(k, String(v));
wrap.appendChild(lab);
wrap.appendChild(input);
return { wrap, input };
}
export function makeTextarea(label, id, attrs = {}) {
const wrap = document.createElement("div");
wrap.className = "field";
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = label;
const input = document.createElement("textarea");
input.id = id;
input.autocomplete = "off";
for (const [k, v] of Object.entries(attrs)) input.setAttribute(k, String(v));
wrap.appendChild(lab);
wrap.appendChild(input);
return { wrap, input };
}
export function makeSelect(label, id, options) {
const wrap = document.createElement("div");
wrap.className = "field";
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = label;
const sel = document.createElement("select");
sel.id = id;
for (const o of options) {
const opt = document.createElement("option");
opt.value = o.value;
opt.textContent = o.label;
if (o.selected) opt.selected = true;
sel.appendChild(opt);
}
wrap.appendChild(lab);
wrap.appendChild(sel);
return { wrap, select: sel };
}
export function makeCheckbox(label, id, checked = false) {
const wrap = document.createElement("div");
wrap.className = "field field-check";
const input = document.createElement("input");
input.type = "checkbox";
input.id = id;
input.checked = checked;
const lab = document.createElement("label");
lab.htmlFor = id;
lab.textContent = " " + label;
wrap.appendChild(input);
wrap.appendChild(lab);
return { wrap, input };
}
// Labels whose value is prose, not an answer. Around a thousand tiles end
// their output list with a "Note" that restates the tile's scope in a full
// paragraph -- useful, but not something to print between the numbers with a
// Copy button beside it. Give it its own collapsed row instead, so the answer
// area stays short and the note is one click away.
const PROSE_LABELS = new Set(["Note", "Notes"]);
export function makeOutputLine(parent, label, valueId) {
if (PROSE_LABELS.has(label)) return makeNoteLine(parent, label, valueId);
const row = document.createElement("p");
const lab = document.createElement("strong");
lab.textContent = label + ": ";
row.appendChild(lab);
const span = document.createElement("span");
span.id = valueId;
span.className = "out-value";
row.appendChild(span);
const btn = document.createElement("button");
btn.type = "button";
btn.className = "copy-btn";
btn.style.marginLeft = "8px";
btn.textContent = "Copy";
btn.addEventListener("click", () => copyText(span.textContent || "", btn));
row.appendChild(btn);
parent.appendChild(row);
return span;
}
// Same contract as makeOutputLine -- returns the element the caller writes the
// value into -- but rendered as a collapsed disclosure and left out of
// clipboard.collectOutputs (which reads <p><strong> rows), so "Copy all"
// copies the answer rather than a page of prose.
function makeNoteLine(parent, label, valueId) {
const row = document.createElement("details");
row.className = "note-row";
const sum = document.createElement("summary");
sum.textContent = label;
row.appendChild(sum);
const span = document.createElement("span");
span.id = valueId;
span.className = "out-value note-value";
row.appendChild(span);
parent.appendChild(row);
return span;
}
export function attachExampleButton(host, fillFn) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "example-btn";
btn.textContent = "Test with example";
host.insertBefore(btn, host.firstChild);
// Whether an answer was already on its way in before priming started. A
// deep-linked tile gets real input events from applyHashState, and the
// ?example=1 path clicks this button -- both are meant to show a result.
// Anything else opens without one. Capture phase, so a renderer that fires
// non-bubbling events is still seen.
let seeded = false;
const mark = () => { seeded = true; };
btn.addEventListener("click", () => { mark(); fillFn(); });
host.addEventListener("input", mark, true);
host.addEventListener("change", mark, true);
// Deferred: many tiles attach the button before they build their fields,
// and the view applies deep-linked values right after the renderer returns.
// A microtask runs after both, still before the first paint.
queueMicrotask(() => {
host.removeEventListener("input", mark, true);
host.removeEventListener("change", mark, true);
primeExamplePlaceholders(host, fillFn, seeded);
});
return btn;
}
// Show the tile's worked-example value as the placeholder of every empty
// field, so a user sees the expected magnitude and format before typing
// anything ("e.g. 150"). Rather than hand-writing a placeholder for each of
// the ~1,700 tiles, run the tile's own example filler once against the freshly
// rendered fields, copy what it wrote into placeholders, and put every field
// back exactly as it was. Fields that already hold a value -- a tile default or
// a deep-linked one -- keep it and get no placeholder.
function primeExamplePlaceholders(host, fillFn, seeded) {
// The view can already be gone by the time the microtask runs -- a fast
// hash change, or a catalog-wide sweep. Priming a detached region is pure
// cost, so skip it.
if (host.isConnected === false) return;
const els = Array.from(host.querySelectorAll("input, select, textarea"));
if (!els.length) return;
const before = els.map((el) => ({ el, value: el.value, checked: el.checked }));
// A tile that was not going to show an answer must not start showing one.
// That includes tiles whose fields carry defaults: computing off a default
// nobody chose would put a confident verdict on screen before the reader has
// typed anything.
const restoreOutputs = seeded ? () => {} : snapshotOutputs(host);
try {
fillFn();
} catch {
// A filler that throws against empty fields leaves nothing to copy;
// the restore below still runs so the tile renders as it always did.
}
const touched = [];
for (const snap of before) {
const el = snap.el;
if (isTextish(el) && !snap.value && el.value && !el.getAttribute("placeholder")) {
el.setAttribute("placeholder", "e.g. " + el.value);
}
if (el.value !== snap.value || el.checked !== snap.checked) {
el.value = snap.value;
el.checked = snap.checked;
touched.push(el);
}
}
// Re-fire the events the tile listens on so any mode-driven field
// visibility and the output region return to their pre-fill state. These do
// not bubble: the tile's own per-field listeners see them, but the delegated
// hash-state writer on the region does not, so opening a tile still leaves
// the URL as a bare `#tool-id`.
for (const el of touched) {
el.dispatchEvent(new Event("input", { bubbles: false }));
el.dispatchEvent(new Event("change", { bubbles: false }));
}
// The filler's compute is debounced, so it lands well after the restore
// above. Watch the answer region and undo any write until it settles;
// reverting inside the observer callback means no intermediate frame is ever
// painted or observable. Once a field differs from what priming put back,
// the reader has typed and the answer on screen is theirs.
const untouched = () => before.every((snap) => snap.el.value === snap.value && snap.el.checked === snap.checked);
restoreOutputs(untouched);
const out = outputRegionFor(host);
if (!seeded && out && typeof MutationObserver === "function") {
const obs = new MutationObserver(() => restoreOutputs(untouched));
obs.observe(out, { childList: true, subtree: true, characterData: true });
setTimeout(() => { restoreOutputs(untouched); obs.disconnect(); }, DEBOUNCE_MS * 4);
}
}
function isTextish(el) {
return el.tagName === "TEXTAREA"
|| (el.tagName === "INPUT" && (el.type === "number" || el.type === "text"));
}
function outputRegionFor(host) {
return (host.parentElement && host.parentElement.querySelector(".output-region")) || null;
}
// Capture the answer region's current text so priming can put it back. The
// returned restore takes a predicate: once the reader has changed a field, the
// answer on screen is theirs and must be left alone. Returns a no-op when the
// tile has no sibling output region.
function snapshotOutputs(host) {
const out = outputRegionFor(host);
if (!out) return () => {};
const leaves = Array.from(out.querySelectorAll("*"))
.filter((el) => !el.firstElementChild)
.map((el) => ({ el, text: el.textContent }));
return (untouched) => {
if (untouched && !untouched()) return;
for (const leaf of leaves) {
if (leaf.el.textContent !== leaf.text) leaf.el.textContent = leaf.text;
}
};
}