diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 1ba59b4e..b1a263ae 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -425,8 +425,28 @@ environment's `mount`, not to the embedded bootstrap page): the application after changing it. The tab's tooltip names the shortcut in use. - While the terminal is collapsed, `wf dev` keeps reloading the full-window interface, and a failed build still shows its diagnostic over it. - -The tab is a button (`aria-expanded`, 44 px target) and the window a non-modal dialog. The interface stays in the preview +- **The tab's menu** opens with a right click, a long press on a touch screen, or the Menu key or Shift+F10 while the tab + has the focus; a click and the shortcut keep opening and collapsing the terminal. Its entries are **Terminal**, + **C++ state ▸** (Functions, Browsers and tasks, Watches) and **TypeScript state ▸** (Packages, Bridge), the inspectors + of the application's state ([ADR-027](adr/ADR-027-inspecteurs-de-l-etat-de-l-application.md)). The arrow keys move in + it and open a submenu (right arrow, Enter or Space; the left arrow closes it), Escape closes the whole menu, from a + submenu too, and gives the focus back to the tab, and a press elsewhere closes it. It opens beside the tab and stays inside the browser window, on the other + side or upwards when there is no room, and narrows to a window smaller than its width. Closed, it takes no key from + the interface. A manifest may name Shift+F10 as the terminal's shortcut: on the focused tab, Shift+F10 then opens the + menu, and the tab's click (Enter or Space) or the menu's Terminal entry opens the terminal; anywhere else, the menu + included, the shortcut toggles the terminal. + + An inspector entry that cannot open is greyed, and the menu says why. The page asks C++ once which containers would + reach the inspectors (`webfront.inspector.containers()`, section 8 of the ADR). A library without that function is too + old for the inspectors. The inspectors answer only a page that is admitted (`UI::isLocalClient`): the view of an + embedded frontend (WebKitGTK, WKWebView, WebView2, CEF), which proves itself at the handshake, or any loopback page when + the application sets `WebFrontConfig::trustLoopbackClients`. With the system browser, which never receives that proof, + the entries are therefore unavailable by default, and the menu says to choose an embedded frontend or to set + `trustLoopbackClients`, knowing that any local process can then read the state of the application. The inspector panels + themselves come with the next versions of the environment; until then an admitted page's entries say so. + +The tab is a button (`aria-expanded`, `aria-haspopup="menu"`, 44 px target), its menu a `menu` of `menuitem`s of 44 px, +and the window a non-modal dialog. The interface stays in the preview frame, as before: the layout adds nothing to the application's documents except the shortcut's listener and the preview page's announcement, installed in the interface and in the same-origin frames it embeds (not in a frame of another origin, nor one inside a shadow tree: click the interface or the tab first). This is a layout, not a diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 01420ab6..373da32d 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -15,6 +15,7 @@ #include "WebFront.hpp" #include +#include namespace webfront { @@ -71,6 +72,14 @@ inline constexpr int apiVersion = 1; inline constexpr std::string_view defaultRegistry{"https://registry.npmjs.org/"}; +/// What webfront.inspector.containers() answers (ADR-027, section 8): whether the calling page can open a secondary window +/// that reaches the inspectors (the frontend opens one and the page is admitted, since opening it is checked like any +/// inspector call), whether the page itself is admitted (UI::isLocalClient), and whether a new connection that is not +/// proven would be (trustLoopbackClients). Three booleans and no state of the application: the call checks no access. +inline constexpr std::tuple inspectorContainers(bool frontendOpensWindows, bool hostAdmitted, bool trustLoopback) noexcept { + return {frontendOpensWindows && hostAdmitted, hostAdmitted, trustLoopback}; +} + /// The configuration the environment reads. "registry" always names a usable registry, for environments /// that predate "registryExplicit"; the latter tells whether the application chose it. inline std::string bootstrapConfig(const DeveloperBootstrapOptions& options) { @@ -131,6 +140,14 @@ class DeveloperAppWithNetwork : public BasicWF("webfront.developer.abort"); expose<&Store::stateOfLines, std::string, std::string>("webfront.developer.state"); expose<&Store::commitGroupLines, void, std::string, std::string, std::string>("webfront.developer.commitGroup"); +#if !(defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION) + // The inspectors exist only in the developer environment and never in a distribution build (ADR-027, section 1). + // The menu of the environment's tab asks it first: an environment that does not find it says the library is too old. + using Caller = typename Base::UI; + this->template cppFunction, Caller>("webfront.inspector.containers", [trust = this->trustsLoopbackClients()](Caller ui) { + return developer::inspectorContainers(Base::canShowSecondaryWindow(), ui.isLocalClient(), trust); + }); +#endif } /// Registers a store operation as a bridge callback; the store stays alive as long as the callback. diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index dcb15050..4fb7115f 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1488,6 +1488,12 @@ class BasicWF { windowOptions.background = "#141821"; } + /// Whether the application chose WebFrontConfig::trustLoopbackClients: a new connection that is not proven would then + /// be a local client when its peer is the loopback (the inspectors' containers, ADR-027 section 8). + [[nodiscard]] bool trustsLoopbackClients() const noexcept { + return trustLoopbackClients; + } + private: // The constructor has already bound and listened; this thread services the queued I/O. // Launch server only once or restart if previous thread ended diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index a789b3ab..5a7329ce 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -22,7 +22,8 @@ "js/developer/environment/development.mjs": "1f32f911610c72ad3e935de1c2b138fa275ce9eda04bb63c824d5e09923305a6", "js/developer/environment/testing.mjs": "aeb584505fab5957b9c02e78536e12f7d7f3d12f8adb2e17f1a1a6e395e43f3c", "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", - "js/developer/environment/workspace.mjs": "05d3474f1581eff1b41cea38318d20166e672997c2fec94d16ba8dd50edd09fb", + "js/developer/environment/workspace.mjs": "5af5ea2a9a27c403d60fe54c268ae07741cae8a89da2cc148e4f64114f2b71d7", + "js/developer/environment/menu.mjs": "9399a5d6a4c28cbf775713ae87e59de905a109d67034024abe03b81a5af9eeb4", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", @@ -45,7 +46,7 @@ "js/developer/starters/agent-guide.md": "45dcbcb06cd6c04e048a6fcb9eb4305efde169f97b1c2bafbcc8c127127077f0", "js/developer/starters/app/main.ts": "b4f43fd3cd9136d86dd3e6e89e29092ddf3b67066c2cc08d78078d15a445054e", "js/developer/starters/app/style.css": "6a042eff15ee9b1603c95d3e4e974a03876e1c365389553e84eb7c472aded180", - "js/developer/tools/distribution.json": "bdb27ea91159b1371c568a6fce3f851c5fd1ed44bafdc68f42ce2232198e3c92", + "js/developer/tools/distribution.json": "06c5e81e5fbbe3407488840646fb8dd1b36b540fca43dd85dcd5d7342261a36a", "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a577f4396ab867096bc6fe6876e16e5220121ec8e8dd234fa1e4819d0a1173e1", diff --git a/js/developer/environment/menu.mjs b/js/developer/environment/menu.mjs new file mode 100644 index 00000000..7fefec6a --- /dev/null +++ b/js/developer/environment/menu.mjs @@ -0,0 +1,432 @@ +// The context menu of the WebFront tab (#679, ADR-027): the terminal and the inspectors of the application's state. A +// click on the tab and the shortcut keep opening and collapsing the terminal; the menu opens with a right click, a long +// press on a touch screen, the Menu key or Shift+F10 on the tab. While it is closed it takes no key and no pointer from +// the interface: its listeners are on the tab, and on the page only while it is open. + +// --- Entries --------------------------------------------------------------------------------------------------- + +/** The inspector panels, by submenu; `id` is what the environment's inspector opens. */ +export const inspectorMenus = [ + {id: 'cpp', label: 'C++ state', children: [ + {id: 'cpp.functions', label: 'Functions'}, + {id: 'cpp.browsers', label: 'Browsers and tasks'}, + {id: 'cpp.watches', label: 'Watches'}, + ]}, + {id: 'typescript', label: 'TypeScript state', children: [ + {id: 'typescript.packages', label: 'Packages'}, + {id: 'typescript.bridge', label: 'Bridge'}, + ]}, +]; + +// --- Access to the inspectors ---------------------------------------------------------------------------------- + +/** The reserved function that says which containers would reach the inspectors; the only one that checks no access. */ +export const containersFunction = 'webfront.inspector.containers'; + +export const accessReasons = { + checking: 'Checking whether this page may open the inspectors…', + tooOld: 'The WebFront library of this application has no inspectors (webfront.inspector.*): update it.', + noContainer: 'The inspectors answer only a view of the application, and this page is not one: use an embedded frontend ' + + '(WebKitGTK, WKWebView, WebView2 or CEF), or set WebFrontConfig::trustLoopbackClients, knowing that any local ' + + 'process can then read the state of the application.', + noInspector: 'This version of the developer environment cannot open the inspectors yet.', +}; + +/** + * What the menu can offer from the answer of webfront.inspector.containers(), a tuple of three booleans + * (secondaryWindow, host, newConnections; ADR-027, section 8), or from the error of that call. `containers` is null when + * no container reaches the inspectors, and `reason` then says why. + * + * Every container needs the host page to be admitted: a secondary window is opened by an admitted page, the floating + * window borrows its bridge, and a tab of the system browser is admitted only by trustLoopbackClients, which admits a + * loopback page too. A page that is not admitted while new connections would be is not on the loopback, and neither + * would its tab be. + */ +export function inspectorAccess(answer, error = null) { + if (error) { + if (error?.code === 'webfront.notFound') return {containers: null, reason: accessReasons.tooOld}; + return {containers: null, reason: `The inspectors cannot be reached: ${error?.message ?? error}`}; + } + if (!Array.isArray(answer) || answer.length !== 3 || !answer.every(value => typeof value === 'boolean')) + return {containers: null, reason: 'The inspectors gave an answer that this environment does not read.'}; + const [secondaryWindow, host, newConnections] = answer; + if (!host) return {containers: null, reason: accessReasons.noContainer}; + return {containers: {secondaryWindow, host, newConnections}, reason: ''}; +} + +/** Asks C++ once which containers would reach the inspectors. */ +export async function readInspectorAccess(bridge) { + try { return inspectorAccess(await bridge.cppFunction(containersFunction)()); } + catch (error) { return inspectorAccess(null, error ?? new Error('unknown error')); } +} + +// --- Geometry -------------------------------------------------------------------------------------------------- + +/** + * Where a menu of `size` opens beside `anchor` (a rectangle {left, top, right, bottom}; a point has left === right and + * top === bottom), inside the viewport: on the left of the anchor, since the tab is against the right edge, or on its + * right when the left has no room; level with the anchor's top, or ending at its bottom when the window has no room + * below. A menu larger than the viewport starts at its edge (the page scrolls the menu). + */ +export function placeMenu(anchor, size, viewport) { + const fitsLeft = anchor.left - size.width >= 0, fitsRight = anchor.right + size.width <= viewport.width; + const side = fitsLeft || !fitsRight ? 'left' : 'right'; + const x = side === 'left' ? anchor.left - size.width : anchor.right; + const y = anchor.top + size.height <= viewport.height ? anchor.top : anchor.bottom - size.height; + const within = (value, extent, room) => Math.round(Math.max(0, Math.min(value, room - extent))); + return {x: within(x, size.width, viewport.width), y: within(y, size.height, viewport.height), side}; +} + +/** + * Whether a key opens the menu of the focused tab: the Menu key, or Shift+F10 alone. On the tab they open its menu + * before the terminal's shortcut, which a manifest may set to Shift+F10 (workspace.mjs): a click, Enter or Space on the + * tab, and the menu's Terminal entry, still reach the terminal there. + */ +export const isMenuKey = event => event.key === 'ContextMenu' + || (event.key === 'F10' && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey); + +/** + * How long a touch stays on the tab before the menu opens instead of the terminal, how far it may move, and how long + * after the finger lifts the events of that touch (compatibility mouse events, click) are still its own. + */ +export const longPress = {delay: 550, distance: 10, settle: 1000}; + +// --- Menu ------------------------------------------------------------------------------------------------------ + +export const menuStyles = ` +.webfront-menu{position:fixed;z-index:2147483647;box-sizing:border-box;min-width:min(220px,100vw);max-width:min(360px,100vw);max-height:100vh;overflow:auto;padding:4px;background:#202737;color:#e8edf4;border:1px solid #46536a;border-radius:8px;box-shadow:0 8px 32px #000a;font:14px system-ui} +.webfront-menu[hidden]{display:none} +.webfront-menu [role=menu]{display:flex;flex-direction:column} +.webfront-menu-item{box-sizing:border-box;display:flex;align-items:center;gap:16px;width:100%;min-height:44px;margin:0;padding:0 12px;border:0;border-radius:4px;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer} +.webfront-menu-item>span:first-child{flex:1 1 auto} +.webfront-menu-item:focus{outline:none} +.webfront-menu-item:hover,.webfront-menu-item:focus-visible,.webfront-menu-item[aria-expanded=true]{background:#2f3a50} +.webfront-menu-item:focus-visible{outline:2px solid #d7fa85;outline-offset:-2px} +.webfront-menu-item[aria-disabled=true]{color:#8d97aa;cursor:default} +.webfront-menu-hint{color:#a9b3c4;font-size:12px} +.webfront-menu-reason{margin:4px 0 0;padding:8px 12px;border-top:1px solid #46536a;color:#c8cfdb;font-size:12px;line-height:1.4} +.webfront-menu-reason:empty{display:none} +`; + +let menus = 0; + +/** + * The menu of the tab `button`. `entries` are {id, label, hint?, children?, reason?()}: an entry with children opens a + * submenu, the others call `activate(id)`; `reason()` gives why an entry is unavailable ('' when it is available), read + * each time the menu or the submenu opens, and again by `menu.refresh()` when what it depends on changes while a panel + * is open. `menu.consumeClick()` tells the tab's click handler that a long press opened + * the menu, so that the click that ends it does not also toggle the terminal. + */ +export function createTabMenu({button, entries, activate}) { + const page = button.ownerDocument, view = page.defaultView; + const number = ++menus; + const levels = []; // the open panels, the root first: {panel, list, items, entries, parent} + let longTimer = null, pressed = null, lastPointer = null; + // After a long press opened the menu, until the click that ends the touch (or shortly after the finger lifts, for an + // engine that sends none): that click must not toggle the terminal, and the compatibility mouse events must not take + // the focus from the menu, which would close it. + let afterLongPress = false, longPressEnd = null; + const endLongPress = () => { + afterLongPress = false; + view.clearTimeout(longPressEnd); + longPressEnd = null; + }; + + const reasonOf = entry => (entry.reason?.() ?? '') || ''; + + function panelFor(list, parentItem, depth) { + const panel = page.createElement('div'); + panel.className = 'webfront-menu'; + panel.dataset.level = String(depth); + const menu = page.createElement('div'); + menu.setAttribute('role', 'menu'); + menu.id = `webfront-menu-${number}-${depth}`; + if (parentItem) menu.setAttribute('aria-labelledby', parentItem.id); + else menu.setAttribute('aria-label', 'WebFront'); + const note = page.createElement('p'); + note.className = 'webfront-menu-reason'; + note.id = `${menu.id}-reason`; + const reasons = []; + const items = list.map((entry, index) => { + const item = page.createElement('button'); + item.type = 'button'; + item.tabIndex = -1; + item.className = 'webfront-menu-item'; + item.id = `${menu.id}-${index}`; + item.setAttribute('role', 'menuitem'); + item.dataset.entry = entry.id; + const label = page.createElement('span'); + label.textContent = entry.label; + item.append(label); + if (entry.children) { + item.setAttribute('aria-haspopup', 'menu'); + item.setAttribute('aria-expanded', 'false'); + const arrow = page.createElement('span'); + arrow.setAttribute('aria-hidden', 'true'); + arrow.textContent = '▸'; + item.append(arrow); + } else if (entry.hint) { + const hint = page.createElement('span'); + hint.className = 'webfront-menu-hint'; + hint.textContent = entry.hint; + item.append(hint); + if (entry.keys) item.setAttribute('aria-keyshortcuts', entry.keys); + } + return item; + }); + menu.append(...items); + panel.append(menu, note); + const level = {panel, menu, note, items, entries: list, parent: parentItem}; + applyReasons(level); + return level; + } + + /** Greys the entries of a panel that are unavailable, with their reason, and enables the others. */ + function applyReasons({note, items, entries: list}) { + const reasons = []; + list.forEach((entry, index) => { + const item = items[index], reason = entry.children ? '' : reasonOf(entry); + if (reason) { + item.setAttribute('aria-disabled', 'true'); + item.setAttribute('aria-describedby', note.id); + item.title = reason; + if (!reasons.includes(reason)) reasons.push(reason); + } else { + item.removeAttribute('aria-disabled'); + item.removeAttribute('aria-describedby'); + item.removeAttribute('title'); + } + }); + note.textContent = reasons.join(' '); + } + + /** Places a panel beside its anchor (level.anchor()), inside the viewport, for the size it has now. */ + function place(level) { + const {panel} = level, anchor = level.anchor(); + panel.style.left = '0px'; + panel.style.top = '0px'; + const viewport = {width: page.documentElement.clientWidth, height: page.documentElement.clientHeight}; + const {x, y, side} = placeMenu(anchor, {width: panel.offsetWidth, height: panel.offsetHeight}, viewport); + panel.style.left = `${x}px`; + panel.style.top = `${y}px`; + panel.dataset.side = side; + } + + const isOpen = () => levels.length > 0; + const levelOf = element => levels.findIndex(level => level.panel.contains(element)); + + function closeFrom(depth) { + while (levels.length > depth) { + const level = levels.pop(); + level.panel.remove(); + level.parent?.setAttribute('aria-expanded', 'false'); + } + } + + function close({focus = true} = {}) { + if (!isOpen()) return; + closeFrom(0); + page.removeEventListener('pointerdown', outside, true); + page.removeEventListener('focusin', focusMoved, true); + view.removeEventListener('blur', windowLeft); + view.removeEventListener('resize', closeQuietly); + if (focus) button.focus(); + } + const closeQuietly = () => close({focus: false}); + + /** Opens the menu beside `anchor` (the tab's rectangle by default) with the focus on its first entry. */ + function open(anchor = button.getBoundingClientRect()) { + if (isOpen()) return; + const root = panelFor(entries, null, 0); + levels.push(root); + page.body.append(root.panel); + root.anchor = () => anchor; + place(root); + root.panel.addEventListener('keydown', onKey); + root.panel.addEventListener('click', onClick); + root.panel.addEventListener('pointerover', onHover); + page.addEventListener('pointerdown', outside, true); + page.addEventListener('focusin', focusMoved, true); + view.addEventListener('blur', windowLeft); + view.addEventListener('resize', closeQuietly); + root.items[0]?.focus(); + } + + function openSubmenu(item, {focus = true} = {}) { + const depth = levelOf(item), level = levels[depth]; + const entry = level.entries[level.items.indexOf(item)]; + if (!entry?.children) return; + if (levels[depth + 1]?.parent === item) { + if (focus) levels[depth + 1].items[0]?.focus(); + return; + } + closeFrom(depth + 1); + const sub = panelFor(entry.children, item, depth + 1); + levels.push(sub); + item.setAttribute('aria-controls', sub.menu.id); + item.setAttribute('aria-expanded', 'true'); + page.body.append(sub.panel); + // Beside its parent panel, level with its entry: read again each time it is placed, since the parent may move. + sub.anchor = () => { + const rect = item.getBoundingClientRect(), parentRect = level.panel.getBoundingClientRect(); + return {left: parentRect.left, right: parentRect.right, top: rect.top, bottom: rect.bottom}; + }; + place(sub); + sub.panel.addEventListener('keydown', onKey); + sub.panel.addEventListener('click', onClick); + sub.panel.addEventListener('pointerover', onHover); + if (focus) sub.items[0]?.focus(); + } + + function choose(item) { + const level = levels[levelOf(item)]; + const entry = level?.entries[level.items.indexOf(item)]; + if (!entry) return; + if (entry.children) { openSubmenu(item); return; } + if (item.getAttribute('aria-disabled') === 'true') return; // its reason stays on screen + close({focus: false}); + activate(entry.id); + } + + function onKey(event) { + const item = event.target.closest?.('.webfront-menu-item'); + const depth = levelOf(event.target); + if (depth < 0) return; + const {items} = levels[depth]; + const index = items.indexOf(item); + const move = to => items[(to + items.length) % items.length]?.focus(); + let handled = true; + switch (event.key) { + case 'ArrowDown': move(index + 1); break; + case 'ArrowUp': move(index < 0 ? -1 : index - 1); break; + case 'Home': move(0); break; + case 'End': move(-1); break; + case 'ArrowRight': + if (item?.hasAttribute('aria-haspopup')) openSubmenu(item); + break; + case 'ArrowLeft': + if (depth > 0) { + const parent = levels[depth].parent; + closeFrom(depth); + parent.focus(); + } + break; + case 'Escape': + close(); // every level, from a submenu too, with the focus back on the tab; the left arrow goes up one level + break; + case 'Enter': case ' ': + if (item) choose(item); + break; + case 'Tab': + // The menu closes and the focus goes back to the tab before the browser moves it: the default action is kept, + // so Tab goes on to the element after the tab and Shift+Tab to the one before, as from the tab itself. + close(); + event.stopPropagation(); + return; + default: handled = false; + } + if (!handled) return; + event.preventDefault(); + event.stopPropagation(); + } + + function onClick(event) { + const item = event.target.closest?.('.webfront-menu-item'); + if (item) choose(item); + } + + // A pointer that rests on an entry with a submenu opens it, and one on another entry of that menu closes it. + function onHover(event) { + if (event.pointerType === 'touch') return; + const item = event.target.closest?.('.webfront-menu-item'); + if (!item) return; + const depth = levelOf(item); + if (item.hasAttribute('aria-haspopup')) openSubmenu(item, {focus: false}); + else closeFrom(depth + 1); + item.focus(); + } + + // A press anywhere else closes it, on the tab too: the click that follows toggles the terminal as usual. + function outside(event) { + if (levelOf(event.target) < 0) closeQuietly(); + } + // The focus left the menu for another element of the page, or for the interface's frame (the window loses it). + function focusMoved(event) { + if (levelOf(event.target) >= 0) return; + // The tab took the focus from the touch that opened the menu: the menu keeps it. + if (afterLongPress && button.contains(event.target)) { levels[0]?.items[0]?.focus(); return; } + closeQuietly(); + } + function windowLeft() { closeQuietly(); } + + // --- Opening --- + button.setAttribute('aria-haspopup', 'menu'); + button.style.setProperty('-webkit-touch-callout', 'none'); + button.addEventListener('contextmenu', event => { + event.preventDefault(); + if (isOpen()) return; // already opened by the long press or the key that caused this event + // A right click opens the menu where it is; the Menu key and Shift+F10 beside the tab. + const atPointer = lastPointer && view.performance.now() - lastPointer.time < 1000; + open(atPointer ? {left: lastPointer.x, right: lastPointer.x, top: lastPointer.y, bottom: lastPointer.y} : undefined); + }); + button.addEventListener('keydown', event => { + if (!isMenuKey(event)) return; + event.preventDefault(); + event.stopPropagation(); + open(); + }); + const cancelPress = () => { + view.clearTimeout(longTimer); + longTimer = null; + pressed = null; + }; + button.addEventListener('pointerdown', event => { + endLongPress(); + if (event.pointerType === 'mouse' && event.button === 2 || event.pointerType !== 'mouse') + lastPointer = {x: event.clientX, y: event.clientY, time: view.performance.now()}; + if (event.pointerType === 'mouse') return; + cancelPress(); + pressed = {x: event.clientX, y: event.clientY}; + longTimer = view.setTimeout(() => { + longTimer = null; + afterLongPress = true; + open({left: pressed.x, right: pressed.x, top: pressed.y, bottom: pressed.y}); + }, longPress.delay); + }); + button.addEventListener('pointermove', event => { + if (pressed && Math.hypot(event.clientX - pressed.x, event.clientY - pressed.y) > longPress.distance) cancelPress(); + }); + button.addEventListener('pointerup', () => { + view.clearTimeout(longTimer); + longTimer = null; + if (afterLongPress && longPressEnd === null) longPressEnd = view.setTimeout(endLongPress, longPress.settle); + }); + // The mousedown that a touch engine sends after the finger lifts would move the focus to the tab: it is cancelled. + button.addEventListener('mousedown', event => { if (afterLongPress) event.preventDefault(); }); + // A cancelled pointer sends neither compatibility mouse events nor a click: the touch, long press included, is over. + button.addEventListener('pointercancel', () => { + cancelPress(); + endLongPress(); + }); + + return { + open, close, + /** + * Reads the reasons again for the panels that are open, which keep their focus. A reason may change their size: + * each one is placed again beside its anchor, the root first, so that a submenu follows a parent that moved. + */ + refresh() { + levels.forEach(applyReasons); + levels.forEach(place); + }, + get isOpen() { return isOpen(); }, + /** The panels shown, the root first. */ + get panels() { return levels.map(level => level.panel); }, + /** Whether the click that follows a long press must be ignored; reading it clears it. */ + consumeClick() { + const swallowed = afterLongPress; + endLongPress(); + return swallowed; + }, + }; +} diff --git a/js/developer/environment/workspace.mjs b/js/developer/environment/workspace.mjs index b415bcd4..5fbaf94d 100644 --- a/js/developer/environment/workspace.mjs +++ b/js/developer/environment/workspace.mjs @@ -1,9 +1,11 @@ // The layout of the developer page: the terminal alone while the project has no interface, then the interface over the // whole window with the terminal in a floating, movable window that a tab on the right edge opens and collapses. The terminal is mounted // once in its window and never moves in the document afterwards: collapsing only hides it, so the session, a running -// command, the line being typed and the scrollback are kept. The interface stays in the preview frame. +// command, the line being typed and the scrollback are kept. The interface stays in the preview frame. The tab also has a +// context menu (menu.mjs): the terminal and the inspectors of the application's state. import {call, readProject, publish} from './io.mjs'; import {parseShortcut, defaultTerminalShortcut, parseManifest, manifestPath} from './manifest.mjs'; +import {createTabMenu, inspectorMenus, readInspectorAccess, accessReasons, menuStyles, isMenuKey} from './menu.mjs'; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -200,7 +202,7 @@ ${floating} .webfront-terminal-bar{display:flex} @keyframes webfront-terminal-working{to{opacity:.35}} @media (prefers-reduced-motion:reduce){.webfront-terminal-status{animation:none!important}} :root[${attribute}=terminal] .webfront-terminal-toggle,:root[${attribute}=terminal] .webfront-interface{display:none} -`; +${menuStyles}`; const layouts = new WeakMap(); /** Whether a workspace already lays out this preview frame: a page has one, whatever the terminals mounted in it. */ @@ -216,8 +218,10 @@ export const layoutState = frame => layouts.get(frame)?.workspace?.state; * terminal opens in `element`, then attach({focus, fit}) with the functions that focus the terminal and fit it to `element`. * The result gives the `state`, `interfaceExists` (the page opened on an existing interface, to load in the frame), * the `status` shown on the tab and command(running) to say that a command runs, toggle(), open({focus}) and close(), `button` and `panel`, the `shortcut` in use ("F9") and placeSaved(). + * The tab's context menu (menu.mjs) is `menu`, and `inspectorAccess` resolves to what webfront.inspector.containers() + * allowed. `openInspector(panel)`, when given, opens an inspector panel; without it the menu says they cannot open yet. */ -export async function createWorkspace({bridge, element, frame}) { +export async function createWorkspace({bridge, element, frame, openInspector = null}) { const layout = {workspace: null}; layouts.set(frame, layout); const page = element.ownerDocument, view = page.defaultView, root = page.documentElement; @@ -229,6 +233,8 @@ export async function createWorkspace({bridge, element, frame}) { let place = remembered; // as chosen; what is displayed is fitted to the viewport let focusTerminal = () => {}, fitTerminal = () => {}; const session = {command: false, dev: null}; + // Asked once: whether this page may reach the inspectors does not change while its connection lives. + let access = null; const style = page.createElement('style'); style.textContent = styles; @@ -272,6 +278,7 @@ export async function createWorkspace({bridge, element, frame}) { const shown = () => clampRect(place ?? defaultRect(viewport()), viewport()); function render() { root.setAttribute(attribute, state); + if (state === State.terminal) menu.close({focus: false}); // the tab is hidden with the interface const open = state === State.floating; button.setAttribute('aria-expanded', String(open)); const status = tabStatus(session), words = statusText(status); @@ -298,7 +305,28 @@ export async function createWorkspace({bridge, element, frame}) { else focusTerminal(); } - button.addEventListener('click', () => apply('toggle')); + // The context menu: the terminal, and the inspectors when this page reaches them (ADR-027, section 8). + const inspectorReason = () => !access ? accessReasons.checking : access.reason || (openInspector ? '' : accessReasons.noInspector); + const menu = createTabMenu({ + button, + entries: [ + {id: 'terminal', label: 'Terminal', hint: keys, keys: keys.replace('Ctrl', 'Control')}, + ...inspectorMenus.map(group => ({...group, children: group.children.map(panel => ({...panel, reason: inspectorReason}))})), + ], + activate: id => { + if (id === 'terminal') { + if (state === State.floating) focusTerminal(); else apply('open'); + } else if (!inspectorReason()) openInspector(id); + }, + }); + + const inspectorAccess = readInspectorAccess(bridge).then(result => { + access = result; + menu.refresh(); // a submenu opened while C++ was asked still says it is checking + return result; + }); + // A long press that opened the menu ends with a click: it does not also toggle the terminal. + button.addEventListener('click', () => { if (!menu.consumeClick()) apply('toggle'); }); closeButton.addEventListener('click', () => apply('close')); // Only a published preview loaded in the frame is an interface. wf dev also unhides the frame to show the diagnostic // of a failed build: before any preview, the frame stays out of the page and the terminal, which prints the @@ -314,8 +342,11 @@ export async function createWorkspace({bridge, element, frame}) { // The listener is the first of its window (below), so the application's ones never see the shortcut. const onKey = event => { if (!isToggleKey(event, shortcut) || state === State.terminal) return; + // On the focused tab, a shortcut that is also a menu key (Shift+F10 in the manifest) opens the tab's menu. + if (event.target === button && isMenuKey(event)) return; event.preventDefault(); event.stopImmediatePropagation(); + menu.close({focus: false}); apply('toggle'); }; view.addEventListener('keydown', onKey, true); @@ -393,7 +424,7 @@ export async function createWorkspace({bridge, element, frame}) { session.command = Boolean(running); render(); }, - interfaceExists, button, panel, bar, shortcut: keys, + interfaceExists, button, panel, bar, shortcut: keys, menu, inspectorAccess, attach({focus, fit = () => {}}) { focusTerminal = focus; fitTerminal = fit; diff --git a/js/developer/tools/bundle-inputs.json b/js/developer/tools/bundle-inputs.json index 990500e2..5c1b0560 100644 --- a/js/developer/tools/bundle-inputs.json +++ b/js/developer/tools/bundle-inputs.json @@ -23,6 +23,7 @@ "js/developer/environment/testing.mjs", "js/developer/environment/terminal.mjs", "js/developer/environment/workspace.mjs", + "js/developer/environment/menu.mjs", "js/developer/environment/tarball.mjs", "js/developer/environment/commands.mjs", "js/developer/environment/files.mjs", diff --git a/js/developer/tools/distribution.json b/js/developer/tools/distribution.json index 4acc5bb7..4f71ef2e 100644 --- a/js/developer/tools/distribution.json +++ b/js/developer/tools/distribution.json @@ -1,4 +1,4 @@ { - "version": "1.2.0", + "version": "1.2.1", "baseUrl": "https://dist.webfront.fr/" } diff --git a/test/developer/specs/workspace-specs.mjs b/test/developer/specs/workspace-specs.mjs index 0ce5a442..3b7bec85 100644 --- a/test/developer/specs/workspace-specs.mjs +++ b/test/developer/specs/workspace-specs.mjs @@ -1,8 +1,11 @@ // Specs of the developer page's layout (workspace.mjs): what counts as an existing interface, the states of the display, // and the place of the floating terminal window. The page itself is checked in test/web/developer-specs.mjs. import {hasInterface, previewDirectory, State, initialState, nextState, clampRect, defaultRect, keyboardRect, minimumSize, step, - isToggleKey, Status, tabStatus, statusText, defaultShortcut, shortcutText, readShortcut, parsePlace, formatPlace, readPlace, placeStore, placePath} from '../../../js/developer/environment/workspace.mjs'; + isToggleKey, Status, tabStatus, statusText, defaultShortcut, shortcutText, readShortcut, parsePlace, formatPlace, readPlace, placeStore, placePath, + createWorkspace} from '../../../js/developer/environment/workspace.mjs'; import {publish} from '../../../js/developer/environment/io.mjs'; +import {inspectorAccess, readInspectorAccess, accessReasons, containersFunction, placeMenu, createTabMenu, longPress, inspectorMenus, + menuStyles} from '../../../js/developer/environment/menu.mjs'; import {memoryBridge} from '../memory-bridge.mjs'; describe('The developer page layout', () => { @@ -184,4 +187,467 @@ describe('The developer page layout', () => { await expectAsync(store.saved()).toBeResolved(); }); }); + + describe('tab menu', () => { + describe('access to the inspectors', () => { + it('is open to an admitted page, whatever the container', () => { + expect(inspectorAccess([true, true, false])).toEqual({containers: {secondaryWindow: true, host: true, newConnections: false}, reason: ''}); + expect(inspectorAccess([false, true, true]).containers).toEqual({secondaryWindow: false, host: true, newConnections: true}); + }); + + it('names no container to a page that is not admitted, and says how to admit one', () => { + for (const answer of [[false, false, false], [false, false, true]]) { + const access = inspectorAccess(answer); + expect(access.containers).toBeNull(); + expect(access.reason).toBe(accessReasons.noContainer); + } + expect(accessReasons.noContainer).toContain('trustLoopbackClients'); + expect(accessReasons.noContainer).toContain('embedded frontend'); + }); + + it('tells a library without inspectors from a bridge that fails', () => { + expect(inspectorAccess(null, Object.assign(new Error('not found'), {code: 'webfront.notFound'})).reason).toBe(accessReasons.tooOld); + expect(inspectorAccess(null, new Error('connection lost')).reason).toContain('connection lost'); + expect(inspectorAccess(['yes', true, true]).containers).toBeNull(); + expect(inspectorAccess([true, true]).containers).toBeNull(); + }); + + it('asks the reserved function once', async () => { + const asked = []; + const bridge = answer => ({cppFunction: name => async () => { asked.push(name); return answer(); }}); + expect((await readInspectorAccess(bridge(() => [false, true, false]))).containers?.host).toBeTrue(); + expect((await readInspectorAccess(bridge(() => { throw Object.assign(new Error('no'), {code: 'webfront.notFound'}); }))).reason) + .toBe(accessReasons.tooOld); + expect(asked).toEqual([containersFunction, containersFunction]); + }); + }); + + describe('place', () => { + const viewport = {width: 1000, height: 600}, size = {width: 240, height: 200}; + const tab = {left: 956, right: 1000, top: 64, bottom: 152}; + + it('opens on the left of the tab, level with its top', () => { + expect(placeMenu(tab, size, viewport)).toEqual({x: 716, y: 64, side: 'left'}); + }); + + it('opens on the right of an anchor with no room on its left, and ends at its bottom near the window\'s', () => { + expect(placeMenu({left: 100, right: 300, top: 500, bottom: 540}, size, viewport)).toEqual({x: 300, y: 340, side: 'right'}); + }); + + it('stays inside a window smaller than the menu', () => { + const placed = placeMenu({left: 200, right: 200, top: 90, bottom: 90}, size, {width: 280, height: 140}); + expect(placed.x).toBe(0); + expect(placed.y).toBe(0); + expect(placeMenu(tab, {width: 2000, height: 50}, viewport)).toEqual({x: 0, y: 64, side: 'left'}); + }); + }); + + describe('on the page', () => { + let style, button, activated, menu, reason; + const key = (target, init) => target.dispatchEvent(new KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init})); + const items = (level = 0) => [...menu.panels[level].querySelectorAll('[role=menuitem]')]; + const labels = level => items(level).map(item => item.firstChild.textContent); + + beforeEach(() => { + style = document.createElement('style'); + style.textContent = menuStyles; + document.head.append(style); + button = document.createElement('button'); + button.textContent = 'tab'; + button.style.cssText = 'position:fixed;right:0;top:64px;width:44px;height:88px'; + document.body.append(button); + activated = []; + reason = 'Not here.'; + menu = createTabMenu({button, activate: id => activated.push(id), entries: [ + {id: 'terminal', label: 'Terminal', hint: 'F9', keys: 'F9'}, + ...inspectorMenus.map(group => ({...group, children: group.children.map(panel => ({...panel, reason: () => reason}))})), + ]}); + button.addEventListener('click', () => { if (!menu.consumeClick()) activated.push('click'); }); + }); + afterEach(() => { + menu.close({focus: false}); + button.remove(); + style.remove(); + }); + + it('opens with a right click, on a menu that names its entries, and leaves the click to the terminal', () => { + expect(button.getAttribute('aria-haspopup')).toBe('menu'); + expect(menu.isOpen).toBeFalse(); + const event = new MouseEvent('contextmenu', {bubbles: true, cancelable: true, button: 2, clientX: 980, clientY: 100}); + expect(button.dispatchEvent(event)).toBeFalse(); // the browser's own menu does not open + expect(menu.isOpen).toBeTrue(); + expect(menu.panels[0].querySelector('[role=menu]')).not.toBeNull(); + expect(labels(0)).toEqual(['Terminal', 'C++ state', 'TypeScript state']); + expect(items(0)[1].getAttribute('aria-haspopup')).toBe('menu'); + expect(items(0)[0].getAttribute('aria-keyshortcuts')).toBe('F9'); + expect(document.activeElement).toBe(items(0)[0]); + expect(items(0).every(item => item.getBoundingClientRect().height >= 44)).toBeTrue(); + const box = menu.panels[0].getBoundingClientRect(); + expect(box.right).toBeLessThanOrEqual(document.documentElement.clientWidth + 0.5); + expect(box.left).toBeGreaterThanOrEqual(0); + button.click(); // a click still toggles the terminal + expect(activated).toEqual(['click']); + }); + + it('opens with the Menu key and Shift+F10, and is driven with the arrows', () => { + button.focus(); + key(button, {key: 'F10'}); + expect(menu.isOpen).toBeFalse(); + key(button, {key: 'F10', shiftKey: true}); + expect(menu.isOpen).toBeTrue(); + menu.close(); + expect(document.activeElement).toBe(button); + key(button, {key: 'ContextMenu'}); + expect(menu.isOpen).toBeTrue(); + const [terminal, cpp, typescript] = items(0); + key(terminal, {key: 'ArrowDown'}); + expect(document.activeElement).toBe(cpp); + key(cpp, {key: 'ArrowUp'}); + key(terminal, {key: 'ArrowUp'}); + expect(document.activeElement).toBe(typescript); // it wraps + key(typescript, {key: 'Home'}); + expect(document.activeElement).toBe(terminal); + key(terminal, {key: 'End'}); + key(typescript, {key: 'ArrowUp'}); + key(cpp, {key: 'ArrowRight'}); + expect(cpp.getAttribute('aria-expanded')).toBe('true'); + expect(labels(1)).toEqual(['Functions', 'Browsers and tasks', 'Watches']); + expect(menu.panels[1].querySelector('[role=menu]').getAttribute('aria-labelledby')).toBe(cpp.id); + expect(document.activeElement).toBe(items(1)[0]); + key(items(1)[0], {key: 'ArrowLeft'}); + expect(menu.panels.length).toBe(1); + expect(document.activeElement).toBe(cpp); + key(cpp, {key: 'Escape'}); + expect(menu.isOpen).toBeFalse(); + expect(document.activeElement).toBe(button); + // From a submenu, at any entry, Escape closes every level at once and gives the focus back to the tab. + for (const group of [1, 2]) { + key(button, {key: 'ContextMenu'}); + key(items(0)[group], {key: 'Enter'}); + expect(menu.panels.length).toBe(2); + const last = items(1).at(-1); + key(last, {key: 'End'}); + key(last, {key: 'Escape'}); + expect(menu.isOpen).withContext(`group ${group}`).toBeFalse(); + expect(document.querySelector('.webfront-menu')).toBeNull(); + expect(document.activeElement).toBe(button); + } + }); + + it('greys an unavailable entry with its reason, and does nothing when it is chosen', () => { + button.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})); + key(items(0)[2], {key: 'ArrowRight'}); + expect(labels(1)).toEqual(['Packages', 'Bridge']); + const note = menu.panels[1].querySelector('.webfront-menu-reason'); + expect(note.textContent).toBe('Not here.'); + for (const item of items(1)) { + expect(item.getAttribute('aria-disabled')).toBe('true'); + expect(item.getAttribute('aria-describedby')).toBe(note.id); + expect(item.title).toBe('Not here.'); + } + key(items(1)[0], {key: 'Enter'}); + items(1)[1].click(); + expect(activated).toEqual([]); + expect(menu.isOpen).toBeTrue(); + // The reasons are read each time a submenu opens. + reason = ''; + key(items(1)[0], {key: 'ArrowLeft'}); + key(items(0)[2], {key: 'ArrowRight'}); + expect(items(1).some(item => item.hasAttribute('aria-disabled'))).toBeFalse(); + expect(getComputedStyle(menu.panels[1].querySelector('.webfront-menu-reason')).display).toBe('none'); + key(items(1)[1], {key: 'Enter'}); + expect(activated).toEqual(['typescript.bridge']); + expect(menu.isOpen).toBeFalse(); + }); + + it('activates the terminal, and closes on a press elsewhere without taking the focus', () => { + button.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})); + key(items(0)[0], {key: ' '}); + expect(activated).toEqual(['terminal']); + expect(menu.isOpen).toBeFalse(); + const field = document.createElement('input'); + document.body.append(field); + try { + button.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})); + document.body.dispatchEvent(new PointerEvent('pointerdown', {bubbles: true})); + expect(menu.isOpen).toBeFalse(); + button.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})); + field.focus(); + // A window without the system's focus moves the focus without sending focusin: the spec sends it. + field.dispatchEvent(new FocusEvent('focusin', {bubbles: true})); + expect(menu.isOpen).toBeFalse(); + expect(document.activeElement).toBe(field); + } finally { field.remove(); } + }); + + it('reads the reasons again on refresh, in the panels already open', () => { + button.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true})); + key(items(0)[1], {key: 'ArrowRight'}); + const [panel, first] = [menu.panels[1], items(1)[0]]; + expect(first.getAttribute('aria-disabled')).toBe('true'); + reason = ''; + menu.refresh(); + expect(menu.panels[1]).toBe(panel); + expect(document.activeElement).toBe(first); + expect(items(1).some(item => item.hasAttribute('aria-disabled') || item.hasAttribute('aria-describedby') || item.title)).toBeFalse(); + expect(panel.querySelector('.webfront-menu-reason').textContent).toBe(''); + reason = 'Gone.'; + menu.refresh(); + expect(items(1).every(item => item.getAttribute('aria-disabled') === 'true' && item.title === 'Gone.')).toBeTrue(); + expect(panel.querySelector('.webfront-menu-reason').textContent).toBe('Gone.'); + expect(items(0).some(item => item.hasAttribute('aria-disabled'))).toBeFalse(); // the groups stay available + }); + + it('places the open panels again when a longer reason makes them taller, near the bottom of the window', () => { + const height = document.documentElement.clientHeight, width = document.documentElement.clientWidth; + const inside = panel => { + const box = panel.getBoundingClientRect(); + return box.top >= 0 && box.bottom <= height + 0.5 && box.left >= 0 && box.right <= width + 0.5; + }; + reason = 'Wait.'; + menu.open({left: width - 44, right: width, top: height - 88, bottom: height}); + key(items(0)[2], {key: 'ArrowRight'}); + const [root, submenu] = menu.panels, before = submenu.getBoundingClientRect().height; + expect(inside(root) && inside(submenu)).toBeTrue(); + reason = 'A reason long enough to take several lines in the submenu. '.repeat(4); + menu.refresh(); + expect(submenu.getBoundingClientRect().height).toBeGreaterThan(before + 20); + expect(menu.panels).toEqual([root, submenu]); + expect(inside(root) && inside(submenu)).withContext(JSON.stringify(submenu.getBoundingClientRect())).toBeTrue(); + expect(document.activeElement).toBe(items(1)[0]); + }); + + it('leaves the menu with Tab and Shift+Tab, from the tab, in the direction asked', () => { + for (const shiftKey of [false, true]) { + for (const depth of [0, 1]) { + button.focus(); + key(button, {key: 'ContextMenu'}); + if (depth) key(items(0)[1], {key: 'ArrowRight'}); + const from = document.activeElement; + const tab = new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: 'Tab', shiftKey}); + from.dispatchEvent(tab); + // The browser moves the focus after the event, from the element that has it then: the tab. + expect(tab.defaultPrevented).withContext(`shift ${shiftKey}, level ${depth}`).toBeFalse(); + expect(menu.isOpen).toBeFalse(); + expect(document.querySelector('.webfront-menu')).toBeNull(); + expect(document.activeElement).toBe(button); + } + } + }); + + it('takes no key while it is closed', () => { + const seen = []; + const listener = event => seen.push(event.key); + window.addEventListener('keydown', listener); + try { + for (const name of ['Escape', 'ArrowDown', 'Enter']) key(document.body, {key: name}); + expect(seen).toEqual(['Escape', 'ArrowDown', 'Enter']); + } finally { window.removeEventListener('keydown', listener); } + }); + + it('opens with a long press on a touch screen, without toggling the terminal', () => { + jasmine.clock().install(); + try { + const touch = (type, x = 980, y = 100) => button.dispatchEvent(new PointerEvent(type, {bubbles: true, pointerType: 'touch', clientX: x, clientY: y})); + touch('pointerdown'); + jasmine.clock().tick(longPress.delay - 1); + expect(menu.isOpen).toBeFalse(); + jasmine.clock().tick(1); + expect(menu.isOpen).toBeTrue(); + touch('pointerup'); + button.click(); + expect(activated).toEqual([]); + menu.close(); + // A short tap is a click; a press that moves is not a long press. + touch('pointerdown'); + touch('pointerup'); + button.click(); + expect(activated).toEqual(['click']); + touch('pointerdown'); + touch('pointermove', 980, 100 + longPress.distance + 5); + jasmine.clock().tick(longPress.delay * 2); + expect(menu.isOpen).toBeFalse(); + } finally { jasmine.clock().uninstall(); } + }); + + it('ends the long press when its pointer is cancelled after the menu opened', () => { + jasmine.clock().install(); + try { + const touch = type => button.dispatchEvent(new PointerEvent(type, {bubbles: true, pointerType: 'touch', clientX: 980, clientY: 100})); + touch('pointerdown'); + jasmine.clock().tick(longPress.delay); + expect(menu.isOpen).toBeTrue(); + touch('pointercancel'); // no pointerup, no click: nothing else comes from this touch + // The tab is a tab again at once, with no delay to wait for. + expect(button.dispatchEvent(new MouseEvent('mousedown', {bubbles: true, cancelable: true}))).toBeTrue(); + button.focus(); + button.dispatchEvent(new FocusEvent('focusin', {bubbles: true})); + expect(menu.isOpen).toBeFalse(); + expect(document.activeElement).toBe(button); + button.click(); // Enter or Space on the tab + expect(activated).toEqual(['click']); + } finally { jasmine.clock().uninstall(); } + }); + + it('stays open after a long press when the engine sends mouse events once the finger lifts', () => { + jasmine.clock().install(); + try { + const touch = type => button.dispatchEvent(new PointerEvent(type, {bubbles: true, pointerType: 'touch', clientX: 980, clientY: 100})); + const mouseDown = () => button.dispatchEvent(new MouseEvent('mousedown', {bubbles: true, cancelable: true})); + touch('pointerdown'); + jasmine.clock().tick(longPress.delay); + touch('pointerup'); + const first = items(0)[0]; + expect(document.activeElement).toBe(first); + // The compatibility mousedown does not move the focus, and an engine that moves it anyway gives it back. + expect(mouseDown()).toBeFalse(); + button.focus(); + button.dispatchEvent(new FocusEvent('focusin', {bubbles: true})); + expect(menu.isOpen).toBeTrue(); + expect(document.activeElement).toBe(first); + button.click(); + expect(menu.isOpen).toBeTrue(); + expect(activated).toEqual([]); + // Once that touch is over, the tab is a tab again: a press closes the menu, a mousedown is the browser's. + expect(mouseDown()).toBeTrue(); + menu.close({focus: false}); + // An engine that sends no click: the touch is over shortly after the finger lifts. + touch('pointerdown'); + jasmine.clock().tick(longPress.delay); + touch('pointerup'); + jasmine.clock().tick(longPress.settle); + expect(mouseDown()).toBeTrue(); + button.focus(); + button.dispatchEvent(new FocusEvent('focusin', {bubbles: true})); + expect(menu.isOpen).toBeFalse(); + button.click(); + expect(activated).toEqual(['click']); + } finally { jasmine.clock().uninstall(); } + }); + }); + + // A workspace of this page on a project in memory, whose webfront.inspector.containers() answers `containers`. + const press = (target, init) => target.dispatchEvent(new KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init})); + async function testWorkspace({files = new Map(), containers = Promise.resolve([false, true, false])} = {}) { + const {bridge: projectBridge} = memoryBridge(files); + const bridge = {cppFunction: name => name === containersFunction ? () => containers : projectBridge.cppFunction(name)}; + const element = document.createElement('div'), frame = document.createElement('iframe'); + frame.hidden = true; + document.body.append(element, frame); + const workspace = await createWorkspace({bridge, element, frame, openInspector: () => {}}); + const remove = async () => { + workspace.menu.close({focus: false}); + frame.hidden = true; // the layout goes back to the terminal alone: its listeners on this window do nothing + await new Promise(resolve => setTimeout(resolve)); + [workspace.panel, workspace.button, frame].forEach(node => node.remove()); + document.head.querySelectorAll('style').forEach(style => { if (style.textContent.includes('.webfront-terminal-toggle')) style.remove(); }); + document.documentElement.removeAttribute('data-webfront-workspace'); + }; + return {workspace, frame, remove}; + } + + describe('with Shift+F10 as the terminal\'s shortcut', () => { + let mounted; + beforeEach(async () => { + const manifest = encode(JSON.stringify({format: 1, name: 'app', version: '0.1.0', developer: {terminalShortcut: 'Shift+F10'}})); + const files = new Map([['webfront.project.json', manifest], [`${previewDirectory}/index.html`, encode('

