From 9c4d2f9b3880f0d6d10dca054653f0617d193a82 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Mon, 9 Nov 2026 16:37:45 -0500 Subject: [PATCH 1/7] cards: adopt the shared Card API (chrome + chart widgets) for the UPS dashboards Converge apcupsd's per-UPS and Fleet dashboards on the shared Card API: - Bundle the canonical js/cards.js + css/cards.css + css/card-widgets.css and load them only when core does not already ship them (file_exists gates), so on Cacti 1.2.32+ the core copies are used. - Replace the plugin's own card controller with a thin adapter over the shared window.CactiCards engine (drag/keyboard reorder, per-card tools, add-card catalogue and debounced layout save now come from core); the adapter keeps apcupsd's extras - the UPS picker, Cacti's timespan selector, the sortable card tables and the maximize dialog. - Re-vocabulary the card chrome to the .cc* contract (data-expandable / data-expanded / data-severity) and draw the card bodies from the shared .cc* chart primitives (ccGauge incl. ticks, ccBullet incl. avg marker, ccPill severities, ccEmpty), which the companion core change #8684 adds. - Standardize auto-refresh on Cacti's set_page_refresh() and reload-on-change, matching the other Card API dashboards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- css/apcupsd.css | 14 + css/card-widgets.css | 371 +++++++++++++ css/cards.css | 298 +++++++++++ includes/dashboard.php | 189 ++++--- js/apcupsd_dashboard.js | 770 +++++++-------------------- js/cards.js | 407 ++++++++++++++ tests/Unit/DashboardRefreshTest.php | 224 +------- tests/Unit/DashboardRrdStatsTest.php | 2 +- 8 files changed, 1409 insertions(+), 866 deletions(-) create mode 100644 css/card-widgets.css create mode 100644 css/cards.css create mode 100644 js/cards.js diff --git a/css/apcupsd.css b/css/apcupsd.css index ab44a4d..8cb9ad1 100644 --- a/css/apcupsd.css +++ b/css/apcupsd.css @@ -17,7 +17,21 @@ * text colour via color-mix(currentColor ...) so the same rules read correctly * on every Cacti theme, with the per-theme css/.css files tuning accents. * Severity accents (up/recovering/down) use fixed, theme-independent colours. + * + * The card chrome and chart primitives now come from the shared Card API + * stylesheets (css/cards.css + css/card-widgets.css); the rules below are kept + * only where they also style apcupsd-specific content (tables, graph panels, + * the gauge grid, the UPS/timespan pickers). The shared grid reads its column + * count and accent palette from these custom properties. */ +#apcupsd_dashboard.ccGrid, +#apcupsd_dashboard_dialog { + --cc-cols: 8; + --cc-card: transparent; + --cc-text: currentColor; + --cc-border: color-mix(in srgb, currentColor 18%, transparent); + --cc-header-bg: color-mix(in srgb, currentColor 9%, transparent); +} .apcupsdDashboard { color: #1b6ca8; diff --git a/css/card-widgets.css b/css/card-widgets.css new file mode 100644 index 0000000..8c6959d --- /dev/null +++ b/css/card-widgets.css @@ -0,0 +1,371 @@ +/* + +-------------------------------------------------------------------------+ + | Copyright (C) 2004-2026 The Cacti Group | + +-------------------------------------------------------------------------+ + | Cacti: The Complete RRDtool-based Graphing Solution | + +-------------------------------------------------------------------------+ +*/ + +/* + * cacti-card-widgets - shared, server-rendered chart primitives for the card + * API (companion to cards.css). These are the small, JS-free building blocks a + * dashboard card body is made of: a semicircular gauge, horizontal usage and + * distribution bars, a min/avg/max bullet, a stacked proportion bar, and stat + * tiles. Every element is plain markup + inline SVG so a card rendered by any + * plugin (including third-party panels surfaced inside Intropage) displays with + * no plugin-specific stylesheet or JavaScript. + * + * All colours derive from the active theme: neutrals from currentColor via + * color-mix, and severities from the shared --cc-sev-* custom properties (with + * sensible fallbacks) so a host or theme can retint them. The PHP helpers in + * lib/html.php (card_gauge(), card_bar(), card_bullet(), card_stackbar(), + * card_stat()) emit exactly this markup. + * + * Severity tokens: up (good), warn, down (bad), none (neutral/disabled). + */ + +/* ---- Semicircular gauge ---- */ +.ccGauge { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + padding: 2px 0 4px; +} + +.ccGaugeSvg { + width: 100%; + max-width: 190px; + height: auto; +} + +.ccGaugeTrack { + stroke: color-mix(in srgb, currentColor 16%, transparent); + stroke-width: 11; + stroke-linecap: round; +} + +.ccGaugeValue { + stroke-width: 11; + stroke-linecap: round; + transition: stroke-dasharray 0.4s ease; +} + +.ccGaugeValue--up { stroke: var(--cc-sev-up, #3c9a5f); } +.ccGaugeValue--warn { stroke: var(--cc-sev-warn, #d9830f); } +.ccGaugeValue--down { stroke: var(--cc-sev-down, #cc0000); } +.ccGaugeValue--none { stroke: color-mix(in srgb, currentColor 45%, transparent); } + +/* Faint radial ticks marking the window min and max on the gauge arc. */ +.ccGaugeTick { + stroke: color-mix(in srgb, currentColor 55%, transparent); + stroke-width: 2; +} + +.ccGaugeText { + margin-top: -22px; + text-align: center; + line-height: 1.2; +} + +.ccGaugeValueText { + display: block; + font-size: 20px; + font-weight: 700; +} + +.ccGaugeSub { + display: block; + font-size: 11px; + color: color-mix(in srgb, currentColor 65%, transparent); +} + +/* ---- Horizontal usage bar ---- */ +.ccBar { + position: relative; + height: 14px; + min-width: 80px; + border-radius: 7px; + background: color-mix(in srgb, currentColor 14%, transparent); + overflow: hidden; +} + +.ccBarFill { + position: absolute; + top: 0; + left: 0; + bottom: 0; + border-radius: 7px; + background: color-mix(in srgb, currentColor 45%, transparent); +} + +.ccBarFill--up { background: var(--cc-sev-up, #3c9a5f); } +.ccBarFill--warn { background: var(--cc-sev-warn, #d9830f); } +.ccBarFill--down { background: var(--cc-sev-down, #cc0000); } +.ccBarFill--none { background: color-mix(in srgb, currentColor 40%, transparent); } + +.ccBarLabel { + display: block; + margin-top: 2px; + font-size: 11px; + color: color-mix(in srgb, currentColor 70%, transparent); +} + +/* Row wrapper: label + value above a bar. */ +.ccBarRow { + display: flex; + flex-direction: column; + gap: 3px; + margin: 6px 0; +} + +.ccBarHead { + display: flex; + justify-content: space-between; + font-size: 12px; +} + +/* ---- Min/avg/max bullet ---- */ +.ccBullet { + margin: 9px 0; +} + +.ccBulletHead { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 8px; + margin-bottom: 4px; +} + +.ccBulletLabel { + font-size: 12px; + font-weight: 600; +} + +.ccBulletAvg { + font-size: 12px; + font-variant-numeric: tabular-nums; + color: color-mix(in srgb, currentColor 78%, transparent); +} + +.ccBulletTrack { + position: relative; + height: 16px; + border-radius: 8px; + background: color-mix(in srgb, currentColor 12%, transparent); + overflow: hidden; +} + +.ccBulletRange { + position: absolute; + top: 0; + bottom: 0; + border-radius: 8px; +} + +.ccBulletRange--up { background: color-mix(in srgb, var(--cc-sev-up, #3c9a5f) 55%, transparent); } +.ccBulletRange--warn { background: color-mix(in srgb, var(--cc-sev-warn, #d9830f) 55%, transparent); } +.ccBulletRange--down { background: color-mix(in srgb, var(--cc-sev-down, #cc0000) 55%, transparent); } +.ccBulletRange--none { background: color-mix(in srgb, currentColor 32%, transparent); } + +.ccBulletMarker { + position: absolute; + top: -2px; + bottom: -2px; + width: 3px; + transform: translateX(-1px); + background: currentColor; + border-radius: 2px; +} + +/* A faint dashed tick marking the historical average, distinct from the strong + current-value marker, so both are visible when they differ. */ +.ccBulletAvgMarker { + position: absolute; + top: 1px; + bottom: 1px; + width: 0; + border-left: 2px dashed color-mix(in srgb, currentColor 70%, transparent); + transform: translateX(-1px); +} + +.ccBulletScale { + display: flex; + justify-content: space-between; + margin-top: 2px; + font-size: 10px; + font-variant-numeric: tabular-nums; + color: color-mix(in srgb, currentColor 60%, transparent); +} + +/* ---- Stacked proportion bar ---- */ +.ccStack { + display: flex; + height: 20px; + border-radius: 6px; + overflow: hidden; + background: color-mix(in srgb, currentColor 12%, transparent); +} + +.ccStackSeg { + height: 100%; +} + +.ccStackSeg--up { background: var(--cc-sev-up, #3c9a5f); } +.ccStackSeg--warn { background: var(--cc-sev-warn, #d9830f); } +.ccStackSeg--down { background: var(--cc-sev-down, #cc0000); } +.ccStackSeg--none { background: color-mix(in srgb, currentColor 35%, transparent); } + +.ccStackLegend { + display: flex; + flex-wrap: wrap; + gap: 10px; + margin-top: 8px; + font-size: 11px; +} + +.ccStackLegend span { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.ccStackChip { + width: 10px; + height: 10px; + border-radius: 2px; + display: inline-block; +} + +.ccStackChip--up { background: var(--cc-sev-up, #3c9a5f); } +.ccStackChip--warn { background: var(--cc-sev-warn, #d9830f); } +.ccStackChip--down { background: var(--cc-sev-down, #cc0000); } +.ccStackChip--none { background: color-mix(in srgb, currentColor 35%, transparent); } + +/* ---- Stat tiles ---- */ +.ccStat { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + padding: 6px 0; +} + +.ccStatValue { + font-size: 30px; + font-weight: 700; + line-height: 1; +} + +.ccStatLabel { + font-size: 12px; + color: color-mix(in srgb, currentColor 70%, transparent); +} + +.ccTiles { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); + gap: 8px; +} + +.ccTile { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + padding: 8px 6px; + border: 1px solid color-mix(in srgb, currentColor 18%, transparent); + border-radius: 6px; +} + +.ccTileValue { + font-size: 20px; + font-weight: 700; + line-height: 1; +} + +.ccTileLabel { + font-size: 11px; + color: color-mix(in srgb, currentColor 70%, transparent); +} + +.ccTile--up { border-color: color-mix(in srgb, var(--cc-sev-up, #3c9a5f) 55%, transparent); } +.ccTile--warn { border-color: color-mix(in srgb, var(--cc-sev-warn, #d9830f) 55%, transparent); } +.ccTile--down { border-color: color-mix(in srgb, var(--cc-sev-down, #cc0000) 55%, transparent); } +.ccTile--up .ccTileValue { color: var(--cc-sev-up, #3c9a5f); } +.ccTile--warn .ccTileValue { color: var(--cc-sev-warn, #d9830f); } +.ccTile--down .ccTileValue { color: var(--cc-sev-down, #cc0000); } + +/* ---- Distribution rows and in-table mini bars ---- */ +.ccDistRow { + display: grid; + grid-template-columns: minmax(80px, 34%) 1fr auto; + align-items: center; + gap: 8px; + margin: 6px 0; + font-size: 12px; +} + +.ccDistLabel { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ccDistTrack { + height: 12px; + border-radius: 6px; + background: color-mix(in srgb, currentColor 12%, transparent); + overflow: hidden; +} + +.ccDistFill { + display: block; + height: 100%; + border-radius: 6px; + background: color-mix(in srgb, currentColor 45%, transparent); +} + +.ccDistValue { + font-variant-numeric: tabular-nums; + color: color-mix(in srgb, currentColor 80%, transparent); +} + +.ccMiniBar { + display: block; + position: relative; + height: 10px; + min-width: 60px; + border-radius: 5px; + background: color-mix(in srgb, currentColor 12%, transparent); + overflow: hidden; +} + +.ccMiniBarFill { + position: absolute; + top: 0; + left: 0; + bottom: 0; + border-radius: 5px; + background: color-mix(in srgb, currentColor 45%, transparent); +} + +/* ---- Small shared helpers ---- */ +.ccEmpty { + color: color-mix(in srgb, currentColor 65%, transparent); + font-style: italic; +} + +.ccPill { + display: inline-block; + padding: 1px 8px; + border-radius: 10px; + font-size: 11px; + background: color-mix(in srgb, currentColor 12%, transparent); +} + +.ccPill--up { background: var(--cc-sev-up, #3c9a5f); color: #fff; } +.ccPill--warn { background: var(--cc-sev-warn, #d9830f); color: #fff; } +.ccPill--down { background: var(--cc-sev-down, #cc0000); color: #fff; } +.ccPill--none { background: color-mix(in srgb, currentColor 45%, transparent); color: #fff; } diff --git a/css/cards.css b/css/cards.css new file mode 100644 index 0000000..d68ef00 --- /dev/null +++ b/css/cards.css @@ -0,0 +1,298 @@ +/* + +-------------------------------------------------------------------------+ + | Copyright (C) 2004-2026 The Cacti Group | + +-------------------------------------------------------------------------+ + | Cacti: The Complete RRDtool-based Graphing Solution | + +-------------------------------------------------------------------------+ +*/ + +/* + * cacti-cards vX.Y - shared "card chrome" (presentation layer). + * + * This file is bundled per-plugin (no cross-plugin or core dependency) and is + * kept byte-identical between the plugins that use it. It styles a grid of + * cards with a draggable header, per-card tools and optional expand/resize. + * All colours come from CSS custom properties the host sets, so it inherits + * the active Cacti theme without baking any palette in. + * + * HTML contract (emitted by the host's PHP): + * + *
+ *
+ *
+ * + *

Title

