oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// look.js: a team page's icon and banner with script (columns and icons
2// spec §2.5, §3.3). Without it, the look row's links and the banner's
3// controls open /p/{id}/look, which does everything with forms. This
4// adds the icon picker, uploads straight from the page, and dragging
5// the banner to reposition it. Every change is POST /p/{id}/look, held
6// for the busy rule's 650ms; the page is then loaded again, which
7// commits any draft as a close does (level-up §6.5).
8(function () {
9 "use strict";
10
11 var HOLD_MS = 650;
12 var COLUMNS = 8;
13 var TYPES = "image/png,image/jpeg,image/gif,image/webp";
14 var ICON_BYTES = 128 * 1024;
15
16 function element(tag, attributes, text) {
17 var made = document.createElement(tag);
18 Object.keys(attributes || {}).forEach(function (name) {
19 made.setAttribute(name, attributes[name]);
20 });
21 if (text) made.textContent = text;
22 return made;
23 }
24
25 // busy marks the control that sent a change, as busy.js marks a
26 // form's button: a spinner, aria-busy, and no second press.
27 function busy(control, on) {
28 if (!control) return;
29 var spin = control.querySelector("[rst-spin]");
30 if (on && !spin) {
31 spin = element("span", { "rst-spin": "", "aria-hidden": "true" });
32 control.insertBefore(spin, control.firstChild);
33 } else if (!on && spin) {
34 spin.remove();
35 }
36 if (on) control.setAttribute("aria-busy", "true");
37 else control.removeAttribute("aria-busy");
38 if ("disabled" in control) control.disabled = on;
39 }
40
41 // send posts the look change, holds for the busy rule, and loads the
42 // page again; a refusal comes back as its sentence. control, when
43 // given, shows the busy state while it waits.
44 function send(href, fields, control) {
45 if (control && control.getAttribute("aria-busy") === "true") {
46 return Promise.resolve(null);
47 }
48 busy(control, true);
49 var body = new URLSearchParams();
50 Object.keys(fields).forEach(function (key) { body.set(key, fields[key]); });
51 var wait = new Promise(function (resolve) { setTimeout(resolve, HOLD_MS); });
52 var sent = fetch(href, {
53 method: "POST", body: body, credentials: "same-origin",
54 headers: { "Accept": "application/json" }
55 }).then(function (response) {
56 return response.json().then(function (reply) {
57 return { ok: response.ok, reply: reply };
58 });
59 });
60 return Promise.all([sent, wait]).then(function (both) {
61 if (both[0].ok) {
62 window.location.reload();
63 return null;
64 }
65 busy(control, false);
66 return both[0].reply.error || "That didn't work. Try again.";
67 }, function () {
68 busy(control, false);
69 return "That didn't work. Try again.";
70 });
71 }
72
73 // upload sends one file to POST /images and answers its public id.
74 function upload(file) {
75 var form = new FormData();
76 form.append("file", file);
77 return fetch("/images", {
78 method: "POST", body: form, credentials: "same-origin",
79 headers: { "Accept": "application/json" }
80 }).then(function (response) {
81 return response.json().then(function (reply) {
82 if (!response.ok) throw new Error(reply.error || "The picture wasn't stored.");
83 return reply.id;
84 });
85 });
86 }
87
88 // squareIcon crops a picture to a centred square at side pixels: PNG
89 // for a picture that may be transparent, JPEG otherwise (§2.3).
90 function squareIcon(file, side) {
91 if (typeof createImageBitmap !== "function") return Promise.resolve(file);
92 return createImageBitmap(file, { imageOrientation: "from-image" }).then(function (bitmap) {
93 var edge = Math.min(bitmap.width, bitmap.height);
94 var canvas = element("canvas", { width: String(side), height: String(side) });
95 canvas.getContext("2d").drawImage(bitmap, (bitmap.width - edge) / 2,
96 (bitmap.height - edge) / 2, edge, edge, 0, 0, side, side);
97 var type = file.type === "image/jpeg" ? "image/jpeg" : "image/png";
98 return new Promise(function (resolve) {
99 canvas.toBlob(function (blob) { resolve(blob || file); }, type, 0.9);
100 });
101 }).then(function (blob) {
102 if (blob.size > ICON_BYTES && side > 64) return squareIcon(file, side / 2);
103 return blob;
104 }, function () { return file; });
105 }
106
107 // chooseFile opens the file chooser and answers the file picked.
108 function chooseFile(then) {
109 var input = element("input", { type: "file", accept: TYPES, hidden: "" });
110 document.body.appendChild(input);
111 input.addEventListener("change", function () {
112 var file = input.files && input.files[0];
113 input.remove();
114 if (file) then(file);
115 });
116 input.click();
117 }
118
119 // say shows a sentence in the page's polite live region.
120 function say(text) {
121 // The region is the server's, so it exists before anything is said.
122 var region = document.getElementById("mapa-look-said");
123 if (region) region.textContent = text;
124 }
125
126 // ---- The icon picker ----------------------------------------------------
127
128 function Picker(row) {
129 this.href = row.getAttribute("data-mapa-look-href");
130 this.list = row.getAttribute("data-mapa-emoji");
131 this.opener = row.querySelector('[data-mapa-look="icon"]');
132 this.hasIcon = Boolean(document.querySelector("h1[mapa-title] > [mapa-icon]"));
133 this.build();
134 }
135
136 Picker.prototype.build = function () {
137 var picker = this;
138 this.pop = element("div", { popover: "", role: "dialog", "aria-label": "Choose an icon", "mapa-picker": "" });
139 this.field = element("input", {
140 "rst-input": "", type: "search", role: "combobox", "aria-expanded": "true",
141 "aria-controls": "mapa-picker-list", "aria-autocomplete": "list",
142 "aria-label": "Search for an emoji or type one", autocomplete: "off", "mapa-picker-field": ""
143 });
144 this.listbox = element("div", { id: "mapa-picker-list", role: "listbox", "aria-label": "Emoji", "mapa-picker-list": "" });
145 this.status = element("p", { role: "status", "mapa-sr": "" });
146 this.error = element("p", { "rst-field-error": "", role: "alert", hidden: "" });
147 var foot = element("div", { "mapa-picker-foot": "" });
148 var pictureButton = element("button", { type: "button", "rst-btn": "" }, "Upload a picture…");
149 foot.appendChild(pictureButton);
150 if (this.hasIcon) {
151 var remove = element("button", { type: "button", "rst-btn": "" }, "Remove icon");
152 remove.addEventListener("click", function () { picker.submit({ do: "remove-icon" }); });
153 foot.appendChild(remove);
154 }
155 [this.field, this.status, this.error, this.listbox, foot].forEach(function (part) { picker.pop.appendChild(part); });
156 document.body.appendChild(this.pop);
157 pictureButton.addEventListener("click", function () { picker.picture(); });
158 this.field.addEventListener("input", function () { picker.filter(); });
159 this.field.addEventListener("keydown", function (event) { picker.key(event); });
160 this.listbox.addEventListener("click", function (event) {
161 var option = event.target.closest("[role=option]");
162 if (option) picker.choose(option.getAttribute("data-emoji"));
163 });
164 var escaped = false;
165 this.pop.addEventListener("keydown", function (event) {
166 if (event.key === "Escape") escaped = true;
167 });
168 this.pop.addEventListener("toggle", function (event) {
169 if (event.newState === "open") { escaped = false; return; }
170 // Back to the opener after Esc; a click elsewhere keeps its focus.
171 if (escaped) picker.opener.focus({ preventScroll: true });
172 });
173 };
174
175 Picker.prototype.open = function () {
176 var picker = this;
177 this.pop.showPopover();
178 this.field.focus();
179 if (this.emoji) return;
180 fetch(this.list, { credentials: "same-origin" }).then(function (response) {
181 return response.json();
182 }).then(function (data) {
183 picker.groups = data.groups;
184 picker.emoji = data.emoji;
185 picker.filter();
186 }).catch(function () {
187 picker.refused("The emoji list didn't load. Type an emoji, or upload a picture.");
188 });
189 };
190
191 // filter draws the emoji matching the search, by group, at most 400.
192 Picker.prototype.filter = function () {
193 if (!this.emoji) return;
194 var query = this.field.value.trim().toLowerCase();
195 var typed = this.field.value.trim();
196 var shown = this.emoji.filter(function (each) {
197 return !query || each.n.indexOf(query) >= 0 || each.e === typed ||
198 each.e.replace(/️/g, "") === typed.replace(/️/g, "");
199 }).slice(0, 400);
200 this.listbox.textContent = "";
201 this.options = [];
202 var picker = this, group = -1, holder = null;
203 shown.forEach(function (each, index) {
204 if (each.g !== group && !query) {
205 group = each.g;
206 holder = element("div", { role: "group", "aria-label": picker.groups[group], "mapa-picker-group": "" });
207 holder.appendChild(element("p", { "aria-hidden": "true", "mapa-picker-head": "" }, picker.groups[group]));
208 picker.listbox.appendChild(holder);
209 } else if (!holder) {
210 holder = picker.listbox;
211 }
212 var option = element("div", { role: "option", id: "mapa-emoji-" + index, "data-emoji": each.e, "aria-label": each.n, "aria-selected": "false" }, each.e);
213 holder.appendChild(option);
214 picker.options.push(option);
215 });
216 this.status.textContent = shown.length === 1 ? "1 emoji" : shown.length + " emoji";
217 this.active(0);
218 };
219
220 Picker.prototype.active = function (index) {
221 if (!this.options || !this.options.length) {
222 this.field.removeAttribute("aria-activedescendant");
223 return;
224 }
225 index = Math.max(0, Math.min(index, this.options.length - 1));
226 if (this.current !== undefined && this.options[this.current]) {
227 this.options[this.current].setAttribute("aria-selected", "false");
228 }
229 this.current = index;
230 var option = this.options[index];
231 option.setAttribute("aria-selected", "true");
232 option.scrollIntoView({ block: "nearest" });
233 this.field.setAttribute("aria-activedescendant", option.id);
234 };
235
236 Picker.prototype.key = function (event) {
237 var moves = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: COLUMNS, ArrowUp: -COLUMNS };
238 if (moves[event.key] && this.options && this.options.length) {
239 if ((event.key === "ArrowRight" || event.key === "ArrowLeft") && this.field.value) return;
240 event.preventDefault();
241 this.active(this.current + moves[event.key]);
242 } else if (event.key === "Enter" && this.options && this.options[this.current]) {
243 event.preventDefault();
244 this.choose(this.options[this.current].getAttribute("data-emoji"));
245 }
246 };
247
248 Picker.prototype.choose = function (emoji) {
249 this.submit({ do: "emoji", emoji: emoji });
250 };
251
252 Picker.prototype.picture = function () {
253 var picker = this;
254 chooseFile(function (file) {
255 picker.status.textContent = "Uploading the picture";
256 squareIcon(file, 256).then(upload).then(function (id) {
257 picker.submit({ do: "icon", image: id });
258 }, function (error) { picker.refused(error.message); });
259 });
260 };
261
262 Picker.prototype.submit = function (fields) {
263 var picker = this;
264 this.pop.setAttribute("aria-busy", "true");
265 send(this.href, fields).then(function (refusal) {
266 if (refusal) picker.refused(refusal);
267 });
268 };
269
270 Picker.prototype.refused = function (text) {
271 this.pop.removeAttribute("aria-busy");
272 this.error.textContent = text;
273 this.error.hidden = false;
274 this.field.focus();
275 };
276
277 // ---- The banner -----------------------------------------------------------
278
279 function addBanner(href, control) {
280 if (control && control.getAttribute("aria-busy") === "true") return;
281 chooseFile(function (file) {
282 say("Uploading the banner");
283 busy(control, true);
284 upload(file).then(function (id) {
285 busy(control, false);
286 return send(href, { do: "banner", image: id, y: "50" }, control);
287 }).then(function (refusal) { if (refusal) say(refusal); },
288 function (error) { busy(control, false); say(error.message); });
289 });
290 }
291
292 // reposition lets the picture be dragged up or down, or moved with the
293 // arrow keys, then stores the nearest step of 5 (§3.2). The link that
294 // started it gives way to a real button, Save position; Esc cancels.
295 function reposition(banner, href, link, byKey) {
296 var picture = banner.querySelector("img");
297 var stored = parseInt(banner.getAttribute("data-y"), 10);
298 var y = isNaN(stored) ? 50 : stored;
299 var start = null;
300 var save = element("button", { type: "button", "rst-btn": "" }, "Save position");
301 link.replaceWith(save);
302 banner.setAttribute("data-mapa-moving", "");
303 picture.draggable = false;
304 // A key that started this is still going down: focus the button,
305 // and let it save, only once that key is up, so it never presses
306 // the button too. A pointer's click is done already.
307 // A click with no key behind it (a screen reader's, voice control's)
308 // is armed after a short wait, so keyup is the fast path, not the
309 // only one (Fable, build round 2).
310 var armed = false;
311 function arm() {
312 if (armed) return;
313 armed = true;
314 save.focus();
315 }
316 if (byKey) {
317 document.addEventListener("keyup", arm, { once: true });
318 setTimeout(arm, 400);
319 } else {
320 setTimeout(arm, 0);
321 }
322 say("Drag the picture or use the arrow keys. Then choose Save position.");
323 function show(next) {
324 y = Math.max(0, Math.min(100, Math.round(next / 5) * 5));
325 banner.setAttribute("data-y", String(y));
326 }
327 function end() { start = null; }
328 picture.addEventListener("pointerdown", function (event) {
329 event.preventDefault();
330 start = { at: event.clientY, y: y };
331 picture.setPointerCapture(event.pointerId);
332 });
333 picture.addEventListener("pointermove", function (event) {
334 if (!start) return;
335 var moved = (start.at - event.clientY) / banner.clientHeight * 100;
336 show(start.y + moved);
337 });
338 ["pointerup", "pointercancel", "lostpointercapture"].forEach(function (name) {
339 picture.addEventListener(name, end);
340 });
341 save.addEventListener("keydown", function (event) {
342 if (event.key === "ArrowUp") { event.preventDefault(); show(y + 5); }
343 if (event.key === "ArrowDown") { event.preventDefault(); show(y - 5); }
344 if (event.key === "Escape") { event.preventDefault(); window.location.reload(); }
345 });
346 save.addEventListener("click", function () {
347 if (!armed) return;
348 send(href, { do: "position", y: String(y) }, save).then(function (refusal) {
349 if (refusal) say(refusal);
350 });
351 });
352 }
353
354 function bindBanner(banner) {
355 var href = banner.getAttribute("data-mapa-look-href");
356 if (!href) return;
357 banner.querySelectorAll("[data-mapa-banner]").forEach(function (control) {
358 control.addEventListener("click", function (event) {
359 var what = control.getAttribute("data-mapa-banner");
360 event.preventDefault();
361 if (what === "reposition") reposition(banner, href, control, event.detail === 0);
362 if (what === "change") addBanner(href, control);
363 if (what === "remove") {
364 send(href, { do: "remove-banner" }, control).then(function (refusal) {
365 if (refusal) say(refusal);
366 });
367 }
368 });
369 });
370 }
371
372 function start() {
373 var row = document.querySelector("[mapa-look-row]");
374 if (row && typeof HTMLElement.prototype.showPopover === "function") {
375 var picker = null;
376 row.querySelector('[data-mapa-look="icon"]').addEventListener("click", function (event) {
377 event.preventDefault();
378 picker = picker || new Picker(row);
379 picker.open();
380 });
381 row.querySelector('[data-mapa-look="banner"]').addEventListener("click", function (event) {
382 event.preventDefault();
383 addBanner(row.getAttribute("data-mapa-look-href"), event.currentTarget);
384 });
385 }
386 document.querySelectorAll("[mapa-banner]").forEach(bindBanner);
387 }
388
389 if (document.readyState === "loading") {
390 document.addEventListener("DOMContentLoaded", start);
391 } else {
392 start();
393 }
394})();
395