/* * What "Show me" of a help topic does in the report as it is now (help-topics.js has the topics): its * steps, one control each, in the order a reader clicks them (help-guide.jsx walks them). A step marks * its control by its key (HelpContext's `guide`, help.js) or, for a control that draws no mark of its * own, by its selector (`select`, the `nth` match: the second chip of Rows); its card says one of the * answer's steps, or a text of CARD with the control's own words. What has to open first is a step of * its own (`prep`: the zones folded away, the field list in its drawer or on its rail, the other tab, * a toolbar button in More); a field the question needs that is in the data but not in Rows or Columns * is added first (`notice` says which). The control a menu opens from is the `origin`: its ring stays * until the end. Where the report has nothing to show (no field in Rows, an entry that is greyed out * now), the sentence that says why (`none`). The plans are pure, tested without a DOM. An own * question's "Show me" rings an element of the page instead (hostElement, which reads the page, as * `shows` does). * * Controls are found as the browser tests find them, by their test ids and zones. */ import { measureChoices, totalNoEffect } from "./menu-ops.js"; import { filterZoneFields, sourceOf } from "./view-ops.js"; import { CARD } from "./help-topics.js"; /** * @typedef {object} ShowState * @property {any} view * @property {(field: string) => string} typeOf a field's type ("date", "number", "string") * @property {string[]} fields the data's fields, in the field list's order * @property {"table" | "chart" | "both"} display what the result shows * @property {{ drillDown: boolean, save: boolean, link: boolean, import: boolean, fullScreen: boolean, date: boolean, number: boolean, * viewsInMore: boolean, dataInMore: boolean, startOverInMore: boolean, zonesFolded: boolean, fieldsHidden: "drawer" | "rail" | false, * tableHidden: boolean, chartHidden: boolean, resetOff: boolean, undoOff: boolean }} features * what the report offers and its data holds, which toolbar buttons are in More now, whether the zones are * folded away and the field list is in its drawer or on its rail, whether the table or the chart is not * shown (the other tab is), and whether Reset or Undo does nothing now */ /** * @typedef {import("./help-topics.js").Text} Text * @typedef {object} ShowStep one control to click * @property {string} [key] the control's key: it draws its mark itself * @property {string} [select] or its selector, the `nth` match (one that draws no mark of its own) * @property {number} [nth] * @property {number | Text} say what the card says: the topic's step of that index, or this text * @property {string} [origin] the menu opens from here: the element marked from now to the end, this * control's closest match of the selector (the whole chip, the field's row), else the control * @property {string} [from] the zone of the origin: a bottom sheet's head names it beside the menu's name * @property {true} [prep] it opens what the next step's control is in: skipped where that shows already * @property {true} [keep] the last step, where the reader picks one or more: a click there does not end it * @property {string[]} [via] the buttons that open the menu again where it closed meanwhile (a view saved) * @property {true} [gone] done once its control goes (the level that names a view, saved or left) */ /** * @typedef {object} ShowPlan * @property {string} [none] the key of HELP_TEXTS' sentence: nothing to show * @property {string} [notice] the key of HELP_TEXTS' notice: what Show me adds first, `field` * @property {string} [note] the key of HELP_TEXTS' sentence about a step left out (no link) * @property {ShowStep[]} [steps] * @property {string} [field] the field the steps are about * @property {{ field: string | null, agg: string }} [measure] the value a sort goes by */ /** A field name inside a selector's quoted attribute value: quotes, backslashes and line breaks escaped as CSS writes them. */ const quoted = (/** @type {string} */ text) => text.replace(/["\\]/g, "\\$&").replace(/[\n\r\f]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `); /** A control by its test id. */ export const testId = (/** @type {string} */ id) => `[data-testid="${quoted(id)}"]`; /** A chip's menu button in a zone. */ const chip = (/** @type {string} */ zone) => `[data-zone="${zone}"] [data-testid^="chip-menu-"]`; /** The zones opened first where they are folded away (a phone). @param {ShowState} state @returns {ShowStep[]} */ const zonesFirst = ({ features }) => (features.zonesFolded ? [{ select: testId("layout-summary"), say: CARD.zones, prep: true }] : []); /** The field list opened first: its drawer (a phone), or from its rail. @param {ShowState} state @returns {ShowStep[]} */ function fieldsFirst({ features }) { if (!features.fieldsHidden) { return []; } return [{ select: features.fieldsHidden === "drawer" ? '[data-pk-opener="fields"]' : testId("expand-fields"), say: CARD.openFields, prep: true }]; } /** A chip's menu, the zones opened first. @param {ShowState} state @param {string} zone @param {number} nth @returns {ShowStep[]} */ const chipMenu = (state, zone, nth) => [...zonesFirst(state), { select: chip(zone), nth, say: CARD.openMenu, origin: "[data-chip]", from: zone }]; /** A field's menu in the field list ("⋯"), the list opened first. @param {ShowState} state @param {string} field @param {Text} say @returns {ShowStep[]} */ const fieldMenu = (state, field, say = CARD.fieldMenu) => [...fieldsFirst(state), { select: testId(`field-menu-${field}`), say, origin: "[data-field]" }]; /** A toolbar button's menu: the button, its menu's origin. @returns {ShowStep[]} */ const toolbarMenu = (/** @type {string} */ button) => [{ select: testId(button), say: CARD.openMenu, origin: testId(button) }]; /** A toolbar button's menu where the button may be in More now: More, then its entry there. @returns {ShowStep[]} */ const inMoreOr = (/** @type {boolean} */ inMore, /** @type {string} */ button, /** @type {string} */ entry) => (inMore ? [...toolbarMenu("more"), { key: entry, say: CARD.choose }] : toolbarMenu(button)); /** * The first field of Rows, then of Columns, that `ok` accepts, with its zone and place. * @param {any} view * @param {(field: string) => boolean} ok * @param {string[]} zones */ function onAxis(view, ok, zones = ["rows", "cols"]) { for (const zone of zones) { const at = view[zone].findIndex(ok); if (at !== -1) { return { zone, at, field: view[zone][at] }; } } return null; } /** * A field's menu in Rows or Columns, then its entries (`then`), or the sentence why there is none. * @param {ShowState} state * @param {{ zone: string, at: number, field: string } | null} found * @param {string} none * @param {ShowStep[]} then * @returns {ShowPlan} */ const onChip = (state, found, none, then) => (found ? { steps: [...chipMenu(state, found.zone, found.at), ...then], field: found.field } : { none }); /** A value's menu at one of its entries. @param {ShowState} state @param {string} key @returns {ShowPlan} */ const onValue = (state, key) => (state.view.values.length ? { steps: [...chipMenu(state, "values", 0), { key, say: 2 }], field: state.view.values[0].field } : { none: "noValue" }); /** The fields placed anywhere in the view. */ const placed = (view) => new Set([...view.rows, ...view.cols, ...view.values.map((v) => v.field), ...filterZoneFields(view)]); /** Whether a field (or the field a grouping is of) is of a type. @param {ShowState} state @param {string} field @param {string} type */ const isType = ({ typeOf, view }, field, type) => typeOf(sourceOf(view, field)) === type; /** A field of the field list's: the first one not placed (any for none), into Rows. @type {(state: ShowState) => ShowPlan} */ function addField(state) { const used = placed(state.view); const field = state.fields.find((f) => !used.has(f)) ?? state.fields[0]; return field === undefined ? { none: "noField" } : { steps: [...fieldMenu(state, field, used.has(field) ? CARD.fieldMenu : CARD.notPlaced), { key: `field-rows-${field}`, say: CARD.addToRows }], field }; } /** * A field of a type in Rows or Columns, its menu at `then`; else the data's first field of that type * added to Rows first, its chip then the last of Rows (`notice` says so). * @param {ShowState} state * @param {"date" | "number"} type * @param {ShowStep[]} then * @returns {ShowPlan} */ function typedPlan(state, type, then) { const found = onAxis(state.view, (f) => isType(state, f, type)); if (found) { return onChip(state, found, "noField", then); } const field = state.fields.find((f) => state.typeOf(f) === type); if (field === undefined) { return { none: "noField" }; } const add = { key: `field-rows-${field}`, say: CARD.addToRows }; return { notice: type === "date" ? "needDate" : "needNumber", steps: [...fieldMenu(state, field), add, ...chipMenu(state, "rows", state.view.rows.length), ...then], field }; } /** A date in Rows or Columns, else the field list's date into Filters. @type {(state: ShowState) => ShowPlan} */ function dateRange(state) { const found = onAxis(state.view, (f) => isType(state, f, "date")); if (found) { return onChip(state, found, "noField", [{ key: "topic-filter", say: 2 }]); } const field = state.fields.find((f) => state.typeOf(f) === "date"); return field === undefined ? { none: "noField" } : { steps: [...fieldMenu(state, field), { key: `field-filter-${field}`, say: CARD.choose }], field }; } /** * Sort by a value: with one value, "Largest … first" right in the field's menu; with more, the row * "Sort by value" that opens them (menu-topics.js: axisTopics). * @type {(state: ShowState) => ShowPlan} */ function sortValue(state) { const { view, typeOf } = state; if (!view.values.length) { return { none: "noValue" }; } const measures = measureChoices(view, typeOf); const plan = onChip(state, onAxis(view, () => true), "noAxis", [{ key: measures.length === 1 ? "sort-value-desc-0" : "topic-sortValue", say: 2 }]); return plan.none ? plan : { ...plan, measure: measures[0] }; } /** * The table's or the chart's settings at an entry: the other tab first where it shows, then their * button (its own on Both), then the entry, the answer's third step. * @param {ShowState} state * @param {"table" | "chart"} kind * @param {Omit} entry * @param {number} [say] the answer's step the entry's card says * @returns {ShowPlan} */ function settingsPlan({ display }, kind, entry, say = 2) { const other = display !== "both" && display !== kind; const button = testId(display === "both" ? `${kind}-settings` : "view-settings"); return { steps: [...(other ? [{ key: `show-${kind}`, say: kind === "table" ? CARD.tableFirst : CARD.chartFirst, prep: /** @type {const} */ (true) }] : []), { select: button, say: CARD.openMenu, origin: button }, { ...entry, say }] }; } /** The one switch of the totals that changes something in this layout (`keys` in order), else why none does. @param {ShowState} state @param {string[]} keys @param {string} none @returns {ShowPlan} */ function totalPlan(state, keys, none) { const key = keys.find((k) => totalNoEffect(state.view, k) === null); if (key) { return settingsPlan(state, "table", { key: `total-${key}` }); } return { none: state.view.values.length ? none : "noValue" }; } /** Saving a view, then its link; the link alone where it cannot be saved, saving alone (and a sentence) without a link. @type {(state: ShowState) => ShowPlan} */ function share({ features }) { const open = inMoreOr(features.viewsInMore, "views", "more-views"); // after the view is saved the menu has closed: it opens again at Copy link const via = features.viewsInMore ? [testId("more"), testId("more-views")] : [testId("views")]; // the level that names the view: the step is done once it goes (saved, or Back) const save = features.save ? [{ key: "save-as", say: CARD.choose }, { select: `.pk-popover ${testId("level-saveAs")}`, say: CARD.nameView, gone: /** @type {const} */ (true) }] : []; const link = features.link ? [{ key: "copy-link", say: 3, via }] : []; return { steps: [...open, ...save, ...link], note: features.link ? undefined : "noLink" }; } /** * What "Show me" does, by topic: a function of the report as it is now. * @type {Readonly ShowPlan>>} */ const PLANS = Object.freeze({ "add-field": addField, filter: (state) => onChip(state, onAxis(state.view, () => true), "noAxis", [{ key: "topic-filter", say: 2 }, { select: `.pk-popover ${testId("level-filter")} .pk-values`, say: 3, keep: true }]), "filter-rule": (state) => onChip(state, onAxis(state.view, () => true), "noAxis", [{ key: "topic-filter", say: 2 }]), "top-n": (state) => onChip(state, onAxis(state.view, () => true, ["rows"]), "noRows", [{ key: "topic-top", say: 2 }]), "sort-value": sortValue, // the units with the whole level: centring its menu would scroll the line on the data's range // above it under the level's head (#1163) "group-dates": (state) => typedPlan(state, "date", [{ key: "topic-group", say: 2 }, { select: `.pk-popover ${testId("level-group")}`, say: 3, keep: true }]), "number-ranges": (state) => typedPlan(state, "number", [{ key: "topic-bins", say: 2 }]), "date-range": dateRange, percent: (state) => onValue(state, "topic-showAs"), summarize: (state) => onValue(state, "topic-summarize"), "number-format": (state) => onValue(state, "topic-format"), // Highlight's three choices side by side: their row, which draws no mark of its own highlight: (state) => { const plan = onValue(state, "topic-highlight"); return plan.steps ? { ...plan, steps: [...plan.steps.slice(0, -1), { select: testId("topic-highlight"), say: 2 }] } : plan; }, // a field of Rows or Columns, else a value rename: (state) => { const found = onAxis(state.view, () => true); return found || !state.view.values.length ? onChip(state, found, "noAxis", [{ key: "topic-name", say: 2 }]) : onValue(state, "topic-name"); }, // the table shown: its tab first; then the chart's settings at the chart's type chart: ({ display }) => { const button = testId(display === "both" ? "chart-settings" : "view-settings"); return { steps: [...(display === "table" ? [{ key: "show-chart", say: 0, prep: /** @type {const} */ (true) }] : []), { select: button, say: CARD.openMenu, origin: button }, { key: "chart-types", say: CARD.chartType }] }; }, // one type, the one the step names: Lines "chart-type": (state) => settingsPlan(state, "chart", { select: testId("chart-line") }), "value-labels": (state) => settingsPlan(state, "chart", { key: "topic-valueLabels" }), legend: (state) => settingsPlan(state, "chart", { key: "topic-legend" }), "chart-title": (state) => settingsPlan(state, "chart", { key: "topic-title" }), "reference-line": (state) => settingsPlan(state, "chart", { key: "topic-lines" }), "chart-image": ({ display }) => ({ steps: [...(display === "table" ? [{ key: "show-chart", say: CARD.chartFirst, prep: /** @type {const} */ (true) }] : []), ...toolbarMenu("export"), { key: "export-png", say: CARD.choose }] }), // the switch that changes something in this layout, Rows' first; none greyed out: why there is none subtotals: (state) => totalPlan(state, state.view.rows.length < 2 && state.view.cols.length >= 2 ? ["colSubtotals"] : ["rowSubtotals", "colSubtotals"], "noSubtotals"), "grand-totals": (state) => totalPlan(state, ["grandTotalRow", "grandTotalColumn"], "noAxis"), // Collapse all, or Expand all where groups are collapsed; with one field in Rows neither does anything "expand-collapse": (state) => (state.view.rows.length < 2 ? { none: "noGroups" } : settingsPlan(state, "table", { key: state.view.collapsed?.rows?.length ? "expand-all" : "collapse-all" })), // in the zones' heading row, also while they are folded // the button by its own words (the answer's step also speaks of the phone) swap: ({ view }) => (view.rows.length + view.cols.length ? { steps: [{ select: testId("swap"), say: CARD.click }] } : { none: "noAxis" }), // the number of the table the arrow keys start from (its tab stop, table.jsx), the tab Table first "drill-down": ({ view, display }) => (view.values.length ? { steps: [...(display === "chart" ? [{ key: "show-table", say: CARD.tableFirst, prep: /** @type {const} */ (true) }] : []), { select: `${testId("pivot-table")} td[tabindex="0"]`, say: 0 }] } : { none: "noValue" }), // the menu open: the entry by its own words, not the answer's "Open Export and choose …" export: () => ({ steps: [...toolbarMenu("export"), { key: "export-xlsx", say: CARD.choose }] }), "export-csv": () => ({ steps: [...toolbarMenu("export"), { key: "export-csv", say: CARD.choose }] }), print: () => ({ steps: [...toolbarMenu("export"), { key: "export-print", say: CARD.choose }] }), share, "load-data": ({ features }) => ({ steps: [...inMoreOr(features.dataInMore, "data", "more-data"), { key: "load-file", say: CARD.choose }] }), // Reset greyed out (the start view shows): why, instead of marking it "start-over": ({ features }) => features.resetOff ? { none: "atStart" } : { steps: features.startOverInMore ? [...toolbarMenu("more"), { key: "more-reset", say: CARD.choose }] : [...toolbarMenu("start-over"), { key: "reset", say: CARD.choose }] }, // Undo greyed out (nothing changed yet): why undo: ({ features }) => (features.undoOff ? { none: "nothingToUndo" } : { steps: [{ select: testId("undo"), say: 0 }] }), "full-screen": () => ({ steps: [{ select: testId("full-screen"), say: CARD.click }] }) }); /** * The plan of a topic's "Show me" in the report as it is now. * @param {string} id the topic's id * @param {ShowState} state * @returns {ShowPlan} */ export const showPlan = (id, state) => (Object.hasOwn(PLANS, id) ? PLANS[id](state) : { none: "noField" }); /** * Whether a topic shows in the list: one that `needs` a feature only where the report offers it, one * about a type of field only where the data has one. * @param {import("./help-topics.js").HelpTopic} topic * @param {ShowState["features"]} features */ export function offered(topic, features) { if (topic.needs === "share") { return features.save || features.link; } return topic.needs === undefined || Boolean(features[topic.needs]); } /** * The steps of a topic as the report is now: a step that `needs` saving or a link only with it, one * about a button in More, the zones folded away or the other tab only while it is so (every one of * a list), and none `unless` that holds. * @param {import("./help-topics.js").HelpTopic} topic * @param {ShowState["features"]} features */ export const offeredSteps = (topic, features) => topic.steps.filter((s) => [s.needs ?? []].flat().every((n) => features[n]) && !(s.unless && features[s.unless])); /** * The page's element of an own question's "Show me" (its `show.target`, an id): looked up with * getElementById in the report's tree (the document, or the shadow root a React host mounts the report * in), then in the tree of each shadow host outwards to the document. So pivotkit-element finds it in * the page around ``. An element inside another shadow root is not found, nor one of the * report's own, nor one the page does not show (no box: display none, or not in a slot). * @param {HTMLElement} root the report * @param {string} id * @returns {HTMLElement | null} */ export function hostElement(root, id) { for (let tree = /** @type {any} */ (root.getRootNode()); tree; tree = tree.host?.getRootNode() ?? null) { const el = tree.getElementById?.(id); if (el && !root.contains(el) && el.getClientRects().length) { return el; } } return null; } /** Whether an element shows: it has a box and is not hidden (the field list's drawer while closed). @param {Element} el */ export const shows = (el) => el.getClientRects().length > 0 && el.ownerDocument.defaultView?.getComputedStyle(el).visibility !== "hidden";