forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAreaMenuOverlay.tsx
More file actions
372 lines (350 loc) · 12.7 KB
/
AreaMenuOverlay.tsx
File metadata and controls
372 lines (350 loc) · 12.7 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
import { useCallback, useEffect, useRef, useState } from "react";
import * as Blockly from "blockly";
import * as ReactDOM from "react-dom";
import { Button, ButtonProps } from "../../../react-common/components/controls/Button";
import { FocusTrap } from "../../../react-common/components/controls/FocusTrap";
import IProjectView = pxt.editor.IProjectView;
interface AreaMenuOverlapProps {
parent: IProjectView;
}
interface RectBounds {
top: number;
bottom: number;
left: number;
right: number;
width: number;
height: number;
}
type AreaId = "topbar" | "simulator" | "toolbox" | "workspace" | "bottombar" | "tutorial";
interface Area {
id: AreaId;
ariaLabel: string;
shortcutKey: string;
getClassName?(projectView: IProjectView): string | undefined;
getBounds(projectView: IProjectView): DOMRect | undefined;
focus(projectView: IProjectView): void;
}
const getToolboxBounds = (projectView: IProjectView): DOMRect | undefined => {
const flyoutOnly = projectView.state.editorState?.hasCategories === false;
const blocksActive = projectView.isBlocksActive();
if (flyoutOnly) {
return document.querySelector(`${blocksActive ? ".blocklyFlyout" : ".monacoFlyout"}`)?.getBoundingClientRect();
} else {
return document.querySelector(`${blocksActive ? ".blocklyToolbox" : ".monacoToolboxDiv"}`)?.getBoundingClientRect();
}
}
const isSimMini = () => !!document.querySelector(".miniSim");
const areas: Area[] = [
{
id: "topbar",
ariaLabel: lf("Top bar"),
shortcutKey: "1",
getBounds() {
return document.querySelector("#mainmenu")?.getBoundingClientRect();
},
focus() {
findFirstFocusableDescendant(
document.querySelector("#mainmenu")!,
(e) =>
// This isn't actually focusable and has the same behavior as home.
e.classList.contains("brand") ||
// The menuitem containing the editor toggle.
!!Array.from(e.children).find(e => e.id === "editortoggle")
)?.focus();
}
},
{
id: "simulator",
ariaLabel: lf("Simulator"),
shortcutKey: "2",
getBounds(projectView: IProjectView) {
if (pxt.appTarget.simulator?.headless) {
return undefined;
}
const element = isSimMini()
? document.querySelector(".simPanel")
: projectView.state.collapseEditorTools ?
document.querySelector("#computertogglesim")
: document.querySelector("#editorSidebar")
const bounds = element?.getBoundingClientRect();
if (!bounds) {
return undefined;
}
if (projectView.state.collapseEditorTools) {
// Custom presentation for the collapsed sim.
const isRtl = pxt.Util.isUserLanguageRtl();
const collapsedSimPadding = 30;
const copy = DOMRect.fromRect(bounds);
copy.y = bounds.top - collapsedSimPadding;
copy.width = 70;
copy.height = bounds.height + collapsedSimPadding * 2;
if (isRtl) {
copy.x -= copy.width - bounds.width;
}
return copy;
}
return bounds;
},
focus(projectView: IProjectView) {
// Note that pxtsim.driver.focus() isn't the same as tabbing to the sim.
if (isSimMini()) {
projectView.setSimulatorFullScreen(true);
} else {
if (projectView.state.collapseEditorTools) {
projectView.toggleSimulatorCollapse();
}
(document.querySelector("#boardview") as HTMLElement)?.focus();
}
},
getClassName(projectView: IProjectView) {
const classNames = ["simulator-area"];
if (projectView.state.collapseEditorTools) {
classNames.push("simulator-collapsed");
}
return classNames.join(" ");
},
},
{
id: "toolbox",
ariaLabel: lf("Toolbox"),
shortcutKey: "3",
getBounds(projectView: IProjectView) {
const bounds = getToolboxBounds(projectView);
if (!bounds) {
return undefined;
}
const inTutorial = !!projectView.state.tutorialOptions?.tutorial;
const isHeadless = !!pxt.appTarget.simulator?.headless;
if (projectView.state.collapseEditorTools && !(isHeadless && inTutorial)) {
const isRtl = pxt.Util.isUserLanguageRtl();
// Shift over for a clearer area when the toolbox is collapsed
const copy = DOMRect.fromRect(bounds);
if (isRtl) {
copy.width += document.body.clientWidth - bounds.right;
} else {
copy.x = 0;
copy.width = bounds.x + bounds.width;
}
return copy;
}
return bounds;
},
focus(projectView: IProjectView) {
projectView.editor.focusToolbox();
}
},
{
id: "workspace",
ariaLabel: lf("Workspace"),
shortcutKey: "4",
getBounds(projectView: IProjectView) {
const editorSelectors = ["#pxtJsonEditor", "#githubEditor", "#blocksArea", "#serialEditor", "#assetEditor", "#monacoEditor"];
for (const selector of editorSelectors) {
const element = document.querySelector(selector) as HTMLElement | null;
if (element.offsetParent !== null) {
const bounds = element.getBoundingClientRect();
if (selector === "#monacoEditor" || selector === "#blocksArea") {
// Use bounds that don't overlap the toolbox.
const isRtl = pxt.Util.isUserLanguageRtl();
const toolbox = getToolboxBounds(projectView);
const copied = DOMRect.fromRect(bounds);
if (toolbox) {
copied.width -= toolbox.width;
if (!isRtl) {
copied.x = toolbox.right;
}
}
return copied;
}
return bounds;
}
}
return undefined;
},
focus(projectView: IProjectView) {
if (projectView.isPxtJsonEditor()) {
findFirstFocusableDescendant(document.querySelector("#pxtJsonEditor"))?.focus();
} else {
projectView.editor.focusWorkspace();
}
}
},
{
id: "bottombar",
ariaLabel: lf("Bottom bar"),
shortcutKey: "5",
getBounds() {
return document.querySelector("#editortools")?.getBoundingClientRect();
},
focus() {
findFirstFocusableDescendant(document.querySelector("#editortools")!)?.focus();
}
},
{
id: "tutorial",
ariaLabel: lf("Tutorial"),
// This isn't really in sequence but it's not usually present.
shortcutKey: "0",
getBounds() {
return document.querySelector(".tutorialWrapper")?.getBoundingClientRect();
},
focus() {
findFirstFocusableDescendant(document.querySelector(".tutorialWrapper")!)?.focus();
}
},
];
export const AreaMenuOverlay = ({ parent }: AreaMenuOverlapProps) => {
const previouslyFocused = useRef<Element>(document.activeElement);
const movedFocusToAreaRef = useRef(false);
const getRects = (): Map<AreaId, DOMRect | undefined> => (
new Map(areas.map(area => [area.id, area.getBounds(parent)]))
);
const [areaRects, setAreaRects] = useState(getRects());
const moveFocusToArea = useCallback((area: Area) => {
Blockly.hideChaff();
area.focus(parent);
movedFocusToAreaRef.current = true;
parent.toggleAreaMenu();
}, [parent]);
useEffect(() => {
const listener = (e: KeyboardEvent) => {
const area = areas.find(area => area.shortcutKey === e.key && !!areaRects.get(area.id));
if (area) {
e.preventDefault();
moveFocusToArea(area);
}
}
document.addEventListener("keydown", listener)
const observer = new ResizeObserver(() => {
setAreaRects(getRects())
});
observer.observe(document.body);
return () => {
observer.disconnect()
document.removeEventListener("keydown", listener)
// Restore focus if we didn't already move it.
if (previouslyFocused.current && !movedFocusToAreaRef.current) {
(previouslyFocused.current as HTMLElement).focus();
}
}
}, [])
const handleEscape = useCallback(() => {
parent.toggleAreaMenu();
}, [parent]);
// Something is awry, bail out.
const bailOut = !areaRects.get("workspace");
useEffect(() => {
if (bailOut) {
parent.toggleAreaMenu();
}
}, [bailOut, parent]);
if (bailOut) {
return null;
}
return ReactDOM.createPortal(
<FocusTrap dontRestoreFocus onEscape={handleEscape} arrowKeyNavigation={true} focusFirstItem>
<div className="area-menu-container" role="menu" aria-label={lf("Area overlay")}>
{areas.map(area => {
const rect = areaRects.get(area.id);
return rect ? (<AreaButton
key={area.id}
title={area.ariaLabel}
shortcutKey={area.shortcutKey}
bounds={rect}
onClick={() => {
moveFocusToArea(area);
}}
ariaLabel={area.ariaLabel}
className={area.getClassName?.(parent)}
/>) : null;
})}
</div>
</FocusTrap>,
document.getElementById("root") || document.body
);
}
interface AreaButtonProps extends ButtonProps {
shortcutKey: string;
bounds: RectBounds;
}
const AreaButton = ({ shortcutKey, bounds, ...props }: AreaButtonProps) => {
const { top, height, left, width } = bounds;
return <Button
{...props}
className={`area-button ${props.className}`}
role="menuitem"
style={{
top, height, left, width
}}
>
<div><p>{shortcutKey.toUpperCase()}</p></div>
</Button>
}
/**
* Find the first focusable descendant element within a given element.
*/
function findFirstFocusableDescendant(element: HTMLElement, skip?: (element: Element) => boolean): HTMLElement | null {
const nativelyFocusableSelectors = [
'[contenteditable]:not([contenteditable="false"])',
'a[href]',
'audio[controls]',
'button:not([disabled])',
'details > summary:first-of-type',
'iframe',
'input:not([disabled]):not([type="hidden"])',
'select:not([disabled])',
'textarea:not([disabled])',
'video[controls]',
];
const ariaFocusableRoles = [
'button',
'checkbox',
'combobox',
'dialog',
'gridcell',
'link',
'menuitem',
'menuitemcheckbox',
'menuitemradio',
'option',
'radio',
'searchbox',
'slider',
'spinbutton',
'switch',
'tab',
'textbox',
'treeitem'
];
const selectors = [
...nativelyFocusableSelectors,
'[tabindex]:not([tabindex="-1"])',
...ariaFocusableRoles.map(role => `[role="${role}"]`)
];
const candidates = Array.from(
element.querySelectorAll<HTMLElement>(selectors.join(','))
);
// Could also sequence by tabindex here but assuming only 0/-1 used.
return candidates.find(candidate => {
// This can be replaced with checkVisibility when types/support allows.
if (candidate.offsetParent === null) {
return false;
}
if (candidate.ariaHidden === 'true') {
return false;
}
if (candidate.inert || candidate.closest('[inert]')) {
return false;
}
if (candidate.ariaDisabled === 'true') {
return false;
}
if (candidate.closest('fieldset[disabled]')) {
return false;
}
if (skip?.(candidate)) {
return false;
}
return true;
});
}