app')]]); + mounted = await testWorkspace({files}); + }); + afterEach(() => mounted.remove()); + + it('opens the menu of the focused tab, and toggles the terminal anywhere else', () => { + const {workspace} = mounted; + expect(workspace.shortcut).toBe('Shift+F10'); + expect(workspace.state).toBe(State.interface); + workspace.button.focus(); + press(workspace.button, {key: 'F10', shiftKey: true}); + expect(workspace.menu.isOpen).toBeTrue(); + expect(workspace.state).toBe(State.interface); + // In the menu, the shortcut is the terminal's again: it closes the menu and opens the terminal. + press(document.activeElement, {key: 'F10', shiftKey: true}); + expect(workspace.menu.isOpen).toBeFalse(); + expect(workspace.state).toBe(State.floating); + press(document.body, {key: 'F10', shiftKey: true}); + expect(workspace.state).toBe(State.interface); + expect(workspace.menu.isOpen).toBeFalse(); + // From the tab, the terminal is still a click (Enter or Space) away. + workspace.button.click(); + expect(workspace.state).toBe(State.floating); + }); + }); + + it('fits a window narrower than its usual width', async () => { + const host = document.createElement('iframe'); + host.style.cssText = 'position:fixed;left:0;top:0;width:180px;height:400px;border:0'; + const loaded = new Promise(resolve => host.addEventListener('load', resolve, {once: true})); + host.srcdoc = ''; + document.body.append(host); + await loaded; + try { + const page = host.contentDocument, style = page.createElement('style'), tab = page.createElement('button'); + style.textContent = menuStyles; + tab.style.cssText = 'position:fixed;right:0;top:64px;width:44px;height:88px'; + page.head.append(style); + page.body.append(tab); + const narrow = createTabMenu({button: tab, activate: () => {}, entries: [ + {id: 'terminal', label: 'Terminal', hint: 'F9'}, + ...inspectorMenus.map(group => ({...group, children: group.children.map(panel => ({...panel, reason: () => accessReasons.noContainer}))})), + ]}); + narrow.open(); + press(page.activeElement, {key: 'ArrowDown'}); + press(page.activeElement, {key: 'ArrowRight'}); + expect(narrow.panels.length).toBe(2); + for (const panel of narrow.panels) { + const box = panel.getBoundingClientRect(); + expect(box.left >= 0 && box.right <= 180.5 && box.width <= 180).withContext(JSON.stringify(box)).toBeTrue(); + } + narrow.close({focus: false}); + } finally { host.remove(); } + }); + + describe('with an answer of C++ that comes after the submenu opened', () => { + let mounted, workspace, answer; + + beforeEach(async () => { + mounted = await testWorkspace({containers: new Promise(resolve => { answer = resolve; })}); + workspace = mounted.workspace; + }); + afterEach(() => mounted.remove()); + // Opens the submenu of `group` (1: C++ state, 2: TypeScript state) while C++ has not answered yet. + const openSubmenu = (group, anchor) => { + workspace.menu.open(anchor); + press(workspace.menu.panels[0].querySelectorAll('[role=menuitem]')[group], {key: 'ArrowRight'}); + const submenu = workspace.menu.panels[1]; + expect(submenu.querySelector('.webfront-menu-reason').textContent).toBe(accessReasons.checking); + return submenu; + }; + + it('enables the entries of an admitted page', async () => { + const submenu = openSubmenu(1), entries = [...submenu.querySelectorAll('[role=menuitem]')]; + expect(entries.every(entry => entry.getAttribute('aria-disabled') === 'true')).toBeTrue(); + answer([false, true, false]); + await workspace.inspectorAccess; + expect(workspace.menu.panels[1]).toBe(submenu); + expect(submenu.querySelector('.webfront-menu-reason').textContent).toBe(''); + expect(entries.some(entry => entry.hasAttribute('aria-disabled'))).toBeFalse(); + }); + + it('keeps a submenu opened near the bottom of the window inside it once its reason is longer', async () => { + const height = document.documentElement.clientHeight, width = document.documentElement.clientWidth; + const submenu = openSubmenu(2, {left: width - 44, right: width, top: height - 88, bottom: height}); + const before = submenu.getBoundingClientRect(); + expect(before.bottom).toBeLessThanOrEqual(height + 0.5); + answer([false, false, false]); // a page that is not admitted: the longest reason + await workspace.inspectorAccess; + const after = submenu.getBoundingClientRect(); + expect(submenu.querySelector('.webfront-menu-reason').textContent).toBe(accessReasons.noContainer); + expect(after.height).toBeGreaterThan(before.height); + expect(after.top >= 0 && after.bottom <= height + 0.5).withContext(JSON.stringify(after)).toBeTrue(); + for (const panel of workspace.menu.panels) { + const box = panel.getBoundingClientRect(); + expect(box.left >= 0 && box.right <= width + 0.5 && box.top >= 0 && box.bottom <= height + 0.5).toBeTrue(); + } + }); + }); + }); }); diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index aef299a8..95234207 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -496,6 +496,13 @@ add_test(NAME AutomationAbsentFromDistribution COMMAND "${CMAKE_COMMAND}" --build "${CMAKE_BINARY_DIR}" --target automation_distribution_guard --config $) set_tests_properties(AutomationAbsentFromDistribution PROPERTIES PASS_REGULAR_EXPRESSION "does not exist in a distribution build") +# The inspectors do not exist in a distribution build either (ADR-027, section 1): a bootstrapped developer application +# compiled with WEBFRONT_DISTRIBUTION registers no webfront.inspector.* function. +add_executable(inspector_distribution Main.cpp InspectorDistribution.cpp) +target_link_libraries(inspector_distribution PRIVATE WebFront WebFront::Bdd WebFront_test_hardening WebFront_warnings WebFront_options) +target_compile_definitions(inspector_distribution PRIVATE WEBFRONT_DISTRIBUTION=1) +add_test(NAME InspectorsAbsentFromDistribution COMMAND inspector_distribution) + # A project outside WebFront finds the installed WebFrontBdd package, writes scenarios and has CTest discover them (#647). # Only the top-level project installs the package, so only it can run this check. if(WEBFRONT_IS_TOP_LEVEL) diff --git a/test/unit/InspectorDistribution.cpp b/test/unit/InspectorDistribution.cpp new file mode 100644 index 00000000..dab5658f --- /dev/null +++ b/test/unit/InspectorDistribution.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-25 +// +// WebFront — tests/unit +// Role: A distribution build has no inspector function, even with the developer environment bootstrapped (ADR-027). +// Thread: ui-loop | Alloc: heap-init +// LLM: compiled with WEBFRONT_DISTRIBUTION=1 by the InspectorsAbsentFromDistribution test; exit status is the verdict + +#include "TemporaryDirectory.hpp" +#include +#include + +#if !(defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION) + #error "This test checks a distribution build: compile it with WEBFRONT_DISTRIBUTION=1" +#endif + +using namespace webfront::bdd; +using namespace webfront; + +namespace { +struct QuietFrontend { + static constexpr frontend::Action action{frontend::Action::keepServerRunning}; + static void initialize() { } + static void open(std::string_view, std::string_view) { } +}; +} // namespace + +const Scenario inspectorsAbsent{"A distribution build registers no inspector function (ADR-027, section 1)", [] { + given("a developer application bootstrapped in a distribution build", [&] { + webfront::test::TemporaryDirectory project; + BasicDeveloperApp app(project.path(), WebFrontConfig{.port = "0"}); + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); + then("the environment's callbacks exist, and no webfront.inspector.* function", [&] { + require(app.hasCppFunction("webfront.developer.config")); + require(!app.hasCppFunction("webfront.inspector.containers")); + }); + }); + }}; diff --git a/test/unit/ViewAssociationTests.cpp b/test/unit/ViewAssociationTests.cpp index fcde579e..c704b4ad 100644 --- a/test/unit/ViewAssociationTests.cpp +++ b/test/unit/ViewAssociationTests.cpp @@ -10,6 +10,8 @@ // A connection proves it comes from the view of an embedded frontend by the secret of the launch (#453, ADR-020). #include "InjectableNetworking.hpp" +#include "TemporaryDirectory.hpp" +#include #include #include #include @@ -21,6 +23,7 @@ #include #include #include +#include #include using namespace webfront::bdd; @@ -60,15 +63,16 @@ struct ViewVerdict { }; // Connects one browser whose handshake carries `proof` after its two header bytes, and reports what the UI says. -ViewVerdict connect(ViewApp& app, const std::string& proof) { +template +ViewVerdict connect(Application& app, const std::string& proof, const std::string& request = viewUpgradeRequest) { ViewVerdict verdict; bool started = false; - app.onUIStarted([&](ViewApp::UI ui) { + app.onUIStarted([&](typename Application::UI ui) { verdict.embedded = ui.isEmbeddedView(); verdict.local = ui.isLocalClient(); started = true; }); - ViewSocket::receive(std::as_bytes(std::span(viewUpgradeRequest))); + ViewSocket::receive(std::as_bytes(std::span(request))); msg::Handshake handshake; std::vector payload(handshake.header().begin(), handshake.header().end()); for (const char c : proof) @@ -274,3 +278,116 @@ const Scenario handshakeSecret{"The handshake's secret never reaches the diagnos }); log::removeSinks(sink); }}; + +namespace { +/// A frontend that opens no secondary window: the developer environment's own frontend in these tests. +struct InspectorQuietFrontend { + static constexpr frontend::Action action{frontend::Action::keepServerRunning}; + static void initialize() { } + static void open(std::string_view, std::string_view) { } +}; +using InspectorApp = DeveloperAppWithNetwork; + +/// The browser calls a function without argument; the answer is among the socket's writes. +void callWithoutArgument(const std::string& name, msg::CallId callId) { + msg::FunctionCall<> message; + message.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(name, frame); + frame.freeze(); + ViewSocket::receive(testing::clientFrame(testing::messagePayload(frame))); +} + +/// The encoded answer of webfront.inspector.containers(): a tuple of three booleans. +std::string containersAnswer(bool secondaryWindow, bool host, bool newConnections) { + const auto boolean = [](bool value) { + return static_cast(value ? msg::CodedType::booleanTrue : msg::CodedType::booleanFalse); + }; + return {static_cast(msg::CodedType::tuple), char{3}, boolean(secondaryWindow), boolean(host), boolean(newConnections)}; +} + +/// The developer environment refuses a WebSocket without an Origin; the test's browser names one that the policy admits. +WebFrontConfig inspectorConfig(bool trustLoopback) { + WebFrontConfig config{.port = "0", .trustLoopbackClients = trustLoopback}; + config.contentPolicy.allowAnyBridgeOrigin = true; + return config; +} +const std::string inspectorUpgradeRequest = "GET / HTTP/1.1\r\nHost: localhost\r\nOrigin: http://localhost\r\nUpgrade: websocket\r\n" + "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + +/// The application of a developer project, bootstrapped, with one browser that presents `proof` and asks for the containers. +struct InspectorBrowser { + explicit InspectorBrowser(bool trustLoopback) : app(project.path(), inspectorConfig(trustLoopback)) { + app.bootstrap("developer", {.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}); + } + void connectAndAsk(const std::string& proof) { + connect(app, proof, inspectorUpgradeRequest); + callWithoutArgument("webfront.inspector.containers", 7); + } + webfront::test::TemporaryDirectory project; + InspectorApp app; +}; +} // namespace + +const Scenario inspectorContainersScenario{"The inspectors' containers follow the effective access of the calling page (ADR-027, section 8)", + {"view-association"}, + [] { + given("the three answers computed from the frontend, the page and the trust", [&] { + then("a frontend that opens windows offers one only to an admitted page", [&] { + require(developer::inspectorContainers(true, true, false) == std::tuple{true, true, false}); + require(developer::inspectorContainers(true, false, false) == std::tuple{false, false, false}); + require(developer::inspectorContainers(true, false, true) == std::tuple{false, false, true}); + }); + then("a frontend that opens none offers no window, even to an admitted page", [&] { + require(developer::inspectorContainers(false, true, true) == std::tuple{false, true, true}); + require(developer::inspectorContainers(false, false, false) == std::tuple{false, false, false}); + }); + }); + given("a developer application whose frontend opens no secondary window", [&] { + freshNetwork(); + InspectorBrowser browser{false}; + then("the function is registered once the environment is bootstrapped", [&] { + require(browser.app.hasCppFunction("webfront.inspector.containers")); + }); + when("the view presents the secret of the launch", [&] { + browser.connectAndAsk(testing::LaunchSecret::of(browser.app)); + then("the page is admitted, without a secondary window or new connections", [&] { + require(ViewSocket::wrote(containersAnswer(false, true, false))); + }); + }); + }); + given("a page that is not proven, such as the system browser's or a frame's", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + InspectorBrowser browser{false}; + browser.connectAndAsk({}); + then("the call is answered, and no container is admitted", [&] { + require(ViewSocket::wrote(containersAnswer(false, false, false))); + }); + }); + given("trustLoopbackClients and a page that is not proven on the loopback", [&] { + freshNetwork(); + ViewSocket::peerIsLoopback = true; + InspectorBrowser browser{true}; + browser.connectAndAsk({}); + then("the page and the new connections are admitted", [&] { + require(ViewSocket::wrote(containersAnswer(false, true, true))); + }); + }); + given("trustLoopbackClients and a page that is not on the loopback", [&] { + freshNetwork(); + InspectorBrowser browser{true}; + browser.connectAndAsk({}); + then("the page is not admitted, though new loopback connections would be", [&] { + require(ViewSocket::wrote(containersAnswer(false, false, true))); + }); + }); + given("a developer application that is not bootstrapped", [&] { + freshNetwork(); + webfront::test::TemporaryDirectory project; + InspectorApp app(project.path(), WebFrontConfig{.port = "0"}); + then("it has no inspector function", [&] { + require(!app.hasCppFunction("webfront.inspector.containers")); + }); + }); + }}; diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 3e138985..f73ae237 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -842,8 +842,28 @@ try { const rect = box(selector); return rect.left === 0 && rect.top === 0 && Math.abs(rect.width - root.clientWidth) < 1 && Math.abs(rect.height - root.clientHeight) < 1; }, + // The tab's context menu (#679): its panels, the root first, and the entries of one of them. + menus: () => [...page.querySelectorAll('.webfront-menu')], + entries: level => [...(page.querySelectorAll('.webfront-menu')[level]?.querySelectorAll('[role=menuitem]') ?? [])], + press: (target, init) => target.dispatchEvent(new view.KeyboardEvent('keydown', {bubbles: true, cancelable: true, ...init})), + rightClick: (target, x, y) => target.dispatchEvent(new view.MouseEvent('contextmenu', {bubbles: true, cancelable: true, button: 2, clientX: x, clientY: y})), }; }; + // The reason the inspector entries give, from what webfront.inspector.containers() answered to the page's bridge: + // an admitted page has no inspector to open yet (#680), another one is told how to be admitted (ADR-027, section 8). + const inspectorReason = async bridge => { + const [, host] = await bridge.cppFunction('webfront.inspector.containers')(); + return host ? /cannot open the inspectors yet/ : /trustLoopbackClients/; + }; + // Opens the submenu of `group` (1: C++ state, 2: TypeScript state) until the menu has read the page's access. + const inspectorEntries = async (layoutOf, group, expected) => { + await until(() => { + layoutOf.menus().slice(1).forEach(() => layoutOf.press(layoutOf.entries(1)[0], {key: 'ArrowLeft'})); + layoutOf.press(layoutOf.entries(0)[group], {key: 'ArrowRight'}); + return expected.test(layoutOf.menus()[1]?.querySelector('.webfront-menu-reason')?.textContent ?? ''); + }, 'The inspector entries must give the reason they are unavailable'); + return layoutOf.entries(1); + }; const here = layout(document); if (part === 'workspace') { // First launch, in a project without an interface: the terminal alone, no icon, no empty preview. @@ -890,6 +910,16 @@ try { if (part === 'workspace') await until(() => here.state() === 'floating', `The first preview must leave the terminal open: ${here.state()}`); assert(here.state() !== 'terminal' && here.fills('#preview') && here.style('.webfront-terminal-toggle').display !== 'none', 'A displayed interface must fill the window, with the icon'); + if (part === 'workspace') { + // This page's own menu: the inspector entries follow what its connection is admitted to. + const tabBox = here.box('.webfront-terminal-toggle'); + here.rightClick(here.button(), tabBox.left + 10, tabBox.top + 10); + const entries = await inspectorEntries(here, 1, await inspectorReason(webFront)); + assert(entries.length === 3 && entries.every(entry => entry.getAttribute('aria-disabled') === 'true'), + 'Without an inspector to open, the entries of this page must be greyed'); + here.press(entries[0], {key: 'Escape'}); + assert(here.menus().length === 0 && document.activeElement === here.button(), 'Escape in a submenu must close the whole menu and give the focus back to the tab'); + } // Launching again: the bootstrap page of the same project, in a window of its own size. const relaunched = document.createElement('iframe'); @@ -923,6 +953,54 @@ try { await until(() => sessionText().includes('>'), 'The collapsed terminal must have its prompt'); const before = sessionText(); + // The tab's context menu (#679): a right click opens it beside the tab, inside the window, with the focus on its + // first entry and without opening the terminal. + assert(button.getAttribute('aria-haspopup') === 'menu', 'The tab must announce its menu'); + assert(!again.rightClick(button, icon.left + icon.width / 2, icon.top + icon.height / 2), 'The browser\'s own menu must not open on the tab'); + assert(again.menus().length === 1 && again.menus()[0].querySelector('[role=menu]'), 'A right click on the tab must open its menu'); + assert(again.entries(0).map(entry => entry.firstChild.textContent).join() === 'Terminal,C++ state,TypeScript state', + `The menu must offer the terminal and the inspectors: ${again.entries(0).map(entry => entry.textContent)}`); + assert(again.inside('.webfront-menu') && again.entries(0).every(entry => entry.getBoundingClientRect().height >= 44), + 'The menu must stay inside the window, with targets of 44 px'); + assert(page.activeElement === again.entries(0)[0] && again.state() === 'interface', 'The menu must take the focus, and leave the terminal collapsed'); + // The arrows move in the menu and open a submenu. This page is a frame of the test page: its connection is not + // the proven view, so no container is admitted and the entries say how to admit one. + again.press(again.entries(0)[0], {key: 'ArrowDown'}); + assert(page.activeElement === again.entries(0)[1], 'The down arrow must move to the next entry'); + const [, framedHost] = await relaunched.contentWindow.webFront.cppFunction('webfront.inspector.containers')(); + assert(framedHost === false, 'A frame of the page is not admitted to the inspectors'); + const cppEntries = await inspectorEntries(again, 1, /trustLoopbackClients/); + assert(cppEntries.map(entry => entry.firstChild.textContent).join() === 'Functions,Browsers and tasks,Watches' + && cppEntries.every(entry => entry.getAttribute('aria-disabled') === 'true' && /trustLoopbackClients/.test(entry.title)), + 'The entries of a page that is not admitted must be greyed with their reason'); + assert(page.activeElement === cppEntries[0] && again.inside('.webfront-menu[data-level="1"]'), 'The submenu must take the focus, inside the window'); + again.press(cppEntries[0], {key: 'Enter'}); + assert(again.menus().length === 2 && again.state() === 'interface', 'An unavailable entry must do nothing'); + again.press(cppEntries[0], {key: 'ArrowLeft'}); + assert(again.menus().length === 1 && page.activeElement === again.entries(0)[1], 'The left arrow must close the submenu'); + const tsEntries = await inspectorEntries(again, 2, /trustLoopbackClients/); + assert(tsEntries.map(entry => entry.firstChild.textContent).join() === 'Packages,Bridge', 'The TypeScript state must offer its panels'); + again.press(tsEntries[1], {key: 'Escape'}); + assert(again.menus().length === 0 && page.activeElement === button, 'Escape in a submenu must close the whole menu and give the focus back to the tab'); + // The Menu key and Shift+F10 open it from the keyboard; its Terminal entry opens the terminal. + again.press(button, {key: 'ContextMenu'}); + assert(again.menus().length === 1 && page.activeElement === again.entries(0)[0], 'The Menu key must open the menu on the tab'); + again.press(page.activeElement, {key: 'Escape'}); + again.press(button, {key: 'F10', shiftKey: true}); + assert(again.menus().length === 1, 'Shift+F10 must open the menu on the tab'); + again.press(again.entries(0)[0], {key: 'Enter'}); + assert(again.menus().length === 0 && again.state() === 'floating' && again.panel().contains(page.activeElement), + 'The Terminal entry must open the terminal and give it the keys'); + page.querySelector('.webfront-terminal-close').click(); + assert(again.state() === 'interface' && page.activeElement === pagePreview && sessionText() === before, + 'The terminal opened from the menu must collapse as before'); + // Closed, the menu takes no key from the interface. + again.press(pagePreview.contentDocument.body, {key: 'Escape'}); + again.press(pagePreview.contentDocument.body, {key: 'ArrowDown'}); + assert(again.menus().length === 0 && again.state() === 'interface' && pagePreview.contentWindow.seen.join() === 'Escape,ArrowDown', + `A closed menu must leave the keys to the interface: ${pagePreview.contentWindow.seen}`); + pagePreview.contentWindow.seen.length = 0; + button.click(); assert(again.state() === 'floating' && button.getAttribute('aria-expanded') === 'true', 'A click on the icon must open the terminal'); const dialog = again.panel();