-
-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathui.js
More file actions
399 lines (381 loc) · 11 KB
/
ui.js
File metadata and controls
399 lines (381 loc) · 11 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// @ts-check
// Module core/ui
// Handles the ReSpec UI
// XXX TODO
// - look at other UI things to add
// - list issues
// - lint: validator, link checker, check WebIDL, ID references
// - save to GitHub
// - make a release candidate that people can test
// - once we have something decent, merge, ship as 3.2.0
import { html, pluralize } from "./import-maps.js";
import { reindent, xmlEscape } from "./utils.js";
import css from "../styles/ui.css.js";
import { markdownToHtml } from "./markdown.js";
import { sub } from "./pubsubhub.js";
export const name = "core/ui";
// Opportunistically inserts the style, with the chance to reduce some FOUC
insertStyle();
function insertStyle() {
const styleElement = document.createElement("style");
styleElement.id = "respec-ui-styles";
styleElement.textContent = css;
styleElement.classList.add("removeOnSave");
document.head.appendChild(styleElement);
return styleElement;
}
/**
* @param {Element | null | undefined} elem
* @param {Map<string, string>} ariaMap
*/
function ariaDecorate(elem, ariaMap) {
if (!elem) {
return;
}
Array.from(ariaMap).forEach(([name, value]) => {
elem.setAttribute(`aria-${name}`, value);
});
}
const respecUI = html`<div id="respec-ui" class="removeOnSave" hidden></div>`;
const menu = html`<ul
id="respec-menu"
role="menu"
aria-labelledby="respec-pill"
hidden
></ul>`;
const closeButton = html`<button
class="close-button"
aria-label="Close"
onclick=${() => ui.closeModal()}
title="Close"
>
❌
</button>`;
window.addEventListener("load", () => trapFocus(menu));
/** @type {HTMLElement | null} */
let modal;
/** @type {HTMLElement | null} */
let overlay;
/** @type {HTMLElement | null} */
let currentModalOwner;
/** @type {any[]} */
const errors = [];
/** @type {any[]} */
const warnings = [];
/** @type {Record<string, HTMLButtonElement>} */
const buttons = {};
sub("start-all", () => document.body.prepend(respecUI), { once: true });
sub("end-all", () => document.body.prepend(respecUI), { once: true });
const respecPill = html`<button id="respec-pill" disabled>ReSpec</button>`;
respecUI.appendChild(respecPill);
respecPill.addEventListener(
"click",
/** @param {MouseEvent} e */ e => {
e.stopPropagation();
respecPill.setAttribute("aria-expanded", String(menu.hidden));
toggleMenu();
menu.querySelector("li:first-child button")?.focus();
}
);
document.documentElement.addEventListener("click", () => {
if (!menu.hidden) {
toggleMenu();
}
respecPill.setAttribute("aria-expanded", "false");
});
respecUI.appendChild(menu);
menu.addEventListener(
"keydown",
/** @param {KeyboardEvent} e */ e => {
if (e.key === "Escape" && !menu.hidden) {
respecPill.setAttribute("aria-expanded", String(menu.hidden));
toggleMenu();
respecPill.focus();
return;
}
const items = /** @type {HTMLElement[]} */ ([
...menu.querySelectorAll("button:not([disabled])"),
]);
const currentIndex = items.indexOf(
/** @type {HTMLElement} */ (document.activeElement)
);
switch (e.key) {
case "ArrowDown": {
e.preventDefault();
const next = items[(currentIndex + 1) % items.length];
next?.focus();
break;
}
case "ArrowUp": {
e.preventDefault();
const prev = items[(currentIndex - 1 + items.length) % items.length];
prev?.focus();
break;
}
case "Home":
e.preventDefault();
items[0]?.focus();
break;
case "End":
e.preventDefault();
items[items.length - 1]?.focus();
break;
}
}
);
function toggleMenu() {
menu.classList.toggle("respec-hidden");
menu.classList.toggle("respec-visible");
menu.hidden = !menu.hidden;
}
/**
* @param {Element} element
*/
function trapFocus(element) {
/** @type {NodeListOf<HTMLElement>} */
const focusableEls = element.querySelectorAll(
"a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled])"
);
const firstFocusableEl = focusableEls[0];
const lastFocusableEl = focusableEls[focusableEls.length - 1];
if (firstFocusableEl) {
firstFocusableEl.focus();
}
element.addEventListener("keydown", e => {
const keyEvent = /** @type {KeyboardEvent} */ (e);
if (keyEvent.key !== "Tab") {
return;
}
// shift + tab
if (keyEvent.shiftKey) {
if (document.activeElement === firstFocusableEl) {
lastFocusableEl.focus();
keyEvent.preventDefault();
}
}
// tab
else if (document.activeElement === lastFocusableEl) {
firstFocusableEl.focus();
keyEvent.preventDefault();
}
});
}
const ariaMap = new Map([
["controls", "respec-menu"],
["expanded", "false"],
["haspopup", "true"],
["label", "ReSpec Menu"],
]);
ariaDecorate(respecPill, ariaMap);
/**
* @param {RespecError | string} err
* @param {(RespecError | string)[]} arr
* @param {string} butName
* @param {string} title
*/
function errWarn(err, arr, butName, title) {
arr.push(err);
if (!buttons.hasOwnProperty(butName)) {
buttons[butName] = createWarnButton(butName, arr, title);
respecUI.appendChild(buttons[butName]);
}
const button = buttons[butName];
button.textContent = String(arr.length);
const label = arr.length === 1 ? pluralize.singular(title) : title;
const ariaMap = new Map([["label", `${arr.length} ${label}`]]);
ariaDecorate(button, ariaMap);
}
/**
* @param {string} butName
* @param {any[]} arr
* @param {string} title
*/
function createWarnButton(butName, arr, title) {
const buttonId = `respec-pill-${butName}`;
const button = html`<button
id="${buttonId}"
class="respec-info-button"
></button>`;
button.addEventListener("click", () => {
button.setAttribute("aria-expanded", "true");
const ol = html`<ol class="${`respec-${butName}-list`}"></ol>`;
for (const err of arr) {
const fragment = document
.createRange()
.createContextualFragment(rsErrorToHTML(err));
const li = document.createElement("li");
// if it's only a single element, just copy the contents into li
if (fragment.firstElementChild === fragment.lastElementChild) {
li.append(
.../** @type {Element} */ (fragment.firstElementChild).childNodes
);
// Otherwise, take everything.
} else {
li.appendChild(fragment);
}
ol.appendChild(li);
}
ui.freshModal(title, ol, button);
});
const ariaMap = new Map([
["expanded", "false"],
["haspopup", "true"],
["controls", `respec-pill-${butName}-modal`],
]);
ariaDecorate(button, ariaMap);
return button;
}
export const ui = {
show() {
try {
respecUI.hidden = false;
} catch (err) {
console.error(err);
}
},
hide() {
respecUI.hidden = true;
},
enable() {
respecPill.removeAttribute("disabled");
},
/**
* @param {string} _keyShort shortcut key. unused - kept for backward compatibility.
* @param {string} label
* @param {Function} handler
* @param {string} icon
*/
addCommand(label, handler, _keyShort, icon) {
icon = icon || "";
const id = `respec-button-${label.toLowerCase().replace(/\s+/, "-")}`;
const button = html`<button id="${id}" class="respec-option">
<span class="respec-cmd-icon" aria-hidden="true">${icon}</span> ${label}…
</button>`;
const menuItem = html`<li role="menuitem">${button}</li>`;
menuItem.addEventListener("click", handler);
menu.appendChild(menuItem);
return button;
},
/** @param {RespecError | string} rsError */
error(rsError) {
errWarn(rsError, errors, "error", "ReSpec Errors");
},
/** @param {RespecError | string} rsError */
warning(rsError) {
errWarn(rsError, warnings, "warning", "ReSpec Warnings");
},
/** @param {Element} [owner] */
closeModal(owner) {
const effectiveOwner = owner || currentModalOwner;
if (overlay) {
const overlayElem = overlay;
overlayElem.classList.remove("respec-show-overlay");
overlayElem.classList.add("respec-hide-overlay");
overlayElem.addEventListener("transitionend", () => {
overlayElem.remove();
overlay = null;
});
}
if (effectiveOwner) {
effectiveOwner.setAttribute("aria-expanded", "false");
}
if (!modal) return;
modal.remove();
modal = null;
currentModalOwner = null;
respecPill.focus();
},
/**
* @param {string} title
* @param {Node} content
* @param {HTMLElement} currentOwner
*/
freshModal(title, content, currentOwner) {
if (modal) modal.remove();
if (overlay) overlay.remove();
if (currentModalOwner && currentModalOwner !== currentOwner) {
currentModalOwner.setAttribute("aria-expanded", "false");
}
currentModalOwner = currentOwner;
overlay = html`<div id="respec-overlay" class="removeOnSave"></div>`;
const id = `${currentOwner.id}-modal`;
const headingId = `${id}-heading`;
modal = html`<div
id="${id}"
class="respec-modal removeOnSave"
role="dialog"
aria-labelledby="${headingId}"
>
${closeButton}
<h3 id="${headingId}">${title}</h3>
<div class="inside">${content}</div>
</div>`;
const ariaMap = new Map([["labelledby", headingId]]);
ariaDecorate(modal, ariaMap);
document.body.append(
/** @type {HTMLElement} */ (overlay),
/** @type {HTMLElement} */ (modal)
);
/** @type {HTMLElement} */ (overlay).addEventListener("click", () =>
this.closeModal(currentOwner)
);
/** @type {HTMLElement} */ (overlay).classList.toggle(
"respec-show-overlay"
);
/** @type {HTMLElement} */ (modal).hidden = false;
trapFocus(/** @type {HTMLElement} */ (modal));
},
};
document.addEventListener("keydown", ev => {
if (ev.key === "Escape") {
ui.closeModal();
}
});
window.respecUI = ui;
sub(
"error",
/** @param {RespecError | string} details */ details => ui.error(details)
);
sub(
"warn",
/** @param {RespecError | string} details */ details => ui.warning(details)
);
/**
* @param {RespecError | string} err
*/
function rsErrorToHTML(err) {
if (typeof err === "string") {
return err;
}
const plugin = err.plugin
? `<p class="respec-plugin">(plugin: "${err.plugin}")</p>`
: "";
const hint = err.hint
? `\n${markdownToHtml(
`<p class="respec-hint"><strong>How to fix:</strong> ${reindent(
err.hint
)}`,
{
inline: !err.hint.includes("\n"),
}
)}\n`
: "";
const elements = Array.isArray(err.elements)
? `<p class="respec-occurrences">Occurred <strong>${
err.elements.length
}</strong> times at:</p>
${markdownToHtml(err.elements.map(generateMarkdownLink).join("\n"))}`
: "";
const details = err.details
? `\n\n<details>\n${err.details}\n</details>\n`
: "";
const msg = markdownToHtml(`**${xmlEscape(err.message)}**`, { inline: true });
const result = `${msg}${hint}${elements}${details}${plugin}`;
return result;
}
/**
* @param {Element} element
*/
function generateMarkdownLink(element) {
return `* [\`<${element.localName}>\`](#${element.id}) element`;
}