+ * + * + * + *
+ *
...
+ *
+ *
+ * + * Host theme variables (all optional, sensible fallbacks provided): + * --cc-cols grid column count (default 4) + * --cc-surface page surface behind the cards + * --cc-card card background + * --cc-text card foreground + * --cc-border card / divider border + * --cc-header-bg header background colour + * --cc-header-image header background image (gradient themes) + * --cc-header-fg header foreground + * --cc-sev-up/-warn/-down/-none severity hues (used as a translucent wash + * over the header + its bottom border) + */ + +.ccGrid { + display: grid; + grid-template-columns: repeat(var(--cc-cols, 4), minmax(0, 1fr)); + align-items: start; + gap: 14px; + margin: 10px 4px; + font-variant-numeric: tabular-nums; +} + +/* Column span (width). */ +.ccW1 { grid-column: span 1; } +.ccW2 { grid-column: span 2; } +.ccW3 { grid-column: span 3; } +.ccW4 { grid-column: span 4; } +.ccW5 { grid-column: span 5; } +.ccW6 { grid-column: span 6; } +.ccW7 { grid-column: span 7; } +.ccW8 { grid-column: span 8; } + +/* Row span (height) for the "steps" size model. */ +.ccH1 { grid-row: span 1; } +.ccH2 { grid-row: span 2; } +.ccH3 { grid-row: span 3; } + +.ccCard { + box-sizing: border-box; + min-width: 0; + display: flex; + flex-direction: column; + border: 1px solid var(--cc-border, #cbd8d1); + /* lift the card off the page surface on both light and dark themes */ + background: color-mix(in srgb, var(--cc-text, #23362f) 4%, var(--cc-card, #fff)); + color: var(--cc-text, #23362f); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); + overflow: hidden; +} + +.ccCardDragging { + opacity: 0.5; +} + +.ccCardHeader { + box-sizing: border-box; + /* fixed row height so a tool/handle hover highlight never reflows the header */ + min-height: 34px; + display: flex; + align-items: center; + gap: 8px; + padding: 7px 10px; + border-bottom: 1px solid var(--cc-border, #cbd8d1); + /* paint like the active theme's native html_start_box title bar */ + background-color: var(--cc-header-bg, #e5ece8); + background-image: var(--cc-header-image, none); + background-repeat: repeat-x; + color: var(--cc-header-fg, var(--cc-text, #23362f)); +} + +/* Drag handle: lives on the LEFT of the header; grab it to reorder the card. */ +.ccDrag { + order: -1; + flex: 0 0 auto; + box-sizing: border-box; + padding: 2px 5px; + /* reserve the border so a hover/focus highlight recolours it instead of resizing the header */ + border: 1px solid transparent; + border-radius: 4px; + background: transparent; + color: color-mix(in srgb, currentColor 50%, transparent); + font-size: 13px; + line-height: 1; + cursor: grab; +} + +.ccDrag:hover, +.ccDrag:focus-visible { + color: currentColor; + border-color: transparent; + background: color-mix(in srgb, currentColor 12%, transparent); + outline: none; +} + +.ccDrag:active { + cursor: grabbing; +} + +/* Host toggle to lock reordering (e.g. a "select text" mode): hide the handles. */ +.ccNoDrag .ccDrag { + display: none; +} + +.ccTitle { + flex: 1 1 auto; + min-width: 0; + margin: 0; + font-size: 13px; + font-weight: 600; + line-height: 1.3; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ccTools { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 1px; +} + +.ccTool { + box-sizing: border-box; + padding: 2px 5px; + /* reserve the border so a hover/focus highlight recolours it instead of resizing the header */ + border: 1px solid transparent; + border-radius: 4px; + background: transparent; + color: color-mix(in srgb, currentColor 50%, transparent); + font-size: 12px; + line-height: 1; + cursor: pointer; +} + +.ccTool:hover, +.ccTool:focus-visible { + color: currentColor; + border-color: transparent; + background: color-mix(in srgb, currentColor 12%, transparent); + outline: none; +} + +/* Only the control matching the card's current state is shown. */ +.ccCard:not(.ccCardExpanded) .ccTool[data-tool="collapse"], +.ccCardExpanded .ccTool[data-tool="expand"] { + display: none; +} + +/* Expand/collapse is only meaningful on expandable cards. */ +.ccCard:not([data-expandable="1"]) .ccTool[data-tool="expand"], +.ccCard:not([data-expandable="1"]) .ccTool[data-tool="collapse"] { + display: none; +} + +/* Resize tools only apply to the "steps" size model, and clamp at the ends. */ +.ccCard:not([data-size-model="steps"]) .ccTool[data-tool="shrink"], +.ccCard:not([data-size-model="steps"]) .ccTool[data-tool="grow"] { + display: none; +} + +.ccCardBody { + padding: 4px 12px 10px; + overflow-x: auto; +} + +/* Expandable cards clip to a fixed height until "show more"; a fade hints at the + clipped content. */ +.ccCardExpandable:not(.ccCardExpanded) .ccCardBody { + position: relative; + max-height: 210px; + overflow: hidden; +} + +.ccCardExpandable:not(.ccCardExpanded) .ccCardBody::after { + content: ''; + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 30px; + pointer-events: none; + background: linear-gradient(transparent, color-mix(in srgb, var(--cc-text, #23362f) 4%, var(--cc-card, #fff))); +} + +/* + * Severity wash. Every card carries exactly one data-severity. A single + * translucent colour layer is drawn over the sampled native theme header so the + * strength stays consistent on solid and gradient themes, light and dark. The + * hue comes from a host variable so it follows the theme's colour family. + */ +.ccCard[data-severity="none"] .ccCardHeader { + background-image: + linear-gradient(var(--cc-sev-none, rgba(140, 149, 159, 0.20)), var(--cc-sev-none, rgba(140, 149, 159, 0.20))), + var(--cc-header-image, none); + border-bottom-color: color-mix(in srgb, var(--cc-sev-none-border, #8c959f) 45%, transparent); +} + +.ccCard[data-severity="up"] .ccCardHeader { + background-image: + linear-gradient(var(--cc-sev-up, rgba(148, 179, 107, 0.32)), var(--cc-sev-up, rgba(148, 179, 107, 0.32))), + var(--cc-header-image, none); + border-bottom-color: color-mix(in srgb, var(--cc-sev-up-border, #94b36b) 60%, transparent); +} + +.ccCard[data-severity="warn"] .ccCardHeader { + background-image: + linear-gradient(var(--cc-sev-warn, rgba(255, 143, 30, 0.32)), var(--cc-sev-warn, rgba(255, 143, 30, 0.32))), + var(--cc-header-image, none); + border-bottom-color: color-mix(in srgb, var(--cc-sev-warn-border, #ff8f1e) 60%, transparent); +} + +.ccCard[data-severity="down"] .ccCardHeader { + background-image: + linear-gradient(var(--cc-sev-down, rgba(204, 0, 0, 0.34)), var(--cc-sev-down, rgba(204, 0, 0, 0.34))), + var(--cc-header-image, none); + border-bottom-color: color-mix(in srgb, var(--cc-sev-down-border, #cc0000) 60%, transparent); +} + +/* "Add card" toolbar above the grid. */ +.ccToolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin: 10px 4px 0; +} + +.ccToolbarLabel { + font-size: 12px; + font-weight: 600; + color: var(--cc-text, #23362f); +} + +.ccAdd, +.ccRefreshInterval { + box-sizing: border-box; + padding: 4px 8px; + border: 1px solid var(--cc-border, #cbd8d1); + border-radius: 7px; + background: var(--cc-card, #fff); + color: var(--cc-text, #23362f); + font-size: 12px; +} + +.ccAdd { + min-width: 220px; +} + +.ccRefresh { + display: flex; + align-items: center; + gap: 8px; + margin-left: auto; +} + +/* Maximize dialog: reuse the card body typography on the themed dialog surface. */ +.ccDialogBody { + color: var(--cc-text, #23362f); + font-variant-numeric: tabular-nums; +} diff --git a/includes/dashboard.php b/includes/dashboard.php index f8e2e2d..49c1f38 100644 --- a/includes/dashboard.php +++ b/includes/dashboard.php @@ -42,6 +42,20 @@ function apcupsd_dashboard_print_css(): void { global $config; + // Shared card chrome + chart-widget primitives. On Cacti 1.2.32+ these ship + // in core and are loaded by the common page header; bundle the plugin's own + // copy only when core does not provide them. + // @codeCoverageIgnoreStart -- fallback runs only on cores lacking the bundle; + // the end-to-end run installs a core that ships it, so CI cannot reach here. + if (!file_exists($config['base_path'] . '/include/css/cards.css')) { + print get_md5_include_css('plugins/apcupsd/css/cards.css'); + } + + if (!file_exists($config['base_path'] . '/include/css/card-widgets.css')) { + print get_md5_include_css('plugins/apcupsd/css/card-widgets.css'); + } + // @codeCoverageIgnoreEnd + print get_md5_include_css('plugins/apcupsd/css/apcupsd.css'); $theme = get_selected_theme(); @@ -573,13 +587,13 @@ function apcupsd_dashboard_bullet(string $label, ?float $current, ?float $min, ? $summary[] = __('max %s', apcupsd_dashboard_format_value($max, $unit), 'apcupsd'); } - $head = '
' - . '' . html_escape($label) . '' - . '' . html_escape(implode(' · ', $summary)) . '' + $head = '
' + . '' . html_escape($label) . '' + . '' . html_escape(implode(' · ', $summary)) . '' . '
'; if ($marker_value === null || $scale <= 0) { - return '
' . $head . '
'; + return '
' . $head . '
'; } $lo = max(0.0, min($scale, (float) ($min !== null ? $min : $marker_value))); @@ -590,7 +604,7 @@ function apcupsd_dashboard_bullet(string $label, ?float $current, ?float $min, ? $width = max(0.75, ($hi - $lo) / $scale * 100); $mark = $mk / $scale * 100; - $sev = in_array($severity, ['up', 'recovering', 'down'], true) ? $severity : 'none'; + $sev = ($severity === 'recovering') ? 'warn' : (in_array($severity, ['up', 'down'], true) ? $severity : 'none'); // A faint tick marks the historical average, distinct from the strong marker // at the current reading, so both are visible when they differ. @@ -598,16 +612,16 @@ function apcupsd_dashboard_bullet(string $label, ?float $current, ?float $min, ? if ($avg !== null) { $avg_pos = max(0.0, min($scale, (float) $avg)) / $scale * 100; - $avg_marker = '
'; + $avg_marker = '
'; } - return '
' . $head - . '
' - . '
' + return '
' . $head + . '
' + . '
' . $avg_marker - . '
' + . '
' . '
' - . '
' . html_escape(apcupsd_dashboard_format_value(0.0, $unit)) . '' . html_escape(apcupsd_dashboard_format_value($scale, $unit)) . '
' + . '
' . html_escape(apcupsd_dashboard_format_value(0.0, $unit)) . '' . html_escape(apcupsd_dashboard_format_value($scale, $unit)) . '
' . '
'; } } @@ -630,7 +644,7 @@ function apcupsd_dashboard_bullet(string $label, ?float $current, ?float $min, ? * @return string The gauge HTML. */ function apcupsd_dashboard_gauge(?float $current, ?float $min, ?float $max, float $scale, string $severity, string $center_label, string $sub_label = ''): string { - $sev = in_array($severity, ['up', 'recovering', 'down'], true) ? $severity : 'none'; + $sev = ($severity === 'recovering') ? 'warn' : (in_array($severity, ['up', 'down'], true) ? $severity : 'none'); $frac = ($current !== null && $scale > 0) ? max(0.0, min(1.0, $current / $scale)) : 0.0; $dash = number_format($frac * 100, 2, '.', ''); @@ -649,19 +663,19 @@ function apcupsd_dashboard_gauge(?float $current, ?float $min, ?float $max, floa $ox = 60 + 56 * cos($angle); $oy = 60 - 56 * sin($angle); - return ''; }; - return '
' - . '' - . '' - . '' + return '
' + . '' + . '' + . '' . $tick($min) . $tick($max) . '' - . '
' - . '' . html_escape($center_label) . '' - . ($sub_label !== '' ? '' . html_escape($sub_label) . '' : '') + . '
' + . '' . html_escape($center_label) . '' + . ($sub_label !== '' ? '' . html_escape($sub_label) . '' : '') . '
'; } } @@ -682,7 +696,7 @@ function apcupsd_dashboard_render_bullets(string $group, $ups_id): string { $ups = apcupsd_dashboard_ups($ups_id); if (!cacti_sizeof($ups)) { - return '

' . __esc('No readings have been collected for this UPS yet.', 'apcupsd') . '

'; + return '

' . __esc('No readings have been collected for this UPS yet.', 'apcupsd') . '

'; } apcupsd_dashboard_init_timespan(); @@ -742,7 +756,7 @@ function apcupsd_dashboard_render_bullets(string $group, $ups_id): string { } if ($rows === 0) { - return '

' . __esc('No readings are available for this group yet.', 'apcupsd') . '

'; + return '

' . __esc('No readings are available for this group yet.', 'apcupsd') . '

'; } return $out; @@ -920,13 +934,13 @@ function apcupsd_dashboard_stats_caption(?float $min, ?float $avg, ?float $max, */ function apcupsd_dashboard_gauge_from_reading(?array $reading): string { if (!is_array($reading)) { - return '

' . __esc('No readings have been collected for this UPS yet.', 'apcupsd') . '

'; + return '

' . __esc('No readings have been collected for this UPS yet.', 'apcupsd') . '

'; } $value = $reading['current'] !== null ? $reading['current'] : $reading['avg']; if ($value === null && $reading['min'] === null && $reading['max'] === null) { - return '

' . __esc('No readings are available for this gauge yet.', 'apcupsd') . '

'; + return '

' . __esc('No readings are available for this gauge yet.', 'apcupsd') . '

'; } $unit = $reading['unit']; @@ -1132,19 +1146,19 @@ function apcupsd_dashboard_status_pill(string $status): string { $status = trim($status); $upper = strtoupper($status); - $class = 'apcupsdDashPill--unknown'; + $class = 'ccPill--none'; if ($upper === '') { $status = __('Unknown', 'apcupsd'); } elseif (strpos($upper, 'ONBATT') !== false || strpos($upper, 'LOWBATT') !== false) { - $class = 'apcupsdDashPill--down'; + $class = 'ccPill--down'; } elseif (strpos($upper, 'ONLINE') !== false) { - $class = 'apcupsdDashPill--up'; + $class = 'ccPill--up'; } elseif (strpos($upper, 'CAL') !== false || strpos($upper, 'TRIM') !== false || strpos($upper, 'BOOST') !== false) { - $class = 'apcupsdDashPill--warn'; + $class = 'ccPill--warn'; } - return '' . html_escape($status) . ''; + return '' . html_escape($status) . ''; } } @@ -1177,7 +1191,7 @@ function apcupsd_dashboard_card_body(string $key, $ups_id): string { } if (!$allowed) { - return '

' . __esc('This graph is no longer available.', 'apcupsd') . '

'; + return '

' . __esc('This graph is no longer available.', 'apcupsd') . '

'; } apcupsd_dashboard_init_timespan(); @@ -1202,7 +1216,7 @@ function apcupsd_dashboard_card_body(string $key, $ups_id): string { $reading = apcupsd_dashboard_est_power_reading($ups_id); if ($reading === null) { - return '

' . __esc('Estimated power needs a nominal power rating and a load reading.', 'apcupsd') . '

'; + return '

' . __esc('Estimated power needs a nominal power rating and a load reading.', 'apcupsd') . '

'; } return apcupsd_dashboard_gauge_from_reading($reading); @@ -1211,7 +1225,7 @@ function apcupsd_dashboard_card_body(string $key, $ups_id): string { $cards = apcupsd_dashboard_gauge_cards(); if (!isset($cards[$key])) { - return '

' . __esc('This gauge is no longer available.', 'apcupsd') . '

'; + return '

' . __esc('This gauge is no longer available.', 'apcupsd') . '

'; } return apcupsd_dashboard_gauge_card_body($cards[$key], $ups_id); @@ -1222,7 +1236,7 @@ function apcupsd_dashboard_card_body(string $key, $ups_id): string { switch ($key) { case 'identity': if (!cacti_sizeof($ups)) { - print '

' . __esc('No information has been collected for this UPS yet.', 'apcupsd') . '

'; + print '

' . __esc('No information has been collected for this UPS yet.', 'apcupsd') . '

'; break; } @@ -1289,7 +1303,7 @@ function apcupsd_dashboard_card_body(string $key, $ups_id): string { break; case 'events': if (!cacti_sizeof($ups)) { - print '

' . __esc('No event data has been collected for this UPS yet.', 'apcupsd') . '

'; + print '

' . __esc('No event data has been collected for this UPS yet.', 'apcupsd') . '

'; break; } @@ -1342,33 +1356,35 @@ function apcupsd_dashboard_card_chrome(string $key, string $title, int $span, bo $tools = ''; if ($expandable) { - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; } - $tools .= ''; - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; + $tools .= ''; - $classes = 'apcupsdDashCard apcupsdDashSpan' . $span; + $classes = 'ccCard ccW' . $span; if ($expandable) { - $classes .= ' apcupsdDashCardExpandable'; + $classes .= ' ccCardExpandable'; } if ($expanded) { - $classes .= ' apcupsdDashCardExpanded'; + $classes .= ' ccCardExpanded'; } - $header_class = 'apcupsdDashCardHeader' . ($state !== '' ? ' apcupsdDashCardHeader--' . $state : ''); + $severity = ($state === 'recovering') ? 'warn' : (($state === 'up' || $state === 'down') ? $state : 'none'); - return '
' - . '
' - . '' - . '

' . html_escape($title) . '

' - . '' . $tools . '' + return '
' + . '
' + . '' + . '

' . html_escape($title) . '

' + . '' . $tools . '' . '
' - . '
' . $body . '
' + . '
' . $body . '
' . '
'; } } @@ -1816,18 +1832,15 @@ function apcupsd_dashboard_layout_save(): string { * @return void */ function apcupsd_dashboard_print_refresh(int $seconds, string $page): void { - if ($seconds <= 0) { + if ($seconds <= 0 || !function_exists('set_page_refresh')) { return; } - print ''; + set_page_refresh([ + 'seconds' => $seconds, + 'page' => $page, + 'logout' => 'false' + ]); } } @@ -1932,6 +1945,11 @@ function apcupsd_dashboard(): void { // The dashboard script goes first: when Cacti loads this page through ajax the // scripts run in order, and the refresh script below needs its functions. + // @codeCoverageIgnoreStart -- bundled copy loads only on cores lacking it. + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } + // @codeCoverageIgnoreEnd print ''; apcupsd_dashboard_print_refresh($current_refresh, $refresh_page); @@ -1945,9 +1963,9 @@ function apcupsd_dashboard(): void { $page_refresh_interval = [0 => __('No Refresh', 'apcupsd'), 30 => __('30 Seconds', 'apcupsd'), 60 => __('1 Minute', 'apcupsd'), 300 => __('5 Minutes', 'apcupsd')]; } - print '
'; + print '
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -1986,9 +2004,9 @@ function apcupsd_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -2000,12 +2018,12 @@ function apcupsd_dashboard(): void { } print ''; - print ''; + print ''; print '
'; print ''; print '
'; - print '
'; @@ -2404,7 +2422,7 @@ function apcupsd_fleet_card_body(string $key): string { switch ($key) { case 'overview': if ($total === 0) { - print '

' . __esc('No UPSes are configured yet.', 'apcupsd') . '

'; + print '

' . __esc('No UPSes are configured yet.', 'apcupsd') . '

'; break; } @@ -2434,7 +2452,7 @@ function apcupsd_fleet_card_body(string $key): string { $bar_total = array_sum(array_column($segments, 'count')); if ($bar_total === 0) { - print '

' . __esc('No UPSes are configured yet.', 'apcupsd') . '

'; + print '

' . __esc('No UPSes are configured yet.', 'apcupsd') . '

'; break; } @@ -2460,7 +2478,7 @@ function apcupsd_fleet_card_body(string $key): string { break; case 'readings': if ($enabled === 0) { - print '

' . __esc('No enabled UPSes are reporting readings yet.', 'apcupsd') . '

'; + print '

' . __esc('No enabled UPSes are reporting readings yet.', 'apcupsd') . '

'; break; } @@ -2480,7 +2498,7 @@ function apcupsd_fleet_card_body(string $key): string { break; case 'power': if ($est_count === 0 || $est_watts === null || $est_capacity === null || $est_capacity <= 0) { - print '

' . __esc('Estimated power needs an enabled UPS with a nominal power rating and a load reading.', 'apcupsd') . '

'; + print '

' . __esc('Estimated power needs an enabled UPS with a nominal power rating and a load reading.', 'apcupsd') . '

'; break; } @@ -2506,7 +2524,7 @@ function apcupsd_fleet_card_body(string $key): string { break; case 'gauges': if ($enabled === 0) { - print '

' . __esc('No enabled UPSes are reporting readings yet.', 'apcupsd') . '

'; + print '

' . __esc('No enabled UPSes are reporting readings yet.', 'apcupsd') . '

'; break; } @@ -2599,7 +2617,7 @@ function apcupsd_fleet_card_body(string $key): string { . ''; } } else { - print '' . __esc('No UPSes are configured yet.', 'apcupsd') . ''; + print '' . __esc('No UPSes are configured yet.', 'apcupsd') . ''; } print ''; @@ -2812,6 +2830,11 @@ function apcupsd_fleet_dashboard(): void { // The dashboard script goes first: when Cacti loads this page through ajax the // scripts run in order, and the refresh script below needs its functions. + // @codeCoverageIgnoreStart -- bundled copy loads only on cores lacking it. + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } + // @codeCoverageIgnoreEnd print ''; apcupsd_dashboard_print_refresh($current_refresh, $refresh_page); @@ -2824,9 +2847,9 @@ function apcupsd_fleet_dashboard(): void { $page_refresh_interval = [0 => __('No Refresh', 'apcupsd'), 30 => __('30 Seconds', 'apcupsd'), 60 => __('1 Minute', 'apcupsd'), 300 => __('5 Minutes', 'apcupsd')]; } - print '
'; + print '
'; - print ''; + print ''; print ''; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -2849,9 +2872,9 @@ function apcupsd_fleet_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -2863,12 +2886,12 @@ function apcupsd_fleet_dashboard(): void { } print ''; - print ''; + print ''; print '
'; print ''; print '
'; - print '
'; diff --git a/js/apcupsd_dashboard.js b/js/apcupsd_dashboard.js index 3d7cc9d..17e7c5f 100644 --- a/js/apcupsd_dashboard.js +++ b/js/apcupsd_dashboard.js @@ -16,26 +16,15 @@ +-------------------------------------------------------------------------+ */ -/* UPS Dashboard: the per-UPS drilldown card grid. Mirrors the hmib/intropage - * card interaction model (drag/keyboard reorder, per-card tools, an "Add card" - * catalogue, a Cacti timespan selector, auto-refresh interval + manual refresh) - * with the card order, expanded state and current UPS persisted server-side in - * settings_user. */ - -var apcupsdDashDragging = null; - -/** Cacti's browser auto-logout timer as it was when this script loaded, before the - * dashboard replaces it with its own refresh. Choosing "No Refresh" puts it back (a - * page reload used to). It is kept across re-runs of this script, which can find the - * dashboard's own override in place of the original. */ -var apcupsdDashCoreTimer = typeof apcupsdDashCoreTimer === 'undefined' ? null : apcupsdDashCoreTimer; - -if (typeof refreshIsLogout !== 'undefined' && refreshIsLogout === true && typeof refreshMSeconds !== 'undefined' && typeof refreshPage !== 'undefined') { - apcupsdDashCoreTimer = {ms: refreshMSeconds, page: refreshPage}; -} - -/** The endpoint/scope configuration for a grid, read from its data attributes so - * the per-UPS and fleet dashboards can share this engine. */ +/* UPS Dashboard adapter for the shared card chrome (js/cards.js). The + * CactiCards controller owns drag/keyboard reorder, the per-card tools and the + * debounced layout save; this adapter maps those hooks to apcupsd's upses.php + * endpoints and adds apcupsd's extras: a UPS picker, Cacti's timespan selector + * (its graph and RRD-bullet cards follow the session timespan), an auto-refresh + * interval and a manual refresh-all. Card markup uses the shared .cc* contract + * and the card bodies the shared .cc* chart primitives. */ + +/* The endpoint/scope configuration for a grid, read from its data attributes. */ function apcupsdDashCfg(grid) { return { page: grid.dataset.page || 'upses.php', @@ -44,91 +33,84 @@ function apcupsdDashCfg(grid) { refreshAction: grid.dataset.refreshAction || 'dashboard_refresh', scopeParam: grid.dataset.scopeParam || '', scope: grid.dataset.scope || '', - reload: grid.dataset.reload || 'upses.php', - refreshPage: grid.dataset.refreshPage || '' + reload: grid.dataset.reload || 'upses.php' }; } -/** Build a POST payload for a grid, adding the CSRF token and the grid's scope - * parameter (the UPS id for the per-UPS dashboard; absent for the fleet one). */ +/* Build a POST payload for a grid, adding the CSRF token and the grid's scope + * parameter (the UPS id for the per-UPS dashboard). */ function apcupsdDashPost(grid, extra) { - var cfg = apcupsdDashCfg(grid); var data = {__csrf_magic: csrfMagicToken}; + for (var key in extra) { if (Object.prototype.hasOwnProperty.call(extra, key)) { data[key] = extra[key]; } } + + var cfg = apcupsdDashCfg(grid); + if (cfg.scopeParam) { data[cfg.scopeParam] = cfg.scope; } + return data; } -/** Make a container's sortable headers focusable and screen-reader friendly. */ +/* Make a container's sortable headers focusable and screen-reader friendly. */ function apcupsdDashPrepSortHeaders(container) { if (!container) { return; } + container.querySelectorAll('th.apcupsdDashSortable').forEach(function(th) { if (!th.hasAttribute('tabindex')) { th.setAttribute('tabindex', '0'); } - // Keep the native columnheader role: aria-sort is only valid there, and the - // tabindex + Enter/Space keydown handler already makes it operable. + th.setAttribute('role', 'button'); if (!th.hasAttribute('aria-sort')) { th.setAttribute('aria-sort', 'none'); } }); } -/** Sort a card table by the clicked column header, toggling asc/desc. Numeric - * columns (data-sort="num") sort by the cell's data-sort-value when present. */ +/* Sort a card table by the clicked column header, toggling asc/desc. Numeric + * columns (data-sort="num") sort by the cell's data-sort-value when present. */ function apcupsdDashSortTable(th) { var table = th.closest('table'); + if (!table) { return; } - var tbody = table.tBodies[0]; - if (!tbody) { - return; - } + + var tbody = table.tBodies[0]; var headers = Array.prototype.slice.call(th.parentNode.children); - var index = headers.indexOf(th); - var numeric = th.dataset.sort === 'num'; - var asc = !th.classList.contains('apcupsdDashSortAsc'); + var index = headers.indexOf(th); + var numeric = th.getAttribute('data-sort') === 'num'; + var asc = th.getAttribute('aria-sort') !== 'ascending'; headers.forEach(function(header) { - header.classList.remove('apcupsdDashSortAsc', 'apcupsdDashSortDesc'); - if (header.classList.contains('apcupsdDashSortable')) { + if (header !== th) { header.setAttribute('aria-sort', 'none'); } }); - th.classList.add(asc ? 'apcupsdDashSortAsc' : 'apcupsdDashSortDesc'); + th.setAttribute('aria-sort', asc ? 'ascending' : 'descending'); var rows = Array.prototype.slice.call(tbody.rows).filter(function(row) { return !row.classList.contains('apcupsdDashEmptyRow'); }); - var value = function(row) { - var cell = row.cells[index]; - if (!cell) { - return numeric ? 0 : ''; + rows.sort(function(a, b) { + var x = apcupsdDashCellValue(a.cells[index], numeric); + var y = apcupsdDashCellValue(b.cells[index], numeric); + + if (x < y) { + return asc ? -1 : 1; } - if (numeric) { - var raw = cell.dataset.sortValue !== undefined ? cell.dataset.sortValue : cell.textContent; - var num = parseFloat(String(raw).replace(/[^0-9.\-]/g, '')); - return isNaN(num) ? 0 : num; + if (x > y) { + return asc ? 1 : -1; } - return cell.textContent.trim().toLowerCase(); - }; - - rows.sort(function(a, b) { - var va = value(a); - var vb = value(b); - if (va < vb) { return asc ? -1 : 1; } - if (va > vb) { return asc ? 1 : -1; } return 0; }); @@ -137,37 +119,36 @@ function apcupsdDashSortTable(th) { }); } -/** Remember which header a card's table is sorted by, and in which direction. */ -function apcupsdDashSortSnapshot(card) { - var th = card.querySelector('th.apcupsdDashSortAsc, th.apcupsdDashSortDesc'); - if (!th) { - return null; +/* The sort key of a cell: its data-sort-value when set, else its text; numeric + * columns parse to a number so 9 sorts below 10. */ +function apcupsdDashCellValue(cell, numeric) { + if (!cell) { + return numeric ? 0 : ''; } - return {index: Array.prototype.indexOf.call(th.parentNode.children, th), asc: th.classList.contains('apcupsdDashSortAsc')}; -} -/** Re-apply a remembered sort to a freshly rendered card, so an in-place refresh - * does not throw away the order the user picked. */ -function apcupsdDashSortRestore(card, snapshot) { - if (!snapshot) { - return; + var raw = cell.hasAttribute('data-sort-value') ? cell.getAttribute('data-sort-value') : cell.textContent; + + if (numeric) { + var value = parseFloat(raw); + return isNaN(value) ? 0 : value; } - var th = card.querySelector('th.apcupsdDashSortable:nth-child(' + (snapshot.index + 1) + ')'); - if (!th) { + + return (raw || '').trim().toLowerCase(); +} + +/* Delegate clicks and keyboard activation on a container's sortable headers. */ +function apcupsdDashBindSort(container, namespace) { + if (!container) { return; } - // apcupsdDashSortTable() toggles the direction, so seed the opposite one. - th.classList.toggle('apcupsdDashSortAsc', !snapshot.asc); - apcupsdDashSortTable(th); -} -/** Wire click and Enter/Space sorting on the sortable headers under a root. The - * handlers are delegated, so cards that are refreshed or added later keep working. */ -function apcupsdDashBindSort(root) { - $(root).off('click.apcupsdsort').on('click.apcupsdsort', 'th.apcupsdDashSortable', function() { + apcupsdDashPrepSortHeaders(container); + + $(container).off('click.' + namespace).on('click.' + namespace, 'th.apcupsdDashSortable', function() { apcupsdDashSortTable(this); }); - $(root).off('keydown.apcupsdsort').on('keydown.apcupsdsort', 'th.apcupsdDashSortable', function(event) { + + $(container).off('keydown.' + namespace).on('keydown.' + namespace, 'th.apcupsdDashSortable', function(event) { if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { event.preventDefault(); apcupsdDashSortTable(this); @@ -175,558 +156,179 @@ function apcupsdDashBindSort(root) { }); } +/* Wire the per-UPS dashboard grid to the shared card chrome plus apcupsd's + * extras: the UPS picker, Cacti's timespan selector, the auto-refresh interval + * and the manual refresh-all. */ function initApcupsdDashboard() { $(function() { var grid = document.getElementById('apcupsd_dashboard'); - if (!grid) { + + if (!grid || !window.CactiCards) { return; } - // Delegated so the sortable headers also work in cards that are refreshed or - // added later. - apcupsdDashBindSort(grid); + var cfg = apcupsdDashCfg(grid); - grid.querySelectorAll('.apcupsdDashCard').forEach(function(card) { - apcupsdDashBindCard(grid, card); - }); + function catalogue() { + return typeof apcupsdDashCatalog !== 'undefined' ? apcupsdDashCatalog : null; + } - grid.addEventListener('dragover', function(event) { - if (!apcupsdDashDragging) { - return; - } - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - var before = apcupsdDashDragReference(grid, event.clientX, event.clientY); - if (before == null) { - grid.appendChild(apcupsdDashDragging); - } else if (before !== apcupsdDashDragging) { - grid.insertBefore(apcupsdDashDragging, before); - } - }); + function syncAddOptions() { + var add = document.getElementById('apcupsd_dashboard_add'); + var cat = catalogue(); - // Per-card tool buttons bubble to the grid. - $(grid).off('click.apcupsddash').on('click.apcupsddash', '.apcupsdDashCardTool', function() { - var card = this.closest('.apcupsdDashCard'); - if (!card) { + if (!add || !cat) { return; } - switch (this.dataset.tool) { - case 'expand': card.classList.add('apcupsdDashCardExpanded'); apcupsdDashSaveLayout(grid); break; - case 'collapse': card.classList.remove('apcupsdDashCardExpanded'); apcupsdDashSaveLayout(grid); break; - case 'maximize': apcupsdDashMaximize(card); break; - case 'refresh': apcupsdDashRefreshCard(grid, card); break; - case 'remove': apcupsdDashRemoveCard(grid, card); break; - } - }); - - var add = document.getElementById('apcupsd_dashboard_add'); - if (add) { - $(add).off('change.apcupsddash').on('change.apcupsddash', function() { - var key = this.value; - this.value = ''; - if (key) { - apcupsdDashAddCard(grid, key); - } - }); - } - var ups = document.getElementById('apcupsd_dashboard_ups'); - if (ups) { - // Switch the per-UPS dashboard in place (no full page refresh), like the - // timespan selector and the UPS filter do. - $(ups).off('change.apcupsddash').on('change.apcupsddash', function() { - if (this.value) { - loadPageNoHeader('upses.php?action=view&id=' + encodeURIComponent(this.value) + '&header=false'); + var present = {}; + + grid.querySelectorAll('.ccCard').forEach(function(card) { + if (card.dataset.card) { + present[card.dataset.card] = true; } }); - } - // Changing the timespan loads the dashboard in place (no full page refresh) - // so Cacti's session timespan selector picks up predefined_timespan, which - // drives both the graph cards and the RRD bullet/gauge queries. The grid's - // reload target (per-UPS view or the fleet dashboard) carries the id, so - // build the URL from it and request it without the page header. - var timespan = document.getElementById('apcupsd_dashboard_timespan'); - if (timespan) { - $(timespan).off('change.apcupsddash').on('change.apcupsddash', function() { - var reload = apcupsdDashCfg(grid).reload; - var sep = reload.indexOf('?') === -1 ? '?' : '&'; - loadPageNoHeader(reload + sep + 'predefined_timespan=' + encodeURIComponent(this.value) + '&header=false'); - }); - } + while (add.options.length > 1) { + add.remove(1); + } - // Changing the interval persists the preference through a CSRF-protected POST - // (never a drive-by GET), then applies it straight away without reloading the - // page. If the save fails the dropdown goes back to the interval in force. - var interval = document.getElementById('apcupsd_dashboard_refresh'); - if (interval) { - interval.dataset.previous = interval.value; - $(interval).off('change.apcupsddash').on('change.apcupsddash', function() { - apcupsdDashSaveRefresh(grid, this); + Object.keys(cat).forEach(function(key) { + if (!present[key]) { + var option = document.createElement('option'); + option.value = key; + option.textContent = cat[key]; + add.appendChild(option); + } }); } - var refreshNow = document.getElementById('apcupsd_dashboard_refresh_now'); - if (refreshNow) { - $(refreshNow).off('click.apcupsddash').on('click.apcupsddash', function() { - apcupsdDashRefreshAll(grid, this); + function fetchCard(id, expanded) { + return $.post(cfg.page, apcupsdDashPost(grid, {action: cfg.cardAction, card: id, expanded: expanded ? '1' : '0'}), null, 'json').then(function(d) { + return d && d.html ? d.html : null; }); } - }); -} - -/** Wire a single card's drag handle (mouse + keyboard) and drag events. */ -function apcupsdDashBindCard(grid, card) { - apcupsdDashPrepSortHeaders(card); - - var handle = card.querySelector('.apcupsdDashCardDrag'); - if (!handle) { - return; - } - - // Arm HTML5 drag only from the handle, and disarm on release when no drag - // began so selecting content elsewhere can't drag the card. - var disarm = function() { card.draggable = false; }; - handle.addEventListener('mousedown', function() { - card.draggable = true; - document.addEventListener('mouseup', disarm, {once: true}); - }); - handle.addEventListener('touchstart', function() { - card.draggable = true; - document.addEventListener('touchend', disarm, {once: true}); - document.addEventListener('touchcancel', disarm, {once: true}); - }, {passive: true}); - - // Keyboard-accessible reordering: move the card with the arrow keys. - handle.addEventListener('keydown', function(event) { - var back = event.key === 'ArrowLeft' || event.key === 'ArrowUp'; - var fwd = event.key === 'ArrowRight' || event.key === 'ArrowDown'; - if (!back && !fwd) { - return; - } - event.preventDefault(); - if (back && card.previousElementSibling) { - grid.insertBefore(card, card.previousElementSibling); - } else if (fwd && card.nextElementSibling) { - grid.insertBefore(card.nextElementSibling, card); - } else { - return; - } - handle.focus(); - apcupsdDashSaveLayout(grid); - }); - card.addEventListener('dragstart', function(event) { - apcupsdDashDragging = card; - card.classList.add('apcupsdDashCardDragging'); - event.dataTransfer.effectAllowed = 'move'; - try { event.dataTransfer.setData('text/plain', card.dataset.card || ''); } catch (error) { /* IE guard */ } - }); - - card.addEventListener('dragend', function() { - card.draggable = false; - card.classList.remove('apcupsdDashCardDragging'); - if (apcupsdDashDragging) { - apcupsdDashDragging = null; - apcupsdDashSaveLayout(grid); - } - }); -} - -/** The card the dragged card should be inserted before for the current pointer - * position, or null to append at the end. */ -function apcupsdDashDragReference(grid, x, y) { - var cards = Array.prototype.slice.call(grid.querySelectorAll('.apcupsdDashCard:not(.apcupsdDashCardDragging)')); - for (var i = 0; i < cards.length; i++) { - var rect = cards[i].getBoundingClientRect(); - if (y < rect.top - 1) { - return cards[i]; - } - if (y <= rect.bottom && x < rect.left + rect.width / 2) { - return cards[i]; - } - } - return null; -} + function maximize(card) { + var dialog = document.getElementById('apcupsd_dashboard_dialog'); -/** Add a card from the catalogue: fetch its HTML, append it, persist and refresh - * the "Add" options. */ -function apcupsdDashAddCard(grid, key) { - if (apcupsdDashHasCard(grid, key)) { - return; - } - var cfg = apcupsdDashCfg(grid); - $.post(cfg.page, apcupsdDashPost(grid, {action: cfg.cardAction, card: key}), null, 'json').done(function(data) { - if (!data || !data.html || apcupsdDashHasCard(grid, key)) { - return; - } - var card = apcupsdDashParseCard(data.html); - if (!card) { - return; - } - grid.appendChild(card); - apcupsdDashBindCard(grid, card); - apcupsdDashSaveLayout(grid); - apcupsdDashSyncAddOptions(grid); - }); -} - -/** Whether a card with the given key is currently on the grid. */ -function apcupsdDashHasCard(grid, key) { - var present = false; - grid.querySelectorAll('.apcupsdDashCard').forEach(function(card) { - if (card.dataset.card === key) { - present = true; - } - }); - return present; -} - -/** Remove a card from the page and return it to the "Add" catalogue. */ -function apcupsdDashRemoveCard(grid, card) { - card.parentNode.removeChild(card); - apcupsdDashSaveLayout(grid); - apcupsdDashSyncAddOptions(grid); -} - -/** Re-fetch a single card's HTML and swap it in place, keeping expanded state. */ -function apcupsdDashRefreshCard(grid, card, done) { - var icon = card.querySelector('.apcupsdDashCardTool[data-tool="refresh"] .fa, .apcupsdDashCardTool[data-tool="refresh"] .fas'); - if (icon) { - icon.classList.add('fa-spin'); - } - var settle = function() { - if (icon) { - icon.classList.remove('fa-spin'); - } - if (done) { - done(); - } - }; - var expanded = card.classList.contains('apcupsdDashCardExpanded') ? '1' : '0'; - var cfg = apcupsdDashCfg(grid); - $.post(cfg.page, apcupsdDashPost(grid, {action: cfg.cardAction, card: card.dataset.card, expanded: expanded}), null, 'json').done(function(data) { - if (!data || !data.html || !card.parentNode) { - settle(); - return; - } - var fresh = apcupsdDashParseCard(data.html); - if (!fresh) { - settle(); - return; - } - // Read the card's expanded state and sort at swap time: the user may have toggled - // or sorted it while this request was in flight, and that live state must win over - // anything captured when the request was sent. - var sorted = apcupsdDashSortSnapshot(card); - if (card.classList.contains('apcupsdDashCardExpanded')) { - fresh.classList.add('apcupsdDashCardExpanded'); - } else { - fresh.classList.remove('apcupsdDashCardExpanded'); - } - card.parentNode.replaceChild(fresh, card); - apcupsdDashBindCard(grid, fresh); - apcupsdDashSortRestore(fresh, sorted); - if (done) { - done(); - } - }).fail(settle); -} - -/** Refresh every card on the page, spinning the toolbar glyph until all land. A - * refresh that is still in flight is not stacked on, so a slow server is never - * hit by overlapping rounds. */ -var apcupsdDashRefreshing = false; - -function apcupsdDashRefreshAll(grid, button) { - var icon = button ? button.querySelector('.fa, .fas') : null; - var cards = Array.prototype.slice.call(grid.querySelectorAll('.apcupsdDashCard')); - var pending = cards.length; - if (!pending || apcupsdDashRefreshing) { - return; - } - apcupsdDashRefreshing = true; - if (icon) { - icon.classList.add('fa-spin'); - } - cards.forEach(function(card) { - apcupsdDashRefreshCard(grid, card, function() { - pending--; - if (pending <= 0) { - apcupsdDashRefreshing = false; - if (icon) { - icon.classList.remove('fa-spin'); - } + if (!dialog) { + return; } - }); - }); -} -/** Called by Cacti's page timer (the refreshFunction global, the hook the Graphs - * page uses too): refresh the cards in place instead of reloading the page. Cacti - * re-arms the timer after this returns. The timer outlives ajax page loads, so if - * the dashboard is no longer on screen the page that replaced it gets Cacti's - * normal full-page refresh back. */ -function apcupsdDashAutoRefresh() { - var grid = document.getElementById('apcupsd_dashboard'); - if (grid) { - apcupsdDashRefreshAll(grid, document.getElementById('apcupsd_dashboard_refresh_now')); - return; - } + var title = card.querySelector('.ccTitle'); + var body = card.querySelector('.ccCardBody'); - refreshFunction = ''; - if (typeof loadUrl === 'function' && typeof refreshPage !== 'undefined' && refreshPage !== '') { - loadUrl({url: refreshPage}); - } -} + dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; -var apcupsdDashTimer = null; -var apcupsdDashTimerMs = 0; - -/** One tick of the timer used where Cacti has no refreshFunction hook. It stops - * for good once the dashboard is no longer on screen, so it can never follow - * the user to another page. */ -function apcupsdDashOwnTick() { - apcupsdDashTimer = null; - - var grid = document.getElementById('apcupsd_dashboard'); - if (!grid) { - return; - } - - apcupsdDashRefreshAll(grid, document.getElementById('apcupsd_dashboard_refresh_now')); - apcupsdDashTimer = window.setTimeout(apcupsdDashOwnTick, apcupsdDashTimerMs); -} - -/** Start automatic refresh with the interval the page script put in Cacti's - * refreshMSeconds global. Cacti 1.3+ has a refreshFunction hook in its page - * timer, so use that. Cacti 1.2.x has no such hook and its timer would reload - * the whole page (losing the cards' state), so there the page timer is stopped - * and a timer of our own refreshes the cards instead. */ -function apcupsdDashStartRefresh() { - if (typeof refreshFunction !== 'undefined') { - refreshFunction = 'apcupsdDashAutoRefresh()'; - setupPageTimeout(); - return; - } + apcupsdDashBindSort(dialog, 'apcupsddlgsort'); - if (typeof myRefresh !== 'undefined') { - clearTimeout(myRefresh); - } - if (apcupsdDashTimer !== null) { - clearTimeout(apcupsdDashTimer); - } - - apcupsdDashTimerMs = refreshMSeconds; - apcupsdDashTimer = window.setTimeout(apcupsdDashOwnTick, apcupsdDashTimerMs); -} - -/** Put Cacti's own browser auto-logout timer back, as it was before the dashboard - * replaced it with a refresh. Does nothing when the page had no such timer. */ -function apcupsdDashRestoreCoreTimer() { - if (apcupsdDashCoreTimer === null || typeof setupPageTimeout !== 'function') { - return; - } - - refreshIsLogout = true; - refreshPage = apcupsdDashCoreTimer.page; - refreshMSeconds = apcupsdDashCoreTimer.ms; - - if (typeof refreshFunction !== 'undefined') { - refreshFunction = ''; - } - - setupPageTimeout(); -} - -/** Apply a new auto-refresh interval without reloading the page: stop whichever - * timer is running, then start one for the new interval, or for 0 (off) hand the - * page back to Cacti's own timer. */ -function apcupsdDashSetRefresh(seconds, page) { - if (typeof myRefresh !== 'undefined') { - clearTimeout(myRefresh); - } - if (apcupsdDashTimer !== null) { - clearTimeout(apcupsdDashTimer); - apcupsdDashTimer = null; - } - - if (seconds <= 0) { - apcupsdDashRestoreCoreTimer(); - return; - } - - refreshIsLogout = false; - refreshPage = page; - refreshMSeconds = seconds * 1000; - apcupsdDashStartRefresh(); -} + $(dialog).dialog({ + modal: true, + appendTo: 'body', + width: Math.min(900, $(window).width() - 40), + title: title ? title.textContent : '' + }); + } -/** Set a dropdown's value and bring the widget Cacti draws over it (Select2 on - * 1.2.x, a jQuery UI selectmenu on 1.3) back in line, without running the change - * handlers that save a preference. */ -function apcupsdDashSetSelect(select, value) { - var $select = $(select); + var adapter = { + addControl: 'apcupsd_dashboard_add', - select.value = value; + fetchCard: function(id, state) { + return fetchCard(id, state && state.expanded); + }, - if ($select.data('select2')) { - $select.trigger('change.select2'); - } + onAddCard: function(id) { + return fetchCard(id, false); + }, - if ($select.data('ui-selectmenu')) { - $select.selectmenu('refresh'); - } -} + onLayoutChange: function(state) { + var expanded = {}; -var apcupsdDashRefreshSaving = false; -var apcupsdDashRefreshPending = false; + state.order.forEach(function(id) { + if (state.cards[id] && state.cards[id].expanded) { + expanded[id] = true; + } + }); -/** Save the Refresh dropdown's choice, then apply it. One save is in flight at a - * time: a choice made meanwhile is sent once it settles, so saves cannot finish - * out of order and only a value that was actually saved updates the timer or - * becomes the one a failed save rolls back to. */ -function apcupsdDashSaveRefresh(grid, select) { - if (apcupsdDashRefreshSaving) { - apcupsdDashRefreshPending = true; - return; - } + $.post(cfg.page, apcupsdDashPost(grid, { + action: cfg.layoutAction, + layout: JSON.stringify({order: state.order, expanded: expanded}) + }), null, 'json'); - apcupsdDashRefreshSaving = true; + syncAddOptions(); + }, - var cfg = apcupsdDashCfg(grid); - var value = select.value; - var saved = false; - var message = ''; - - $.post(cfg.page, apcupsdDashPost(grid, {action: cfg.refreshAction, refresh: value}), null, 'json').done(function(data) { - if (data && data.ok) { - saved = true; - select.dataset.previous = value; - apcupsdDashSetRefresh(parseInt(value, 10) || 0, cfg.refreshPage); - } else if (data && data.error) { - message = data.error; - } - }).always(function() { - apcupsdDashRefreshSaving = false; + maximize: function(id, mode, card) { + maximize(card); + } + }; - if (apcupsdDashRefreshPending) { - apcupsdDashRefreshPending = false; + CactiCards.init(grid, adapter); + syncAddOptions(); + apcupsdDashBindSort(grid, 'apcupsdsort'); - if (select.value !== select.dataset.previous) { - apcupsdDashSaveRefresh(grid, select); - return; - } + var ups = document.getElementById('apcupsd_dashboard_ups'); + if (ups) { + $(ups).off('change.apcupsd').on('change.apcupsd', function() { + if (this.value) { + window.location = 'upses.php?action=view&id=' + encodeURIComponent(this.value); + } + }); } - if (saved) { - apcupsdDashShowStatus(grid, ''); - } else { - apcupsdDashSetSelect(select, select.dataset.previous); - apcupsdDashShowStatus(grid, message); + // Changing the timespan reloads the dashboard so Cacti's session timespan + // selector picks up predefined_timespan, which drives the graph cards and + // the RRD bullet queries. + var timespan = document.getElementById('apcupsd_dashboard_timespan'); + if (timespan) { + $(timespan).off('change.apcupsd').on('change.apcupsd', function() { + var reload = cfg.reload; + var sep = reload.indexOf('?') === -1 ? '?' : '&'; + window.location = reload + sep + 'predefined_timespan=' + encodeURIComponent(this.value); + }); } - }); -} -/** Open a copy of a card's body in a large modal dialog. */ -function apcupsdDashMaximize(card) { - var dialog = document.getElementById('apcupsd_dashboard_dialog'); - if (!dialog) { - return; - } - var title = card.querySelector('.apcupsdDashCardTitle'); - var body = card.querySelector('.apcupsdDashCardBody'); - dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; - - // The dialog is a clone outside the grid, so wire its own sort handlers. - apcupsdDashPrepSortHeaders(dialog); - apcupsdDashBindSort(dialog); - - $(dialog).dialog({ - modal: true, - appendTo: 'body', - width: Math.min(900, $(window).width() - 40), - title: title ? title.textContent : '' - }); -} - -/** Parse a card HTML string into its
element. */ -function apcupsdDashParseCard(html) { - var tmp = document.createElement('div'); - tmp.innerHTML = html; - return tmp.querySelector('.apcupsdDashCard'); -} - -/** Rebuild the "Add" dropdown so it lists only cards not currently on the page. */ -function apcupsdDashSyncAddOptions(grid) { - var add = document.getElementById('apcupsd_dashboard_add'); - if (!add || typeof apcupsdDashCatalog === 'undefined') { - return; - } - var present = {}; - grid.querySelectorAll('.apcupsdDashCard').forEach(function(card) { - if (card.dataset.card) { - present[card.dataset.card] = true; - } - }); - while (add.options.length > 1) { - add.remove(1); - } - Object.keys(apcupsdDashCatalog).forEach(function(key) { - if (!present[key]) { - var option = document.createElement('option'); - option.value = key; - option.textContent = apcupsdDashCatalog[key]; - add.appendChild(option); + // Changing the interval persists the preference through a CSRF-protected + // POST (never a drive-by GET), then reloads so Cacti's page refresh arms + // the new interval. If the save fails the dropdown rolls back. + var interval = document.getElementById('apcupsd_dashboard_refresh'); + if (interval) { + $(interval).off('change.apcupsd').on('change.apcupsd', function() { + $.post(cfg.page, apcupsdDashPost(grid, {action: cfg.refreshAction, refresh: this.value}), null, 'json').always(function() { + window.location = cfg.reload; + }); + }); } - }); -} - -/** Show (or clear, with an empty message) the status line above the grid. */ -function apcupsdDashShowStatus(grid, message) { - var status = grid.previousElementSibling && grid.previousElementSibling.querySelector('.apcupsdDashSaveStatus'); - if (status) { - status.textContent = message; - status.hidden = !status.textContent; - } -} -/** Serialize layout POSTs so rapid actions can't persist out of order: one - * request is in flight at a time, and a save requested meanwhile is coalesced - * into a single follow-up that reads the latest DOM, so the final state wins. */ -var apcupsdDashSaveInFlight = false; -var apcupsdDashSaveQueued = false; + var refreshNow = document.getElementById('apcupsd_dashboard_refresh_now'); + if (refreshNow) { + $(refreshNow).off('click.apcupsd').on('click.apcupsd', function() { + var icon = this.querySelector('.fa, .fas'); + var cards = Array.prototype.slice.call(grid.querySelectorAll('.ccCard')); + var pending = cards.length; -function apcupsdDashSaveLayout(grid) { - if (apcupsdDashSaveInFlight) { - apcupsdDashSaveQueued = true; - return; - } - apcupsdDashSaveInFlight = true; + if (!pending) { + return; + } - var order = []; - var expanded = {}; - grid.querySelectorAll('.apcupsdDashCard').forEach(function(card) { - if (!card.dataset.card) { - return; - } - order.push(card.dataset.card); - if (card.classList.contains('apcupsdDashCardExpanded')) { - expanded[card.dataset.card] = true; - } - }); + if (icon) { + icon.classList.add('fa-spin'); + } - var cfg = apcupsdDashCfg(grid); - $.post(cfg.page, apcupsdDashPost(grid, { - action: cfg.layoutAction, - layout: JSON.stringify({order: order, expanded: expanded}) - }), null, 'json').done(function(data) { - apcupsdDashShowStatus(grid, data && data.error ? data.error : ''); - }).always(function() { - apcupsdDashSaveInFlight = false; - if (apcupsdDashSaveQueued) { - apcupsdDashSaveQueued = false; - apcupsdDashSaveLayout(grid); + cards.forEach(function(card) { + fetchCard(card.dataset.card, card.classList.contains('ccCardExpanded')).then(function(html) { + if (html && card.parentNode && window.CactiCards) { + CactiCards.replaceCard(grid, adapter, card, html); + } + }).always(function() { + pending--; + if (pending <= 0 && icon) { + icon.classList.remove('fa-spin'); + } + }); + }); + }); } }); } diff --git a/js/cards.js b/js/cards.js new file mode 100644 index 0000000..0ca94cd --- /dev/null +++ b/js/cards.js @@ -0,0 +1,407 @@ +/* + +-------------------------------------------------------------------------+ + | Copyright (C) 2004-2026 The Cacti Group | + +-------------------------------------------------------------------------+ + | Cacti: The Complete RRDtool-based Graphing Solution | + +-------------------------------------------------------------------------+ +*/ + +/* + * cacti-cards vX.Y - shared "card chrome" controller (interaction layer). + * + * Bundled per-plugin with no cross-plugin or core dependency and kept + * byte-identical between the plugins that use it. It wires the DOM behaviour + * for a .ccGrid of .ccCard elements (see cards.css for the HTML contract): + * keyboard-accessible drag/drop reordering, the per-card tool buttons + * (expand/collapse, grow/shrink, maximize, refresh, remove), an optional + * "add card" control, and debounced layout persistence. Everything that is + * plugin-specific (fetching a card, persisting layout, the add catalogue, + * maximize, resize) is delegated to an adapter the host supplies. + * + * Usage (host, from an external nonce'd init or its own JS): + * CactiCards.init(document.getElementById('my_grid'), { + * fetchCard: function(id, state) { return Promise; }, + * onLayoutChange:function(state) { ... persist {order, cards} ... }, + * onAddCard: function(id) { return Promise; }, + * onRemoveCard: function(id) { return Promise|any; }, + * onResize: function(id, dir, cardEl) { return Promise|any; }, // 'grow'|'shrink' + * maximize: function(id, mode, cardEl) { ... }, // mode from data-maximize + * applyTheme: function(gridEl) { ... set --cc-* vars ... } + * }); + * + * The adapter is optional; every hook has a safe no-op default. init() is + * idempotent per grid element. + */ + +window.CactiCards = window.CactiCards || (function() { + 'use strict'; + + var dragging = null; + + function cardSel(adapter) { + return adapter.cardSelector || '.ccCard'; + } + + function cardId(card, adapter) { + return card.getAttribute(adapter.idAttr || 'data-card'); + } + + /* Locate the live card element for an id, used to re-resolve a reference that + * an overlapping replacement may have detached. */ + function findCard(grid, adapter, id) { + var match = null; + if (id == null) { + return null; + } + grid.querySelectorAll(cardSel(adapter)).forEach(function(card) { + if (match === null && cardId(card, adapter) === id) { + match = card; + } + }); + return match; + } + + /* Keep the documented data-* contract (data-expandable / data-expanded) in + * sync with the classes the CSS clipping and serialize() rely on, so a host + * may drive card state through either representation. Called whenever a card + * is (re)bound: initial, added, or refreshed. */ + function normalizeState(card) { + var expandable = card.getAttribute('data-expandable'); + if (expandable === '1' || expandable === 'true') { + card.classList.add('ccCardExpandable'); + } else if (expandable != null) { + card.classList.remove('ccCardExpandable'); + } + if (card.classList.contains('ccCardExpandable')) { + card.setAttribute('data-expandable', '1'); + } + + var expanded = card.getAttribute('data-expanded'); + if (expanded === '1' || expanded === 'true') { + card.classList.add('ccCardExpanded'); + } else if (expanded != null) { + card.classList.remove('ccCardExpanded'); + } + card.setAttribute('data-expanded', card.classList.contains('ccCardExpanded') ? '1' : '0'); + } + + /* Collect the current order and per-card state for persistence. */ + function serialize(grid, adapter) { + var order = []; + var cards = {}; + + grid.querySelectorAll(cardSel(adapter)).forEach(function(card) { + var id = cardId(card, adapter); + if (id == null) { + return; + } + order.push(id); + cards[id] = { + expanded: card.classList.contains('ccCardExpanded'), + height: Number.parseInt(card.getAttribute('data-height') || '1', 10) + }; + }); + + return { order: order, cards: cards }; + } + + /* Debounce layout saves so a burst of reorders coalesces into one call. */ + function saveLayout(grid, adapter) { + if (typeof adapter.onLayoutChange !== 'function') { + return; + } + if (grid.__ccSaveTimer) { + clearTimeout(grid.__ccSaveTimer); + } + grid.__ccSaveTimer = setTimeout(function() { + grid.__ccSaveTimer = null; + adapter.onLayoutChange(serialize(grid, adapter)); + }, 250); + } + + /* The insertion reference for a drop: the first card that follows the pointer + * in reading order. Resolve the pointer's row before comparing horizontal + * centres so dragging over a later card in a row no longer snaps the + * insertion point back to the start of that row. */ + function dragReference(grid, adapter, x, y) { + var cards = Array.prototype.slice.call(grid.querySelectorAll(cardSel(adapter) + ':not(.ccCardDragging)')); + var rowMatch = null; // first card in the pointer's row whose centre is past x + var belowMatch = null; // first card that begins in a row below the pointer + + cards.forEach(function(card) { + var box = card.getBoundingClientRect(); + if (y >= box.top && y <= box.bottom) { + // Pointer is within this card's row band: compare horizontally. + if (rowMatch === null && x < box.left + box.width / 2) { + rowMatch = card; + } + } else if (y < box.top && belowMatch === null) { + // This card starts in a row below the pointer; it ends the + // pointer's row when nothing in that row is past the pointer. + belowMatch = card; + } + }); + + return rowMatch || belowMatch; + } + + /* Swap a card's markup in place (after refresh/add) and re-bind it. */ + function replaceCard(grid, adapter, card, html) { + var tmp = document.createElement('div'); + tmp.innerHTML = (html || '').trim(); + var fresh = tmp.querySelector(cardSel(adapter)) || tmp.firstElementChild; + if (!fresh) { + return null; + } + // Overlapping refresh/resize responses may reference a card that an + // earlier response already swapped out, leaving the captured node + // detached. Re-resolve the live element by id so the latest response + // replaces what is currently in the grid instead of throwing on (and + // losing the update to) a detached node. + var target = card; + if (!grid.contains(target)) { + target = findCard(grid, adapter, cardId(card, adapter)); + } + if (!target || !target.parentNode) { + return null; + } + target.parentNode.replaceChild(fresh, target); + bindCard(grid, adapter, fresh); + if (typeof adapter.applyTheme === 'function') { + adapter.applyTheme(grid); + } + return fresh; + } + + function refreshCard(grid, adapter, card) { + var id = cardId(card, adapter); + // Hosts that inject into an inner body (rather than replacing the whole + // card) provide onRefresh and keep ownership of the swap. + if (typeof adapter.onRefresh === 'function') { + adapter.onRefresh(id, card); + return; + } + if (typeof adapter.fetchCard !== 'function') { + return; + } + var state = { + expanded: card.classList.contains('ccCardExpanded'), + height: Number.parseInt(card.getAttribute('data-height') || '1', 10) + }; + Promise.resolve(adapter.fetchCard(id, state)).then(function(html) { + if (html != null) { + replaceCard(grid, adapter, card, html); + } + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); + } + + function removeCard(grid, adapter, card) { + var id = cardId(card, adapter); + if (typeof adapter.onRemoveCard === 'function') { + adapter.onRemoveCard(id, card); + } + card.parentNode.removeChild(card); + saveLayout(grid, adapter); + } + + function resizeCard(grid, adapter, card, dir) { + var id = cardId(card, adapter); + if (typeof adapter.onResize === 'function') { + Promise.resolve(adapter.onResize(id, dir, card)).then(function(html) { + if (typeof html === 'string') { + replaceCard(grid, adapter, card, html); + } + saveLayout(grid, adapter); + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); + } else { + saveLayout(grid, adapter); + } + } + + /* Wire a single card: its drag handle (mouse + touch + keyboard) and drag + * events. Handle interactions are DELEGATED from the persistent card element + * so they survive hosts that replace the header markup on refresh/reload. */ + function bindCard(grid, adapter, card) { + if (card.__ccBound) { + return; + } + card.__ccBound = true; + + normalizeState(card); + + var onHandle = function(target) { + return target && target.closest && target.closest('.ccDrag'); + }; + + // Arm HTML5 drag only from the handle, and disarm on release when no drag + // began so selecting content elsewhere can't drag the card. + var disarm = function() { card.draggable = false; }; + card.addEventListener('mousedown', function(event) { + if (!onHandle(event.target)) { + return; + } + card.draggable = true; + document.addEventListener('mouseup', disarm, { once: true }); + }); + card.addEventListener('touchstart', function(event) { + if (!onHandle(event.target)) { + return; + } + card.draggable = true; + document.addEventListener('touchend', disarm, { once: true }); + document.addEventListener('touchcancel', disarm, { once: true }); + }, { passive: true }); + + // Keyboard-accessible reordering with the arrow keys. + card.addEventListener('keydown', function(event) { + if (!onHandle(event.target)) { + return; + } + var back = event.key === 'ArrowLeft' || event.key === 'ArrowUp'; + var fwd = event.key === 'ArrowRight' || event.key === 'ArrowDown'; + if (!back && !fwd) { + return; + } + event.preventDefault(); + if (back && card.previousElementSibling) { + grid.insertBefore(card, card.previousElementSibling); + } else if (fwd && card.nextElementSibling) { + grid.insertBefore(card.nextElementSibling, card); + } else { + return; + } + var handle = card.querySelector('.ccDrag'); + if (handle) { + handle.focus(); + } + saveLayout(grid, adapter); + }); + + card.addEventListener('dragstart', function(event) { + // Only start a reorder when the card itself is the armed drag source. + // Native drags bubbling up from links or images in the body (or any + // drag while the handle is hidden via .ccNoDrag, which leaves the card + // unarmed) must not enter reorder mode. + if (!card.draggable || event.target !== card) { + return; + } + dragging = card; + card.classList.add('ccCardDragging'); + }); + card.addEventListener('dragend', function() { + // Native HTML drag-and-drop suppresses the mouseup that would + // otherwise disarm the card, so disarm here on every drag end. + disarm(); + if (dragging !== card) { + return; + } + card.classList.remove('ccCardDragging'); + dragging = null; + saveLayout(grid, adapter); + }); + } + + function init(grid, adapter) { + if (!grid || grid.__ccInit) { + return; + } + grid.__ccInit = true; + adapter = adapter || {}; + + if (typeof adapter.applyTheme === 'function') { + adapter.applyTheme(grid); + } + + grid.querySelectorAll(cardSel(adapter)).forEach(function(card) { + bindCard(grid, adapter, card); + }); + + grid.addEventListener('dragover', function(event) { + if (!dragging || dragging.parentNode !== grid) { + return; + } + event.preventDefault(); + if (event.dataTransfer) { + event.dataTransfer.dropEffect = 'move'; + } + var before = dragReference(grid, adapter, event.clientX, event.clientY); + if (before == null) { + grid.appendChild(dragging); + } else if (before !== dragging) { + grid.insertBefore(dragging, before); + } + }); + + // Per-card tool buttons bubble up to the grid. + grid.addEventListener('click', function(event) { + var tool = event.target.closest ? event.target.closest('.ccTool') : null; + if (!tool || !grid.contains(tool)) { + return; + } + var card = tool.closest(cardSel(adapter)); + if (!card) { + return; + } + // Tools may be rendered as anchors (e.g. remove); never navigate. + event.preventDefault(); + switch (tool.getAttribute('data-tool')) { + case 'expand': + card.classList.add('ccCardExpanded'); + card.setAttribute('data-expanded', '1'); + saveLayout(grid, adapter); + break; + case 'collapse': + card.classList.remove('ccCardExpanded'); + card.setAttribute('data-expanded', '0'); + saveLayout(grid, adapter); + break; + case 'grow': resizeCard(grid, adapter, card, 'grow'); break; + case 'shrink': resizeCard(grid, adapter, card, 'shrink'); break; + case 'maximize': + if (typeof adapter.maximize === 'function') { + adapter.maximize(cardId(card, adapter), card.getAttribute('data-maximize') || 'body', card); + } + break; + case 'refresh': refreshCard(grid, adapter, card); break; + case 'remove': removeCard(grid, adapter, card); break; + } + }); + + // Optional "add card" control referenced by adapter.addControl (an element or id). + var add = adapter.addControl; + if (typeof add === 'string') { + add = document.getElementById(add); + } + if (add) { + add.addEventListener('change', function() { + var id = this.value; + this.value = ''; + if (id && typeof adapter.onAddCard === 'function') { + Promise.resolve(adapter.onAddCard(id)).then(function(html) { + if (html == null) { + return; + } + var tmp = document.createElement('div'); + tmp.innerHTML = String(html).trim(); + var fresh = tmp.querySelector(cardSel(adapter)) || tmp.firstElementChild; + if (fresh) { + grid.appendChild(fresh); + bindCard(grid, adapter, fresh); + if (typeof adapter.applyTheme === 'function') { + adapter.applyTheme(grid); + } + saveLayout(grid, adapter); + } + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); + } + }); + } + } + + return { + init: init, + serialize: serialize, + replaceCard: replaceCard, + bindCard: bindCard + }; +})(); diff --git a/tests/Unit/DashboardRefreshTest.php b/tests/Unit/DashboardRefreshTest.php index c907dc0..257fb27 100644 --- a/tests/Unit/DashboardRefreshTest.php +++ b/tests/Unit/DashboardRefreshTest.php @@ -8,11 +8,10 @@ */ /* - * The dashboards arm Cacti's page timer through the refreshMSeconds / - * refreshPage / refreshIsLogout globals (as graph_view.php does) rather than - * set_page_refresh(), which parks the interval in the session where it can be - * applied to whichever page renders next instead of clearing when the user - * leaves the dashboard. + * The UPS and Fleet dashboards arm auto-refresh through Cacti's standard + * set_page_refresh(), the same way the shared Card API dashboards do, and the + * adapter reloads the page to apply a changed interval after persisting it + * through the CSRF-protected refresh endpoint. */ describe('dashboard auto-refresh', function () { @@ -24,39 +23,30 @@ return (string) $contents; }; - it('does not store the refresh interval in the session', function () use ($read) { - foreach (['includes/dashboard.php', 'upses.php', 'includes/helpers.php', 'js/apcupsd_dashboard.js'] as $file) { - expect($read($file))->not->toContain('set_page_refresh'); - } - }); - - it('sets the Cacti refresh globals from a ready callback and re-arms the page timer', function () use ($read) { + it('arms Cacti\'s page refresh through set_page_refresh from both dashboards', function () use ($read) { $source = $read('includes/dashboard.php'); expect($source)->toContain('function apcupsd_dashboard_print_refresh('); - expect($source)->toContain("'refreshMSeconds = '"); - expect($source)->toContain("'refreshPage = '"); - expect($source)->toContain("'refreshIsLogout = false;'"); - expect($source)->toContain('else { setupPageTimeout(); }'); - expect($source)->toContain('document.getElementById("apcupsd_dashboard")'); + expect($source)->toContain('set_page_refresh(['); + expect($source)->toContain("'seconds' => \$seconds,"); + expect($source)->toContain("'page' => \$page,"); + expect(substr_count($source, 'apcupsd_dashboard_print_refresh($current_refresh, $refresh_page);'))->toBe(2); }); - it('arms the timer from both the Fleet and the per-UPS dashboard', function () use ($read) { + it('does nothing when Refresh is off or the core helper is missing', function () use ($read) { $source = $read('includes/dashboard.php'); - expect($source)->toContain("\$refresh_page = \$config['url_path'] . 'plugins/apcupsd/upses.php?action=dashboard&header=false';"); - expect($source)->toContain("\$refresh_page = \$config['url_path'] . 'plugins/apcupsd/upses.php?action=view&id=' . \$ups_id . '&header=false';"); - expect(substr_count($source, 'apcupsd_dashboard_print_refresh($current_refresh, $refresh_page);'))->toBe(2); + expect($source)->toContain("if (\$seconds <= 0 || !function_exists('set_page_refresh')) {"); }); - it('exposes the refresh URL on both grids so the dropdown can arm the timer', function () use ($read) { + it('arms the timer from both the Fleet and the per-UPS dashboard', function () use ($read) { $source = $read('includes/dashboard.php'); - expect(substr_count($source, "' data-refresh-page=\"' . html_escape(\$refresh_page) . '\"'"))->toBe(2); - expect($read('js/apcupsd_dashboard.js'))->toContain("refreshPage: grid.dataset.refreshPage || ''"); + expect($source)->toContain("\$refresh_page = \$config['url_path'] . 'plugins/apcupsd/upses.php?action=dashboard&header=false';"); + expect($source)->toContain("\$refresh_page = \$config['url_path'] . 'plugins/apcupsd/upses.php?action=view&id=' . \$ups_id . '&header=false';"); }); - it('applies a changed Refresh interval without reloading the page', function () use ($read) { + it('reloads to apply a changed Refresh interval after persisting it', function () use ($read) { $js = $read('js/apcupsd_dashboard.js'); $start = strpos($js, "document.getElementById('apcupsd_dashboard_refresh')"); @@ -65,71 +55,25 @@ expect($start)->toBeGreaterThan(0); expect($end)->toBeGreaterThan($start); - $handler = substr($js, $start, $end - $start); - - expect($handler)->toContain('apcupsdDashSaveRefresh(grid, this);'); - expect($handler)->not->toContain('window.location'); - - $save = substr($js, (int) strpos($js, 'function apcupsdDashSaveRefresh(')); - - expect($save)->not->toContain('window.location'); - expect($save)->not->toContain('location.reload'); - expect($save)->toContain('apcupsdDashSetRefresh(parseInt(value, 10) || 0, cfg.refreshPage);'); - }); - - it('applies only the interval that was saved, using the value that was submitted', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain('var value = select.value;'); - expect($js)->toContain('refresh: value}'); - expect($js)->toContain('select.dataset.previous = value;'); - expect($js)->not->toContain('select.dataset.previous = select.value;'); - }); - - it('keeps one save in flight and sends a choice made meanwhile after it settles', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); + $handler = substr($js, (int) $start, (int) $end - (int) $start); - expect($js)->toContain('var apcupsdDashRefreshSaving = false;'); - expect($js)->toContain('apcupsdDashRefreshPending = true;'); - expect($js)->toContain('if (select.value !== select.dataset.previous) {'); - expect($js)->toContain('apcupsdDashSaveRefresh(grid, select);'); + expect($handler)->toContain('action: cfg.refreshAction, refresh: this.value'); + expect($handler)->toContain('window.location = cfg.reload;'); }); - it('rolls the picker back through its widget without running the save handler', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain('function apcupsdDashSetSelect(select, value) {'); - expect($js)->toContain("\$select.trigger('change.select2');"); - expect($js)->toContain("\$select.selectmenu('refresh');"); - expect($js)->toContain('apcupsdDashSetSelect(select, select.dataset.previous);'); - - // A namespaced trigger, so the 'change.apcupsddash' save handler does not run. - expect($js)->not->toContain("trigger('change')"); - }); - - it('puts Cacti\'s browser logout timer back when Refresh is turned off', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - // Remembered when the script loads, before the dashboard overrides it. - expect($js)->toContain('var apcupsdDashCoreTimer = typeof apcupsdDashCoreTimer === \'undefined\' ? null : apcupsdDashCoreTimer;'); - expect($js)->toContain('refreshIsLogout === true'); - expect(strpos($js, 'apcupsdDashCoreTimer = {ms: refreshMSeconds, page: refreshPage};'))->toBeLessThan(strpos($js, 'function apcupsdDashCfg(')); - - expect($js)->toContain('function apcupsdDashRestoreCoreTimer() {'); - expect($js)->toContain('refreshIsLogout = true;'); - expect($js)->toContain('refreshPage = apcupsdDashCoreTimer.page;'); - expect($js)->toContain('refreshMSeconds = apcupsdDashCoreTimer.ms;'); + it('persists only an interval the refresh picker offers, through a CSRF-checked POST', function () use ($read) { + $source = $read('includes/dashboard.php'); - // "Off" restores it, and never when there was no such timer to restore. - expect(preg_match('/if \(seconds <= 0\) \{\s*apcupsdDashRestoreCoreTimer\(\);\s*return;\s*\}/', $js))->toBe(1); - expect($js)->toContain('if (apcupsdDashCoreTimer === null || typeof setupPageTimeout !== \'function\') {'); + expect($source)->toContain('function apcupsd_dashboard_refresh_save(): string {'); + expect($source)->toContain("set_user_setting('apcupsd_dashboard_refresh', (int) \$posted);"); + expect($source)->toContain("!csrf_check(false)"); }); - it('loads the dashboard script before the script that starts the refresh', function () use ($read) { + it('loads the shared controller and the dashboard script before the refresh is armed', function () use ($read) { $source = $read('includes/dashboard.php'); - // Cacti runs ajax-loaded scripts in order, so the functions must be defined first. expect(substr_count($source, 'plugins/apcupsd/js/apcupsd_dashboard.js?v='))->toBe(2); + expect(substr_count($source, 'plugins/apcupsd/js/cards.js?v='))->toBe(2); $offset = 0; @@ -139,123 +83,7 @@ expect($script)->toBeLessThan($refresh); - $offset = $refresh + 1; + $offset = (int) $refresh + 1; } }); - - it('swaps the running timer for the new interval, or stops it for No Refresh', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect(preg_match('/function apcupsdDashSetRefresh\(seconds, page\) \{\s*if \(typeof myRefresh !== \'undefined\'\) \{\s*clearTimeout\(myRefresh\);\s*\}/', $js))->toBe(1); - expect($js)->toContain('if (seconds <= 0) {'); - expect($js)->toContain('refreshMSeconds = seconds * 1000;'); - expect($js)->toContain('refreshPage = page;'); - - // Stopping must happen before the early return for "off", and starting after it. - expect(strpos($js, 'clearTimeout(myRefresh);', strpos($js, 'function apcupsdDashSetRefresh(')))->toBeLessThan(strpos($js, 'if (seconds <= 0) {')); - expect(strpos($js, 'if (seconds <= 0) {'))->toBeLessThan(strpos($js, 'refreshMSeconds = seconds * 1000;')); - }); - - it('hands the interval to the dashboard script and falls back to the page timer without it', function () use ($read) { - $source = $read('includes/dashboard.php'); - - expect($source)->toContain('if (typeof apcupsdDashStartRefresh === "function") { apcupsdDashStartRefresh(); } else { setupPageTimeout(); }'); - - // The interval has to be in refreshMSeconds before the script reads it. - expect(strpos($source, "'refreshMSeconds = '"))->toBeLessThan(strpos($source, 'apcupsdDashStartRefresh();')); - }); - - it('refreshes the cards in place through Cacti\'s refreshFunction hook where core has one', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain('function apcupsdDashAutoRefresh()'); - expect($js)->toContain("apcupsdDashRefreshAll(grid, document.getElementById('apcupsd_dashboard_refresh_now'))"); - expect($js)->toContain("refreshFunction = 'apcupsdDashAutoRefresh()';"); - - // Support is detected before refreshFunction is assigned, otherwise the assignment itself - // would make Cacti 1.2.x (whose timer ignores it and reloads the page) look supported. - expect(strpos($js, "typeof refreshFunction !== 'undefined'"))->toBeLessThan(strpos($js, "refreshFunction = 'apcupsdDashAutoRefresh()';")); - }); - - it('uses its own timer where core has no refreshFunction hook (Cacti 1.2.x)', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain('function apcupsdDashStartRefresh()'); - expect($js)->toContain('clearTimeout(myRefresh);'); - expect($js)->toContain('apcupsdDashTimer = window.setTimeout(apcupsdDashOwnTick, apcupsdDashTimerMs);'); - expect($js)->toContain('apcupsdDashTimerMs = refreshMSeconds;'); - }); - - it('ends its own timer once the dashboard has left the screen', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect(preg_match('/function apcupsdDashOwnTick\(\) \{\s*apcupsdDashTimer = null;\s*var grid = document\.getElementById\(\'apcupsd_dashboard\'\);\s*if \(!grid\) \{\s*return;\s*\}/', $js))->toBe(1); - }); - - it('hands another page back to Cacti\'s own refresh when the dashboard has gone', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain("refreshFunction = '';"); - expect($js)->toContain('loadUrl({url: refreshPage});'); - }); - - it('does not stack refresh rounds and keeps the chosen sort across an in-place refresh', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->toContain('if (!pending || apcupsdDashRefreshing) {'); - expect($js)->toContain('var sorted = apcupsdDashSortSnapshot(card);'); - expect($js)->toContain('apcupsdDashSortRestore(fresh, sorted);'); - }); - - it('captures the live sort when the refreshed card replaces the old one, not when the request is sent', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect(strpos($js, 'var sorted = apcupsdDashSortSnapshot(card);'))->toBeGreaterThan(strpos($js, 'function apcupsdDashRefreshCard(')); - expect(strpos($js, 'var sorted = apcupsdDashSortSnapshot(card);'))->toBeGreaterThan(strpos($js, '.done(function(data) {')); - expect(strpos($js, 'var sorted = apcupsdDashSortSnapshot(card);'))->toBeLessThan(strpos($js, 'card.parentNode.replaceChild(fresh, card);')); - }); - - it('has no recurring browser timer other than the 1.2.x fallback', function () use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - expect($js)->not->toContain('setInterval'); - - // Every setTimeout() is the fallback timer, which stops itself when the dashboard is gone. - preg_match_all('/setTimeout\s*\(\s*([A-Za-z_]+)/', $js, $matches); - - expect($matches[1])->not->toBe([]); - - foreach ($matches[1] as $callback) { - expect($callback)->toBe('apcupsdDashOwnTick'); - } - }); - - it('navigates in place rather than reloading the whole page', function (string $startMarker, string $endMarker, string $expected) use ($read) { - $js = $read('js/apcupsd_dashboard.js'); - - $start = strpos($js, $startMarker); - $end = strpos($js, $endMarker); - - expect($start)->toBeGreaterThan(0); - expect($end)->toBeGreaterThan($start); - - $handler = substr($js, $start, $end - $start); - - expect($handler)->toContain($expected); - expect($handler)->not->toContain('window.location'); - expect($handler)->not->toContain('location.reload'); - })->with([ - // The per-UPS and the Fleet dashboard share the timespan handler, so one - // in-place load (header-less, like the UPS filter) covers both. - 'timespan selector' => [ - "document.getElementById('apcupsd_dashboard_timespan')", - "document.getElementById('apcupsd_dashboard_refresh')", - "loadPageNoHeader(reload + sep + 'predefined_timespan=' + encodeURIComponent(this.value) + '&header=false');", - ], - 'UPS selector' => [ - "document.getElementById('apcupsd_dashboard_ups')", - "document.getElementById('apcupsd_dashboard_timespan')", - "loadPageNoHeader('upses.php?action=view&id=' + encodeURIComponent(this.value) + '&header=false');", - ], - ]); }); diff --git a/tests/Unit/DashboardRrdStatsTest.php b/tests/Unit/DashboardRrdStatsTest.php index 10d707c..b74ca58 100644 --- a/tests/Unit/DashboardRrdStatsTest.php +++ b/tests/Unit/DashboardRrdStatsTest.php @@ -245,7 +245,7 @@ function apcupsd_test_fleet(array $upses): void { it('labels the track ends with the axis, not with N/A', function () { $html = apcupsd_dashboard_bullet('Battery Voltage', 27.2, null, null, null, 30.0, ' V', ''); - expect($html)->toContain('
0 V30 V
'); + expect($html)->toContain('
0 V30 V
'); expect($html)->not->toContain('N/A'); }); From 658e731405b49210003bfe806372d944f8fc9745 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Mon, 9 Nov 2026 16:42:31 -0500 Subject: [PATCH 2/7] cards: update apcupsd sort-wiring assertions for the shared adapter The Fleet-table sort tests asserted the old controller source (hardcoded namespaces, per-card header prep); update them to the thin adapter which parameterises the sort namespace and binds the maximize dialog through apcupsdDashBindSort(dialog, ...). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/Unit/EstimatedWattsTest.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/Unit/EstimatedWattsTest.php b/tests/Unit/EstimatedWattsTest.php index 4fc423e..1fb4fb2 100644 --- a/tests/Unit/EstimatedWattsTest.php +++ b/tests/Unit/EstimatedWattsTest.php @@ -100,18 +100,17 @@ $js = $read('js/apcupsd_dashboard.js'); - expect($js)->toContain("on('click.apcupsdsort', 'th.apcupsdDashSortable'"); - expect($js)->toContain("on('keydown.apcupsdsort', 'th.apcupsdDashSortable'"); + expect($js)->toContain("on('click.' + namespace, 'th.apcupsdDashSortable'"); + expect($js)->toContain("on('keydown.' + namespace, 'th.apcupsdDashSortable'"); expect($js)->toContain('function apcupsdDashSortTable(th)'); - expect($js)->toContain('apcupsdDashPrepSortHeaders(card)'); + expect($js)->toContain('apcupsdDashPrepSortHeaders(container)'); expect($js)->toContain("setAttribute('aria-sort'"); }); it('also sorts in the maximize dialog', function () use ($read) { $js = $read('js/apcupsd_dashboard.js'); - expect($js)->toContain('apcupsdDashPrepSortHeaders(dialog);'); - expect($js)->toContain('apcupsdDashBindSort(dialog);'); + expect($js)->toContain("apcupsdDashBindSort(dialog, 'apcupsddlgsort');"); }); it('keeps no persisted sort state beyond a click-to-sort header like HMIB', function () use ($read) { From 00ad3307cc19eb19d0636c8bb0d56f1661a0f6ef Mon Sep 17 00:00:00 2001 From: TheWitness Date: Tue, 10 Nov 2026 07:39:11 -0500 Subject: [PATCH 3/7] cards: sync bundled cards.js to the converged controller baseline Update js/cards.js to the converged baseline (md5 84876af1) shared by Cacti core (#8684 for 1.2.x, #8683 for develop) and every Card API plugin: the refresh/resize supersede guard, async remove-commit, the duplicate-add guard and expand/collapse keyboard focus. Byte-identical to core. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- js/cards.js | 66 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 5 deletions(-) diff --git a/js/cards.js b/js/cards.js index 0ca94cd..4e5e480 100644 --- a/js/cards.js +++ b/js/cards.js @@ -173,6 +173,22 @@ window.CactiCards = window.CactiCards || (function() { return fresh; } + /* A per-card-id request generation shared by refresh and resize so a slow + * response cannot overwrite the markup of a newer request for the same card + * (for example a refresh that lands after a later grow). The most recently + * started request for an id wins; earlier in-flight responses are discarded. */ + function startRequest(grid, id) { + if (!grid.__ccReq) { + grid.__ccReq = {}; + } + grid.__ccReq[id] = (grid.__ccReq[id] || 0) + 1; + return grid.__ccReq[id]; + } + + function requestSuperseded(grid, id, token) { + return !!grid.__ccReq && grid.__ccReq[id] !== token; + } + function refreshCard(grid, adapter, card) { var id = cardId(card, adapter); // Hosts that inject into an inner body (rather than replacing the whole @@ -188,8 +204,11 @@ window.CactiCards = window.CactiCards || (function() { expanded: card.classList.contains('ccCardExpanded'), height: Number.parseInt(card.getAttribute('data-height') || '1', 10) }; + var token = startRequest(grid, id); Promise.resolve(adapter.fetchCard(id, state)).then(function(html) { - if (html != null) { + // A newer refresh/resize for this card superseded us; discard the + // stale markup instead of reverting the card to an older state. + if (html != null && !requestSuperseded(grid, id, token)) { replaceCard(grid, adapter, card, html); } }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); @@ -197,17 +216,35 @@ window.CactiCards = window.CactiCards || (function() { function removeCard(grid, adapter, card) { var id = cardId(card, adapter); + // Only drop the live card and persist the new layout once the host has + // confirmed the deletion. Re-resolve by id so an overlapping refresh that + // swapped the node does not leave a detached reference behind. + var commit = function() { + var target = grid.contains(card) ? card : findCard(grid, adapter, id); + if (target && target.parentNode) { + target.parentNode.removeChild(target); + saveLayout(grid, adapter); + } + }; if (typeof adapter.onRemoveCard === 'function') { - adapter.onRemoveCard(id, card); + Promise.resolve(adapter.onRemoveCard(id, card)).then(commit).catch(function() { + /* rejected: leave the card and its saved layout untouched */ + }); + } else { + commit(); } - card.parentNode.removeChild(card); - saveLayout(grid, adapter); } function resizeCard(grid, adapter, card, dir) { var id = cardId(card, adapter); if (typeof adapter.onResize === 'function') { + var token = startRequest(grid, id); Promise.resolve(adapter.onResize(id, dir, card)).then(function(html) { + // A newer refresh/resize for this card has superseded us; leave + // its markup and layout in place rather than reverting them. + if (requestSuperseded(grid, id, token)) { + return; + } if (typeof html === 'string') { replaceCard(grid, adapter, card, html); } @@ -218,6 +255,19 @@ window.CactiCards = window.CactiCards || (function() { } } + /* After expand/collapse hides the button that was activated (see cards.css), + * move keyboard focus to the now-visible counterpart so the control is not + * lost when the card is toggled from the keyboard. */ + function refocusToolCounterpart(card, tool, counterpart) { + if (document.activeElement !== tool) { + return; + } + var next = card.querySelector('.ccTool[data-tool="' + counterpart + '"]'); + if (next) { + next.focus(); + } + } + /* Wire a single card: its drag handle (mouse + touch + keyboard) and drag * events. Handle interactions are DELEGATED from the persistent card element * so they survive hosts that replace the header markup on refresh/reload. */ @@ -348,11 +398,13 @@ window.CactiCards = window.CactiCards || (function() { case 'expand': card.classList.add('ccCardExpanded'); card.setAttribute('data-expanded', '1'); + refocusToolCounterpart(card, tool, 'collapse'); saveLayout(grid, adapter); break; case 'collapse': card.classList.remove('ccCardExpanded'); card.setAttribute('data-expanded', '0'); + refocusToolCounterpart(card, tool, 'expand'); saveLayout(grid, adapter); break; case 'grow': resizeCard(grid, adapter, card, 'grow'); break; @@ -384,7 +436,11 @@ window.CactiCards = window.CactiCards || (function() { var tmp = document.createElement('div'); tmp.innerHTML = String(html).trim(); var fresh = tmp.querySelector(cardSel(adapter)) || tmp.firstElementChild; - if (fresh) { + // A second add of the same card can resolve while the first + // is still pending (the option stays selectable until the + // debounced catalogue sync), so skip ids already on the grid + // to avoid appending a duplicate the server then dedupes. + if (fresh && findCard(grid, adapter, cardId(fresh, adapter)) === null) { grid.appendChild(fresh); bindCard(grid, adapter, fresh); if (typeof adapter.applyTheme === 'function') { From 13db42002835ca4b0e86af754cfcefe43d2e059c Mon Sep 17 00:00:00 2001 From: TheWitness Date: Tue, 10 Nov 2026 16:28:47 -0500 Subject: [PATCH 4/7] Address review feedback: WCAG pill contrast and Number.* statics Sync the shared card-widgets.css so the .ccPill severity backgrounds meet WCAG 4.5:1 contrast (mix each hue 70% with black; give --none a translucent currentColor wash). Use Number.parseFloat and Number.isNaN instead of the global parseFloat/isNaN in the dashboard adapter. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- css/card-widgets.css | 8 ++++---- js/apcupsd_dashboard.js | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/css/card-widgets.css b/css/card-widgets.css index 8c6959d..52842f1 100644 --- a/css/card-widgets.css +++ b/css/card-widgets.css @@ -365,7 +365,7 @@ background: color-mix(in srgb, currentColor 12%, transparent); } -.ccPill--up { background: var(--cc-sev-up, #3c9a5f); color: #fff; } -.ccPill--warn { background: var(--cc-sev-warn, #d9830f); color: #fff; } -.ccPill--down { background: var(--cc-sev-down, #cc0000); color: #fff; } -.ccPill--none { background: color-mix(in srgb, currentColor 45%, transparent); color: #fff; } +.ccPill--up { background: color-mix(in srgb, var(--cc-sev-up, #3c9a5f) 70%, #000); color: #fff; } +.ccPill--warn { background: color-mix(in srgb, var(--cc-sev-warn, #d9830f) 70%, #000); color: #fff; } +.ccPill--down { background: color-mix(in srgb, var(--cc-sev-down, #cc0000) 70%, #000); color: #fff; } +.ccPill--none { background: color-mix(in srgb, currentColor 20%, transparent); } diff --git a/js/apcupsd_dashboard.js b/js/apcupsd_dashboard.js index 17e7c5f..a74a95a 100644 --- a/js/apcupsd_dashboard.js +++ b/js/apcupsd_dashboard.js @@ -129,8 +129,8 @@ function apcupsdDashCellValue(cell, numeric) { var raw = cell.hasAttribute('data-sort-value') ? cell.getAttribute('data-sort-value') : cell.textContent; if (numeric) { - var value = parseFloat(raw); - return isNaN(value) ? 0 : value; + var value = Number.parseFloat(raw); + return Number.isNaN(value) ? 0 : value; } return (raw || '').trim().toLowerCase(); From ca228f61d61ca811db2df15511932d6d3af16061 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Tue, 10 Nov 2026 19:39:23 -0500 Subject: [PATCH 5/7] Fix dark-green toolbar labels on dark themes (deepness) The .ccToolbar sits above #apcupsd_dashboard as a sibling, not a child, so it never inherited --cc-text. .ccToolbarLabel/.ccAdd therefore fell back to the shared chrome's light-theme #23362f default and rendered dark green on dark themes. Bind the card palette to .ccToolbar as well so the toolbar follows the theme foreground like the grid and dialog already do. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- css/apcupsd.css | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/css/apcupsd.css b/css/apcupsd.css index 8cb9ad1..51336f1 100644 --- a/css/apcupsd.css +++ b/css/apcupsd.css @@ -24,6 +24,11 @@ * the gauge grid, the UPS/timespan pickers). The shared grid reads its column * count and accent palette from these custom properties. */ +/* The .ccToolbar above the grid is a sibling of #apcupsd_dashboard, not a child, + so bind the shared palette to it here as well; otherwise .ccToolbarLabel/.ccAdd + fall back to the light-theme #23362f default and render dark green on dark + themes such as deepness. */ +.ccToolbar, #apcupsd_dashboard.ccGrid, #apcupsd_dashboard_dialog { --cc-cols: 8; From 11a4d8fd8a0440014d88485ddd3a81292f8cd19a Mon Sep 17 00:00:00 2001 From: TheWitness Date: Tue, 10 Nov 2026 21:22:18 -0500 Subject: [PATCH 6/7] Address review: responsive grid, sort a11y, save errors, Select2, refresh race - Migrate the responsive breakpoints from the retired .apcupsdDashGrid/ .apcupsdDashSpan* classes to #apcupsd_dashboard.ccGrid + .ccW*, clamping wide spans so narrow screens stack instead of creating implicit columns. - Drop role=button from sortable so the native columnheader role and aria-sort announcement are preserved; direction arrows now key off aria-sort instead of the no-longer-set apcupsdDashSortAsc/Desc classes. - Re-enhance sort headers after every swap (via the controller's applyTheme post-swap hook) so refreshed/re-added cards stay keyboard-operable. - Surface a server-rejected layout save in the .apcupsdDashSaveStatus live region instead of silently reverting on reload. - Bridge Select2's jQuery change on the Add card select to a native event (guarding re-entry) so it works on Cacti 1.2.x and core controllers. - Sync cards.js with the shared fix that preserves the live expand/collapse state at swap time (refresh race), byte-identical with core. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- css/apcupsd.css | 43 ++++++++++++---------------------- js/apcupsd_dashboard.js | 51 +++++++++++++++++++++++++++++++++++++++-- js/cards.js | 6 +++++ 3 files changed, 70 insertions(+), 30 deletions(-) diff --git a/css/apcupsd.css b/css/apcupsd.css index 51336f1..75f0919 100644 --- a/css/apcupsd.css +++ b/css/apcupsd.css @@ -85,21 +85,9 @@ font-size: 12px; } -/* The 8-column card grid; each card spans a number of columns via a span class. */ -.apcupsdDashGrid { - display: grid; - grid-template-columns: repeat(8, minmax(0, 1fr)); - align-items: start; - gap: 14px; - margin: 10px 4px; - font-variant-numeric: tabular-nums; -} - -.apcupsdDashSpan2 { grid-column: span 2; } -.apcupsdDashSpan3 { grid-column: span 3; } -.apcupsdDashSpan4 { grid-column: span 4; } -.apcupsdDashSpan6 { grid-column: span 6; } -.apcupsdDashSpan8 { grid-column: span 8; } +/* The card grid and per-card widths come from the shared .ccGrid / .ccW* chrome + (include/css/cards.css); apcupsd only binds --cc-cols and the responsive + overrides at the bottom of this file. */ .apcupsdDashCard { box-sizing: border-box; @@ -574,8 +562,8 @@ font-size: 10px; } -.apcupsdDashTable th.apcupsdDashSortAsc::after { content: '\2191'; opacity: 0.9; } -.apcupsdDashTable th.apcupsdDashSortDesc::after { content: '\2193'; opacity: 0.9; } +.apcupsdDashTable th.apcupsdDashSortable[aria-sort="ascending"]::after { content: '\2191'; opacity: 0.9; } +.apcupsdDashTable th.apcupsdDashSortable[aria-sort="descending"]::after { content: '\2193'; opacity: 0.9; } /* Fleet total row under the UPSes table. */ .apcupsdDashTotalRow > td { @@ -590,30 +578,29 @@ color: color-mix(in srgb, currentColor 65%, transparent); } -/* Narrow the grid before cards get cramped. */ +/* Narrow the grid before cards get cramped; clamp the shared .ccW* spans to the + reduced column count so they stack instead of creating implicit columns. */ @media (max-width: 1200px) { - .apcupsdDashGrid { + #apcupsd_dashboard.ccGrid { grid-template-columns: repeat(4, minmax(0, 1fr)); } - .apcupsdDashSpan4, - .apcupsdDashSpan6, - .apcupsdDashSpan8 { + #apcupsd_dashboard.ccGrid .ccW4, + #apcupsd_dashboard.ccGrid .ccW5, + #apcupsd_dashboard.ccGrid .ccW6, + #apcupsd_dashboard.ccGrid .ccW7, + #apcupsd_dashboard.ccGrid .ccW8 { grid-column: 1 / -1; } } @media (max-width: 760px) { - .apcupsdDashGrid { + #apcupsd_dashboard.ccGrid { grid-template-columns: 1fr; gap: 10px; } - .apcupsdDashSpan2, - .apcupsdDashSpan3, - .apcupsdDashSpan4, - .apcupsdDashSpan6, - .apcupsdDashSpan8 { + #apcupsd_dashboard.ccGrid > .ccCard { grid-column: 1 / -1; } } diff --git a/js/apcupsd_dashboard.js b/js/apcupsd_dashboard.js index a74a95a..e6b9496 100644 --- a/js/apcupsd_dashboard.js +++ b/js/apcupsd_dashboard.js @@ -67,13 +67,30 @@ function apcupsdDashPrepSortHeaders(container) { if (!th.hasAttribute('tabindex')) { th.setAttribute('tabindex', '0'); } - th.setAttribute('role', 'button'); if (!th.hasAttribute('aria-sort')) { th.setAttribute('aria-sort', 'none'); } }); } +/* Show (or clear) a layout-save error in the toolbar's live-region status span so + * a rejected save is not silently lost on the next reload. */ +function apcupsdDashShowSaveStatus(message) { + var el = document.querySelector('.apcupsdDashSaveStatus'); + + if (!el) { + return; + } + + if (message) { + el.textContent = message; + el.removeAttribute('hidden'); + } else { + el.textContent = ''; + el.setAttribute('hidden', 'hidden'); + } +} + /* Sort a card table by the clicked column header, toggling asc/desc. Numeric * columns (data-sort="num") sort by the cell's data-sort-value when present. */ function apcupsdDashSortTable(th) { @@ -234,6 +251,15 @@ function initApcupsdDashboard() { var adapter = { addControl: 'apcupsd_dashboard_add', + // The shared controller calls applyTheme after every swap (refresh, + // resize, add and manual refresh-all). apcupsd has no per-card palette + // to re-apply, but this is the hook that lets it re-enhance the sort + // headers of freshly inserted, server-rendered markup so keyboard + // users keep access to sorting after a refresh or re-add. + applyTheme: function(g) { + apcupsdDashPrepSortHeaders(g); + }, + fetchCard: function(id, state) { return fetchCard(id, state && state.expanded); }, @@ -254,7 +280,11 @@ function initApcupsdDashboard() { $.post(cfg.page, apcupsdDashPost(grid, { action: cfg.layoutAction, layout: JSON.stringify({order: state.order, expanded: expanded}) - }), null, 'json'); + }), null, 'json').done(function(d) { + // Surface a server-side rejection (e.g. the 4096-char layout + // cap) instead of letting the change silently revert on reload. + apcupsdDashShowSaveStatus(d && d.error ? d.error : ''); + }); syncAddOptions(); }, @@ -268,6 +298,23 @@ function initApcupsdDashboard() { syncAddOptions(); apcupsdDashBindSort(grid, 'apcupsdsort'); + // Cacti 1.2.x upgrades the Add card