/* * "Show me" of a help topic in the report (help-show.js plans its steps): it marks one control at a * time, in the order a reader clicks them, with a card at it - "Step 2 of 3", what to do there, and * "Do it for me" (the guide clicks the control) or, at the last step, "Done". The reader's click on the * marked control, or Enter on it, takes the step; nothing that changes the report happens otherwise. * The control a menu opens from (the origin: a field's chip, a toolbar button) keeps a ring of its own * to the end; in a bottom sheet, which covers it, the sheet's head carries it. The rest of the report * is dimmed. Escape, "Done", a click elsewhere or the marked control going away (its menu closed) ends * it. A step that opens what the next one needs (the zones folded away, the field list, the other tab) * is skipped where that shows already; a step whose menu closed meanwhile (a view saved) opens it again. * A single step (an own question's, Swap, Undo) is a card alone: the reader's next press or key ends it. * * Controls draw their mark themselves by their key (HelpContext's `guide`); one found by its selector * gets the mark here. The card, the dimming and an own question's ring over the page's element are in * the browser's top layer, shown after the menu, so they are above it. The card takes no focus: the * marked control has it. Loaded with the help (help-module.js). */ import React, { useContext, useEffect, useId, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { hasTopLayer, LayerContext, useTopLayer } from "./popover.jsx"; import { fromOrigin, viewportOf } from "./place.js"; import { hostElement, shows, testId } from "./help-show.js"; import { dimHoles, dimPath, overlap, placeCard } from "./help-place.js"; import { HELP_TEXTS } from "./help-topics.js"; import { useIsoLayoutEffect } from "./iso.js"; import { fill } from "./labels.js"; /** How long "Show me" waits for a step's control (a menu loads on demand), in ms. */ const WAIT_MS = 4000; /** The attributes the guide writes: the mark of a control found by its selector, and the origin's. */ const MARK = "data-pk-guided"; const ORIGIN = "data-pk-guide-origin"; /** How long a step's control is kept in the window while what opened for it settles, in ms. */ const SETTLE_MS = 1000; /** The room the dimming leaves around what it keeps clear, in px. */ const HOLE_PAD = 6; /** * A step's control in the report (or in its layer, where that is outside it), or the page's element of * an own question; null where it is not there or shows no box. * @param {HTMLElement} root * @param {HTMLElement | null} layer * @param {import("./use-help.js").GuideStep} step * @param {boolean} current the step marked now: its key draws the mark (else it is found by its test id) * @returns {HTMLElement | null} */ function stepElement(root, layer, step, current) { if (step.target) { return hostElement(root, step.target); } const selector = step.select ?? (current ? `[${MARK}]` : testId(String(step.key))); /** @type {HTMLElement[]} */ let found = []; try { found = /** @type {HTMLElement[]} */ ([...root.querySelectorAll(selector), ...(layer && !root.contains(layer) ? layer.querySelectorAll(selector) : [])]); } catch { // a selector the page cannot read (a field's name it cannot hold) finds nothing } const el = found[step.select ? (step.nth ?? 0) : 0] ?? null; return el && shows(el) ? el : null; } /** * Whether what a step that opens something opens shows already: its control is not there (the field * list open, no button for it), or says it is open or chosen (the zones, a tab). * @param {HTMLElement | null} el */ const done = (el) => !el || el.getAttribute("aria-expanded") === "true" || el.getAttribute("aria-selected") === "true"; /** A visible popover of the report's layer, or null. @param {HTMLElement | null} layer */ const openMenu = (layer) => /** @type {HTMLElement | null} */ (layer?.querySelector(".pk-popover:not(.pk-guide-card)") ?? null); /** * The control the current step marks, once it shows: a step that opens what the next one needs is * skipped where that shows already, a step's menu that closed meanwhile is opened again by its `via` * buttons, and the guide ends when nothing came within WAIT_MS (while the reader works in the menu of * a `via` step, it waits) or when the control goes away; a control drawn anew is followed. * @param {HTMLElement | null} root * @param {HTMLElement | null} layer * @param {import("./use-help.js").Guide} guide * @param {{ current: { end: () => void, next: () => void, skip: () => void } }} act */ function useMarked(root, layer, guide, act) { // the control with the guide it was found for: a new step has none until its own shows, from its // first render on (an effect would leave the last step's control for one frame) const [marked, setMarked] = useState(/** @type {{ el: HTMLElement | null, guide: unknown }} */ ({ el: null, guide: null })); const step = guide.steps[guide.at]; useEffect(() => { if (!root) { return undefined; } if (step.prep && done(stepElement(root, layer, step, false))) { act.current.skip(); return undefined; } let found = /** @type {HTMLElement | null} */ (null); let since = performance.now(); const clicked = new Set(); const check = () => { const el = stepElement(root, layer, step, true); if (found && !el && step.via) { // gone with its menu's first level (the reader saves a view): waits, opens it again found.removeAttribute(MARK); found.style.removeProperty("box-shadow"); found = null; since = performance.now(); setMarked({ el: null, guide }); } else if (found && !el) { // a step done once its control goes (a view named and saved) takes the next one if (step.gone) { act.current.next(); } else { act.current.end(); } return; } // drawn anew (the settings' button of the tab just switched to): the mark goes with it if (el && found && el !== found) { if (step.select) { found.removeAttribute(MARK); found.style.removeProperty("box-shadow"); } found = null; } if (el && !found) { found = el; // a control found by its selector gets the mark the others draw themselves; inside the // origin (a chip's name) the origin's ring is its ring if (step.select) { el.setAttribute(MARK, ""); if (step.origin && el.closest(step.origin) !== el) { el.style.setProperty("box-shadow", "none"); } } setMarked({ el, guide }); return; } if (!el && step.via) { // the menu closed (a view saved): opened again by its buttons, the last one that shows, // each once - outside any menu, or in the one open (More, then its Views…) const menu = openMenu(layer); const button = step.via .map((v) => /** @type {HTMLElement | null} */ (root.querySelector(v) ?? layer?.querySelector(v) ?? null)) .filter((b) => b && shows(b) && !clicked.has(b) && (!menu || menu.contains(b))) .pop(); if (button) { clicked.add(button); button.click(); } // while a button opens it, or the reader works in the menu (names the view), it waits if (button || menu) { since = performance.now(); } } }; const mo = new MutationObserver(check); const watch = { subtree: true, childList: true, attributes: true, attributeFilter: [MARK, "hidden", "aria-expanded", "data-pk-open"] }; mo.observe(root, watch); if (layer && !root.contains(layer)) { mo.observe(layer, watch); } check(); const timer = setInterval(() => { check(); if (!found && performance.now() - since > WAIT_MS) { act.current.end(); } }, 250); return () => { mo.disconnect(); clearInterval(timer); if (step.select) { found?.removeAttribute(MARK); found?.style.removeProperty("box-shadow"); } }; // a new step, or the report's layer: the steps are fixed while the guide runs }, [root, layer, guide, step, act]); return marked.guide === guide ? marked.el : null; } /** * The origin: from the step that names one, its control's closest match (the whole chip, the field's * row), with the zone it is in, to the end. It carries `data-pk-guide-origin` (for a host's tests and * styles); its ring is drawn over it (usePlace), in a bottom sheet that covers it over the sheet's head. * @param {import("./use-help.js").Guide} guide * @param {HTMLElement | null} marked */ function useOrigin(guide, marked) { const origin = useRef(/** @type {{ el: HTMLElement, from?: string } | null} */ (null)); const step = guide.steps[guide.at]; useEffect(() => { if (marked && step.origin) { const el = /** @type {HTMLElement} */ (marked.closest(step.origin) ?? marked); if (origin.current?.el !== el) { origin.current?.el.removeAttribute(ORIGIN); el.setAttribute(ORIGIN, ""); origin.current = { el, from: step.from }; } } }, [marked, step]); // the guide's end takes the origin's mark away useEffect(() => () => origin.current?.el.removeAttribute(ORIGIN), []); return origin; } /** * Where the origin's ring goes: around the origin, or, where the menu the marked control is in covers * the origin (a bottom sheet, a menu over the chip in a short window), around the words of the menu's * head or level title (the field's name), with the zone; where the menu has neither, nowhere. * @param {HTMLElement} marked * @param {{ el: HTMLElement, from?: string } | null} origin * @param {Record} zones * @returns {{ box: DOMRect, from: string | null } | null} */ function originBox(marked, origin, zones) { if (!origin?.el.isConnected) { return null; } const menu = marked.closest(".pk-popover"); const box = origin.el.getBoundingClientRect(); const m = menu?.getBoundingClientRect(); // the menu covers it (a bottom sheet, a menu over the chip in a short window): the ring goes to the menu's head const covered = Boolean(menu && m && !menu.contains(origin.el) && (menu.classList.contains("pk-sheet") || overlap(m, box))); if (!menu || !covered) { return { box, from: null }; } // the menu's name, or a level's title in it ("Team › Filter") const head = menu.querySelector('[data-testid="menu-head"], [data-testid="level-title"]'); if (!head) { return null; } const words = head.ownerDocument.createRange(); words.selectNodeContents(head); return { box: words.getBoundingClientRect(), from: origin.from && Object.hasOwn(zones, origin.from) ? zones[origin.from] : null }; } /** * What the reader does at a step: a click on its control (or Enter on a control that is no button) * takes the step, at the last step ends the guide (not where the reader picks several, `keep`); a click * elsewhere, outside the card, and Escape end it. A single step ends at the next press or key. The * control is looked up at the press, from the step's first render on: a reader who acts at once (Enter * on the entry the menu just focused) is not missed. While the step's control is not there yet (its * menu opens again), a click elsewhere does not end it. * @param {HTMLElement | null} root * @param {HTMLElement | null} layer * @param {import("./use-help.js").Guide} guide * @param {React.RefObject} card * @param {{ current: { end: () => void, next: () => void } }} act */ function useReader(root, layer, guide, card, act) { useIsoLayoutEffect(() => { const doc = root?.ownerDocument; if (!root || !doc) { return undefined; } const step = guide.steps[guide.at]; // an own question's ring on the page: its card alone, which the reader's next press or key ends const single = Boolean(step.target); const last = guide.at === guide.steps.length - 1; const control = () => stepElement(root, layer, step, true); const onKey = (/** @type {KeyboardEvent} */ e) => { const el = control(); if (e.key === "Escape" || (single && (e.key === "Enter" || e.key === " "))) { act.current.end(); } else if ((e.key === "Enter" || e.key === " ") && el && e.composedPath().includes(el) && !el.matches("button, input, select, textarea, a") && !(step.keep && last) && !step.gone) { // a control that acts on its keys, not on a click (a number of the table) act.current.next(); } }; const onDown = () => act.current.end(); const onClick = (/** @type {MouseEvent} */ e) => { const el = control(); if ((card.current && e.composedPath().includes(card.current)) || !el) { return; } if (!e.composedPath().includes(el)) { act.current.end(); } else if (!(step.keep && last) && !step.gone) { act.current.next(); } }; doc.addEventListener("keydown", onKey, true); doc.addEventListener(single ? "pointerdown" : "click", single ? onDown : onClick, true); return () => { doc.removeEventListener("keydown", onKey, true); doc.removeEventListener(single ? "pointerdown" : "click", single ? onDown : onClick, true); }; }, [root, layer, guide, card, act]); } /** * The marked control outside a menu takes the focus (a menu gives it to its marked entry itself) and * comes into view; the card describes it for a screen reader that comes back to it. An element of the * page stays as the page made it. * @param {HTMLElement | null} marked * @param {boolean} hostTarget * @param {string} textId the card's text */ function useDescribed(marked, hostTarget, textId) { useEffect(() => { if (!marked) { return undefined; } if (!marked.closest(".pk-popover")) { marked.focus({ preventScroll: true }); } // in a menu to its middle: the edge of a long menu fades out (levels.jsx: useMoreBelow); in // a bottom sheet's to its top, under the card above the sheet marked.scrollIntoView?.({ block: marked.closest(".pk-sheet") ? "start" : marked.closest(".pk-popover") ? "center" : "nearest", inline: "nearest" }); if (hostTarget) { return undefined; } const described = marked.getAttribute("aria-describedby"); marked.setAttribute("aria-describedby", [described, textId].filter(Boolean).join(" ")); return () => { if (described === null) { marked.removeAttribute("aria-describedby"); } else { marked.setAttribute("aria-describedby", described); } }; }, [marked, hostTarget, textId]); } /** Scrolls a control into the window where it is not in it. @param {HTMLElement} el */ function keepInView(el) { const box = el.getBoundingClientRect(); if (box.top < 0 || box.bottom > viewportOf(el.ownerDocument).height) { el.scrollIntoView?.({ block: "nearest", inline: "nearest" }); } } /** * Where the card goes for a marked control: beside its menu, not over it; a bottom sheet's full width * leaves room only above it, over the dimmed report, so the card covers none of its entries; else at * the control. Never over the origin nor its ring (on the menu's head, Back and title, where the menu * covers the origin): beside them, else at the window's top or bottom edge without an arrow (placeCard). * With the control's box and what the card stands beside. * @param {HTMLElement} marked * @param {HTMLElement} card * @param {DOMRect[]} avoid the origin, then its ring */ function cardSpot(marked, card, avoid) { const menu = marked.closest(".pk-popover"); const box = marked.getBoundingClientRect(); const sheet = Boolean(menu?.classList.contains("pk-sheet")); const size = { width: card.offsetWidth, height: card.offsetHeight }; const viewport = viewportOf(card.ownerDocument); if (menu) { const beside = menu.getBoundingClientRect(); // a bottom sheet's scrim dims the origin outside it: only its ring on the sheet's head counts return { box, beside, sheet, at: placeCard(box, beside, size, viewport, sheet ? ["above"] : ["right", "left", "below", "above"], sheet ? avoid.slice(1) : avoid) }; } // outside a menu, beside the group of controls it is one of, not over its neighbours: the field // list (right of it), the zones, the toolbar, the tabs (below them); else at the control const group = /** @type {HTMLElement | null} */ (marked.closest(GROUPS)); const beside = group?.getBoundingClientRect(); const at = beside && placeCard(box, beside, size, viewport, group?.matches('[data-testid="field-list"]') ? ["right", "left"] : ["below", "above"], avoid); return at?.side && beside ? { box, beside, sheet, at } : { box, beside: box, sheet, at: placeCard(box, box, size, viewport, ["below", "above", "right", "left"], avoid) }; } /** The groups of controls the card stands beside, not over: the field list, the zones, the toolbar, the tabs. */ const GROUPS = '[data-testid="field-list"], [data-testid="zone-section"], .pk-toolbar, .pk-tabs'; /** The words a control shows (its first line), else its name for a screen reader. @param {HTMLElement} el */ const nameOf = (el) => (el.innerText || el.textContent || "").trim().split("\n")[0] || el.getAttribute("aria-label") || el.title; /** * The card's place beside the marked control (beside its menu, not over it), its arrow, the dimmed * report with its holes, and an own question's ring over the page's element: placed again every frame * while they move. A page's element taken away or hidden ends the guide. * @param {HTMLElement | null} marked * @param {HTMLElement | null} root * @param {HTMLElement | null} layer * @param {React.RefObject} card * @param {React.MutableRefObject<{ el: HTMLElement, from?: string } | null>} origin * @param {Record} zones the zones' names * @param {boolean} hostTarget * @param {{ current: { end: () => void } }} act */ function usePlace(marked, root, layer, card, origin, zones, hostTarget, act) { const [place, setPlace] = useState(/** @type {null | { marked: HTMLElement, card: { top: number, left: number }, side: string | null, arrow: number, ring: { top: number, left: number, width: number, height: number } | null, dim: { top: number, left: number, width: number, height: number, path: string } | null, origin: { top: number, left: number, width: number, height: number, from: string | null } | null }} */ (null)); useEffect(() => { const el = card.current; if (!marked || !el || !root) { return undefined; } let frame = 0; let last = ""; // while what opened for it settles (the zones grow open), the control is kept in the window const settled = performance.now() + SETTLE_MS; const forced = Boolean(el.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches); const run = () => { // gone or hidden: useMarked ends the guide, or waits where the step's menu opens again if (!marked.isConnected || !marked.getClientRects().length) { frame = requestAnimationFrame(run); return; } if (!marked.closest(".pk-popover") && performance.now() < settled) { keepInView(marked); } const from = originBox(marked, origin.current, zones); const { box, beside, sheet, at } = cardSpot(marked, el, from && origin.current ? [origin.current.el.getBoundingClientRect(), from.box] : []); const probe = el.hasAttribute("popover") ? null : layer?.querySelector(".pk-origin"); const zero = probe ? probe.getBoundingClientRect() : { top: 0, left: 0 }; const report = root.getBoundingClientRect(); // the card is drawn above the dimming: no hole for it const kept = [beside, ...(from && !sheet ? [from.box] : [])]; // a bottom sheet has its scrim, forced colours no transparency: no dimming const dim = sheet || hostTarget || forced ? null : { ...fromOrigin({ top: report.top, left: report.left }, zero), width: report.width, height: report.height, path: dimPath(report, dimHoles(kept, report, HOLE_PAD)) }; const boxOf = (/** @type {DOMRect} */ b) => ({ ...fromOrigin({ top: b.top, left: b.left }, zero), width: b.width, height: b.height }); const ring = hostTarget ? boxOf(box) : null; const next = { marked, card: fromOrigin({ top: at.top, left: at.left }, zero), side: at.side, arrow: at.arrow, ring, dim, origin: from ? { ...boxOf(from.box), from: from.from } : null }; const key = JSON.stringify({ ...next, marked: null }); if (key !== last) { last = key; setPlace(next); } frame = requestAnimationFrame(run); }; run(); return () => cancelAnimationFrame(frame); }, [marked, root, layer, card, origin, zones, hostTarget, act]); // the place of this control, none yet for the next one's return place?.marked === marked ? place : null; } /** * A text said a moment after it shows, so a screen reader announces it (a live region filled later): * empty until then, and for another control. * @param {HTMLElement | null} marked * @param {string} text */ function useSaid(marked, text) { const [said, setSaid] = useState({ text: "", el: /** @type {HTMLElement | null} */ (null) }); useEffect(() => { if (!marked) { return undefined; } const t = setTimeout(() => setSaid({ text, el: marked }), 50); return () => clearTimeout(t); }, [marked, text]); return said.el === marked && said.text === text ? text : ""; } /** A box as a fixed element's style. @param {{ top: number, left: number, width: number, height: number }} b */ const boxStyle = ({ top, left, width, height }) => ({ top, left, width, height }); /** * The card of a guide of several steps: its arrow at the control, "Step 2 of 3" and the step (shown at * once, so the card has its size from the start, and said a moment later), and Do it for me or Done. * @param {{ cardRef: React.MutableRefObject, topLayer: object, style: object, place: any, parent: string | undefined, * stepOf: string, text: string, said: string, lang: string | undefined, textId: string, last: boolean, t: any, onDo: (() => void) | null, onEnd: () => void }} props */ function StepsCard({ cardRef, topLayer, style, place, parent, stepOf, text, said, lang, textId, last, t, onDo, onEnd }) { const keep = (/** @type {React.MouseEvent} */ e) => e.preventDefault(); return (
{place?.side ?
); } /** * The card of "Show me" at the marked control, while the guide runs, with the dimmed report, the * origin's ring and an own question's ring over the page's element. * @param {{ guide: import("./use-help.js").Guide, root: HTMLElement | null, zones: Record, * onStep: (at: number) => void, onEnd: () => void }} props */ export function GuideCard({ guide, root, zones, onStep, onEnd }) { const { layer } = useContext(LayerContext); const card = useRef(/** @type {HTMLDivElement | null} */ (null)); const ring = useRef(/** @type {HTMLDivElement | null} */ (null)); const dimEl = useRef(/** @type {HTMLDivElement | null} */ (null)); const originEl = useRef(/** @type {HTMLDivElement | null} */ (null)); const textId = useId(); const step = guide.steps[guide.at]; const count = guide.steps.length; const last = guide.at === count - 1; // the latest guide for the listeners made once per step const act = useRef({ end: onEnd, next: () => {}, skip: () => {} }); useEffect(() => { act.current = { end: onEnd, next: () => (last ? onEnd() : onStep(guide.at + 1)), skip: () => onStep(guide.at + 1) }; }); const marked = useMarked(root, layer, guide, act); const origin = useOrigin(guide, marked); useReader(root, layer, guide, card, act); useDescribed(marked, Boolean(step.target), textId); const place = usePlace(marked, root, layer, card, origin, zones, Boolean(step.target), act); // the control's own words fill `{name}`: what it shows, else its name for a screen reader const text = marked && !step.target && step.text.includes("{name}") ? fill(step.text, { name: nameOf(marked) }) : step.text; const said = useSaid(marked, text); const [top] = useState(() => hasTopLayer()); // after the menu: drawn above it, a bottom sheet too; the dimming first, the card last useTopLayer(Boolean(marked), [dimEl, originEl, ring, card], `${guide.at}:${Boolean(place?.dim)}:${Boolean(place?.origin)}`, layer); if (!marked || !layer) { return null; } const t = HELP_TEXTS[guide.lang]; const hidden = { top: 0, left: 0, visibility: /** @type {const} */ ("hidden") }; const topLayer = top ? { popover: "manual" } : {}; return createPortal( <> {place?.dim ? ( ) : null} {place?.origin ? ( ) : null} {step.target ?
: null} {step.target ? (
{said}
) : ( 1 ? fill(t.stepOf, { n: guide.at + 1, m: count }) : ""} text={text} said={said} lang={step.lang} textId={textId} last={last} t={t} onDo={step.gone ? null : () => marked.click()} onEnd={onEnd} /> )} , layer ); }