From 1dbe91d9b995c6962c9dbfdb8316e6d04624ebaa Mon Sep 17 00:00:00 2001 From: TheWitness Date: Mon, 9 Nov 2026 13:44:53 -0500 Subject: [PATCH 01/13] cards: adopt the shared Card API (chrome + chart widgets) for both dashboards Converge the per-device Host Dashboard and the Fleet (Summary) Dashboard on the shared Cacti dashboarding Card API so the chrome and chart primitives are no longer vendored per plugin: - js/cards.js is the byte-identical shared CactiCards controller; the two inlined controllers become thin adapters (js/hmib_dashboard.js, js/hmib_summary_dashboard.js) that map drag/reorder/tools to hmib's endpoints and keep hmib's extras (sortable card tables, device/OS-type pickers, auto-refresh interval, refresh-all). - Card markup uses the shared .cc* chrome contract; card-body charts (gauge, usage/distribution bars, min/avg/max bullet, stacked bar, stat tiles) use the shared .cc* chart-widget primitives (css/card-widgets.css). Card header severity now uses the shared data-severity wash. - On Cacti 1.2.32+ the chrome and widgets come from core; on older cores hmib bundles its own byte-identical cards.js/cards.css/card-widgets.css, gated by file_exists. hmib.css keeps only hmib-specific content styling and binds the shared --cc-* theme variables. No functional change to either dashboard. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + css/card-widgets.css | 349 ++++++++++++++++++++++ css/cards.css | 298 +++++++++++++++++++ css/hmib.css | 18 ++ hmib.php | 211 +++++++------ js/cards.js | 407 +++++++++++++++++++++++++ js/hmib_dashboard.js | 554 +++++++++++++--------------------- js/hmib_summary_dashboard.js | 558 +++++++++++++---------------------- 8 files changed, 1587 insertions(+), 809 deletions(-) create mode 100644 css/card-widgets.css create mode 100644 css/cards.css create mode 100644 js/cards.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c160fc0..f3fd57b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ChangeLog --- develop --- +* dev: Adopt the shared Cacti dashboarding Card API across both dashboards: the per-device Host Dashboard and the Fleet (Summary) Dashboard now drive their card grids through the shared `js/cards.js` (`CactiCards`) controller plus thin `js/hmib_dashboard.js` / `js/hmib_summary_dashboard.js` adapters, the card markup uses the shared `.cc*` chrome contract, and the card-body charts (gauge, usage/distribution bars, min/avg/max bullet, stacked bar, stat tiles) use the shared `.cc*` chart-widget primitives. On Cacti 1.2.32+ the chrome and widgets come from core (`include/js/cards.js`, `include/css/cards.css`, `include/css/card-widgets.css`); on older cores hmib bundles its own byte-identical copies, gated by `file_exists`. Card header severity now uses the shared `data-severity` wash. No functional change to the dashboards * dev: Restore missing characters in the unmatched device-type regression test so PHP syntax checks and the test can run * dev: Run the CI poller with the shared runner group so RRD files and structured directories pass permission verification * issue: Fix the Fleet Dashboard Uptime Distribution still showing all zeros by sourcing it from the Cacti host table's snmp_sysUpTimeInstance directly instead of the frequently-unreported Host Resources hrSystemUptime/sysUpTime columns diff --git a/css/card-widgets.css b/css/card-widgets.css new file mode 100644 index 0000000..b92e702 --- /dev/null +++ b/css/card-widgets.css @@ -0,0 +1,349 @@ +/* + +-------------------------------------------------------------------------+ + | 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); } + +.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; +} + +.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); +} 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/css/hmib.css b/css/hmib.css index 93e2f5a..07764f0 100644 --- a/css/hmib.css +++ b/css/hmib.css @@ -16,6 +16,24 @@ +-------------------------------------------------------------------------+ */ +/* + * Bind the shared card chrome (core include/css/cards.css) and chart-widget + * primitives (include/css/card-widgets.css) - loaded globally on Cacti 1.2.32+, + * bundled by the plugin on older cores - to hmib's theme-agnostic palette. + * Everything derives from currentColor so the dashboard follows every Cacti + * theme; the grids are 8 columns wide. The .cc* chrome/primitive rules below + * (now superseded by the shared stylesheets) are retained only where they also + * style hmib-specific content (tables, status pills, the device picker). + */ +#hmib_dashboard.ccGrid, +#hmib_summary_dashboard.ccGrid { + --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); +} + /* * Base (light-theme) action-glyph colours for the Host MIB views. Each core * theme that needs different (brighter) values ships a same-named override diff --git a/hmib.php b/hmib.php index 263a418..0911f0b 100644 --- a/hmib.php +++ b/hmib.php @@ -109,6 +109,17 @@ general_header(); +// 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. +if (!file_exists($config['base_path'] . '/include/css/cards.css')) { + print get_md5_include_css('plugins/hmib/css/cards.css'); +} + +if (!file_exists($config['base_path'] . '/include/css/card-widgets.css')) { + print get_md5_include_css('plugins/hmib/css/card-widgets.css'); +} + // Load this plugin's per-theme glyph styling: base rules plus the active // theme's override file when one is shipped (see plugins/hmib/css/). print get_md5_include_css('plugins/hmib/css/hmib.css'); @@ -3925,14 +3936,14 @@ function hmib_dashboard_gauge(float $percent, string $center_label, string $sub_ $color = $severity === 'down' ? '#cc0000' : ($severity === 'recovering' ? '#d9830f' : '#3c9a5f'); $dash = number_format($percent, 2, '.', ''); - return '
' - . '' - . '' - . '' + return '
' + . '' + . '' + . '' . '' - . '
' - . '' . html_escape($center_label) . '' - . ($sub_label !== '' ? '' . html_escape($sub_label) . '' : '') + . '
' + . '' . html_escape($center_label) . '' + . ($sub_label !== '' ? '' . html_escape($sub_label) . '' : '') . '
'; } @@ -3947,7 +3958,7 @@ function hmib_dashboard_bar(float $percent): string { $percent = max(0.0, min(100.0, $percent)); $severity = hmib_dashboard_severity($percent); - return '
'; + return '
'; } /** @@ -3990,7 +4001,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { switch ($key) { case 'system': if (!cacti_sizeof($system)) { - print '

' . __esc('No system information has been collected for this device yet.', 'hmib') . '

'; + print '

' . __esc('No system information has been collected for this device yet.', 'hmib') . '

'; break; } @@ -4014,7 +4025,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { break; case 'cpu': if (!cacti_sizeof($system)) { - print '

' . __esc('No processor data available.', 'hmib') . '

'; + print '

' . __esc('No processor data available.', 'hmib') . '

'; break; } @@ -4027,7 +4038,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { break; case 'memory': if (!cacti_sizeof($system)) { - print '

' . __esc('No memory data available.', 'hmib') . '

'; + print '

' . __esc('No memory data available.', 'hmib') . '

'; break; } @@ -4040,7 +4051,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { break; case 'swap': if (!cacti_sizeof($system) || (float) $system['swapSize'] <= 0) { - print '

' . __esc('No swap configured on this device.', 'hmib') . '

'; + print '

' . __esc('No swap configured on this device.', 'hmib') . '

'; break; } @@ -4053,12 +4064,12 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { break; case 'logins': if (!cacti_sizeof($system)) { - print '

' . __esc('No session data available.', 'hmib') . '

'; + print '

' . __esc('No session data available.', 'hmib') . '

'; break; } - print '
' . ($up ? number_format_i18n((int) $system['users'], 0) : __('N/A', 'hmib')) . '' . __esc('Logged-in Users', 'hmib') . '
'; + print '
' . ($up ? number_format_i18n((int) $system['users'], 0) : __('N/A', 'hmib')) . '' . __esc('Logged-in Users', 'hmib') . '
'; print ''; $kv(__('Running Processes', 'hmib'), $up ? number_format_i18n((int) $system['processes'], 0) : __('N/A', 'hmib')); $kv(__('Maximum Processes', 'hmib'), (int) $system['maxProcesses'] > 0 ? number_format_i18n((int) $system['maxProcesses'], 0) : __('Unlimited', 'hmib')); @@ -4088,7 +4099,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { . ''; } } else { - print ''; + print ''; } print '
' . __esc('No per-processor load reported.', 'hmib') . '
' . __esc('No per-processor load reported.', 'hmib') . '
'; @@ -4128,7 +4139,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { . ''; } } else { - print '' . __esc('No storage volumes detected.', 'hmib') . ''; + print '' . __esc('No storage volumes detected.', 'hmib') . ''; } print ''; @@ -4162,7 +4173,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { . ''; } } else { - print '' . __esc('No running processes recorded.', 'hmib') . ''; + print '' . __esc('No running processes recorded.', 'hmib') . ''; } print ''; @@ -4188,12 +4199,12 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { print '' . '' . html_escape($device['description']) . '' - . '' . html_escape($label) . '' + . '' . html_escape($label) . '' . '' . number_format_i18n((int) $device['errors'], 0) . '' . ''; } } else { - print '' . __esc('No hardware devices detected.', 'hmib') . ''; + print '' . __esc('No hardware devices detected.', 'hmib') . ''; } print ''; @@ -4208,7 +4219,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { $count = cacti_sizeof($software); - print '
' . number_format_i18n($count, 0) . '' . __esc('Installed Packages', 'hmib') . '
'; + print '
' . number_format_i18n($count, 0) . '' . __esc('Installed Packages', 'hmib') . '
'; print '' . '' . '' @@ -4222,7 +4233,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { . ''; } } else { - print ''; + print ''; } print '
' . __esc('Name', 'hmib') . '' . __esc('Installed', 'hmib') . '
' . __esc('No installed software inventory collected.', 'hmib') . '
' . __esc('No installed software inventory collected.', 'hmib') . '
'; @@ -4250,7 +4261,7 @@ function hmib_dashboard_card_body(string $key, int $host_id): string { . ''; } } else { - print '' . __esc('No process use history recorded.', 'hmib') . ''; + print '' . __esc('No process use history recorded.', 'hmib') . ''; } print ''; @@ -4283,34 +4294,36 @@ function hmib_dashboard_render_card(string $key, int $host_id, bool $expanded = $tools = ''; if ($def['expandable']) { - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; } - $tools .= ''; - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; + $tools .= ''; - $classes = 'hmibDashCard hmibDashSpan' . (int) $def['span']; + $classes = 'ccCard ccW' . (int) $def['span']; if ($def['expandable']) { - $classes .= ' hmibDashCardExpandable'; + $classes .= ' ccCardExpandable'; } if ($expanded) { - $classes .= ' hmibDashCardExpanded'; + $classes .= ' ccCardExpanded'; } $state = hmib_dashboard_card_state($key, $host_id); - $header_class = 'hmibDashCardHeader' . ($state !== '' ? ' hmibDashCardHeader--' . $state : ''); - - return '
' - . '
' - . '' - . '

' . html_escape($def['title']) . '

' - . '' . $tools . '' + $severity = ($state === 'recovering') ? 'warn' : (($state === 'up' || $state === 'down') ? $state : 'none'); + + return '
' + . '
' + . '' + . '

' . html_escape($def['title']) . '

' + . '' . $tools . '' . '
' - . '
' . hmib_dashboard_card_body($key, $host_id) . '
' + . '
' . hmib_dashboard_card_body($key, $host_id) . '
' . '
'; } @@ -4491,6 +4504,9 @@ function hmib_dashboard(): void { ]); } + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } print ''; $system = hmib_dashboard_system($host_id); @@ -4538,10 +4554,10 @@ function hmib_dashboard(): void { form_end(); - print '
'; + print '
'; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -4549,9 +4565,9 @@ function hmib_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -4563,11 +4579,11 @@ function hmib_dashboard(): void { } print ''; - print ''; + print ''; print '
'; print '
'; - print '
'; + print '
'; foreach ($layout['order'] as $key) { print hmib_dashboard_render_card($key, $host_id, !empty($layout['expanded'][$key])); @@ -4785,10 +4801,10 @@ function hmib_summary_bullet(string $label, ?float $min, ?float $avg, ?float $ma } }; - $head = '
' . html_escape($label) . '' . html_escape($fmt($avg)) . '
'; + $head = '
' . html_escape($label) . '' . html_escape($fmt($avg)) . '
'; if ($avg === null || $scale <= 0) { - return '
' . $head . '
'; + return '
' . $head . '
'; } $lo = max(0.0, min($scale, (float) ($min ?? $avg))); @@ -4801,12 +4817,12 @@ function hmib_summary_bullet(string $label, ?float $min, ?float $avg, ?float $ma $sev = in_array($severity, ['up', 'recovering', 'down'], true) ? $severity : 'none'; - return '
' . $head - . '
' - . '
' - . '
' + return '
' . $head + . '
' + . '
' + . '
' . '
' - . '
' . html_escape($fmt($min)) . '' . html_escape($fmt($max)) . '
' + . '
' . html_escape($fmt($min)) . '' . html_escape($fmt($max)) . '
' . '
'; } @@ -4861,7 +4877,7 @@ function hmib_summary_card_body(string $key, int $ostype): string { ob_start(); if (!cacti_sizeof($stats) || (int) $stats['devices'] === 0) { - print '

' . __esc('No Host MIB devices in this scope yet.', 'hmib') . '

'; + print '

' . __esc('No Host MIB devices in this scope yet.', 'hmib') . '

'; return (string) ob_get_clean(); } @@ -4880,10 +4896,10 @@ function hmib_summary_card_body(string $key, int $ostype): string { ['', hmib_memory((float) $stats['memTotal']), __('Total RAM', 'hmib')] ]; - print '
'; + print '
'; foreach ($tiles as $tile) { - $mod = $tile[0] !== '' ? ' hmibFleetTile--' . $tile[0] : ''; - print '
' . html_escape($tile[1]) . '' . html_escape($tile[2]) . '
'; + $mod = $tile[0] !== '' ? ' ccTile--' . $tile[0] : ''; + print '
' . html_escape($tile[1]) . '' . html_escape($tile[2]) . '
'; } print '
'; @@ -4913,17 +4929,17 @@ function hmib_summary_card_body(string $key, int $ostype): string { ['dis', (int) $stats['disabled'], __('Disabled', 'hmib')] ]; - print '
'; + print '
'; foreach ($segs as $seg) { if ($seg[1] > 0) { - print '
'; + print '
'; } } print '
'; - print '
'; + print '
'; foreach ($segs as $seg) { - print '' . html_escape($seg[2]) . ' ' . number_format_i18n($seg[1], 0) . ''; + print '' . html_escape($seg[2]) . ' ' . number_format_i18n($seg[1], 0) . ''; } print '
'; @@ -4932,7 +4948,7 @@ function hmib_summary_card_body(string $key, int $ostype): string { $storage = hmib_summary_storage_stats($ostype); if (!cacti_sizeof($storage) || (int) $storage['volumes'] === 0) { - print '

' . __esc('No storage volumes detected in this scope.', 'hmib') . '

'; + print '

' . __esc('No storage volumes detected in this scope.', 'hmib') . '

'; break; } @@ -4971,7 +4987,7 @@ function hmib_summary_card_body(string $key, int $ostype): string { ORDER BY devices DESC", $type_params); if (!cacti_sizeof($types)) { - print '

' . __esc('No OS types recorded.', 'hmib') . '

'; + print '

' . __esc('No OS types recorded.', 'hmib') . '

'; break; } @@ -4983,10 +4999,10 @@ function hmib_summary_card_body(string $key, int $ostype): string { foreach ($types as $type) { $width = (int) $type['devices'] / $peak * 100; - print '
' - . '' . html_escape($type['name']) . '' - . '' - . '' . number_format_i18n((int) $type['devices'], 0) . '' + print '
' + . '' . html_escape($type['name']) . '' + . '' + . '' . number_format_i18n((int) $type['devices'], 0) . '' . '
'; } @@ -5038,11 +5054,11 @@ function hmib_summary_card_body(string $key, int $ostype): string { . '' . html_escape($process['name']) . '' . '' . number_format_i18n((int) $process['hosts'], 0) . '' . '' . html_escape($display) . '' - . '' + . '' . ''; } } else { - print '' . __esc('No process statistics recorded.', 'hmib') . ''; + print '' . __esc('No process statistics recorded.', 'hmib') . ''; } print ''; @@ -5074,34 +5090,36 @@ function hmib_summary_render_card(string $key, int $ostype, bool $expanded = fal $tools = ''; if ($def['expandable']) { - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; } - $tools .= ''; - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; + $tools .= ''; - $classes = 'hmibDashCard hmibDashSpan' . (int) $def['span']; + $classes = 'ccCard ccW' . (int) $def['span']; if ($def['expandable']) { - $classes .= ' hmibDashCardExpandable'; + $classes .= ' ccCardExpandable'; } if ($expanded) { - $classes .= ' hmibDashCardExpanded'; + $classes .= ' ccCardExpanded'; } $state = hmib_summary_card_state($key, $ostype); - $header_class = 'hmibDashCardHeader' . ($state !== '' ? ' hmibDashCardHeader--' . $state : ''); - - return '
' - . '
' - . '' - . '

' . html_escape($def['title']) . '

' - . '' . $tools . '' + $severity = ($state === 'recovering') ? 'warn' : (($state === 'up' || $state === 'down') ? $state : 'none'); + + return '
' + . '
' + . '' + . '

' . html_escape($def['title']) . '

' + . '' . $tools . '' . '
' - . '
' . hmib_summary_card_body($key, $ostype) . '
' + . '
' . hmib_summary_card_body($key, $ostype) . '
' . '
'; } @@ -5262,6 +5280,9 @@ function hmib_summary_dashboard(): void { ]); } + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } print ''; $layout = hmib_summary_layout($ostype); @@ -5272,9 +5293,9 @@ function hmib_summary_dashboard(): void { $page_refresh_interval = [0 => __('No Refresh', 'hmib'), 30 => __('30 Seconds', 'hmib'), 60 => __('1 Minute', 'hmib'), 300 => __('5 Minutes', 'hmib')]; } - print '
'; - print ''; - print ''; print ''; if (db_fetch_cell('SELECT COUNT(*) FROM plugin_hmib_hrSystem WHERE host_type = 0') > 0) { @@ -5295,8 +5316,8 @@ function hmib_summary_dashboard(): void { print ''; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -5304,9 +5325,9 @@ function hmib_summary_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -5318,11 +5339,11 @@ function hmib_summary_dashboard(): void { } print ''; - print ''; + print ''; print '
'; print '
'; - print '
'; + print '
'; foreach ($layout['order'] as $key) { print hmib_summary_render_card($key, $ostype, !empty($layout['expanded'][$key])); 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/js/hmib_dashboard.js b/js/hmib_dashboard.js index cc931bd..a8536a0 100644 --- a/js/hmib_dashboard.js +++ b/js/hmib_dashboard.js @@ -16,17 +16,20 @@ +-------------------------------------------------------------------------+ */ -/* Host Dashboard: the per-device drilldown card grid. Mirrors the Syslog Status - * tab's card interaction model (drag/keyboard reorder, per-card tools, an "Add - * card" catalogue, auto-refresh interval + manual refresh) with the card order, - * expanded state and current host persisted server-side in settings_user. */ +/* + * Host Dashboard adapter for the shared card chrome (js/cards.js). The + * CactiCards controller owns drag/keyboard reorder and the per-card tools; this + * adapter maps those to hmib's server endpoints (hmib.php) and wires hmib's + * dashboard extras - sortable card tables, the device picker, the auto-refresh + * interval and manual refresh-all. The card markup uses the shared .cc* + * contract and the card bodies the shared .cc* chart primitives. + */ -var hmibDashDragging = null; +var hmibDashAdapter = null; /* Named navigation callback for the device picker. The select2 drop_callback - * invokes this by name (via the field's on_change/data-callback) on selection - * instead of emitting a change event, so it reads the picker value itself and - * opens that device's dashboard. Must stay global for executeFunctionByName(). */ + * invokes this by name on selection (it does not emit a change event on older + * Cacti), so it must stay global for executeFunctionByName(). */ function hmibDashboardNavigate() { var host = document.getElementById('hmib_dashboard_host'); @@ -35,277 +38,124 @@ function hmibDashboardNavigate() { } } -function initHmibDashboard() { - $(function() { - var grid = document.getElementById('hmib_dashboard'); - if (!grid) { - return; - } - - grid.querySelectorAll('.hmibDashCard').forEach(function(card) { - hmibDashBindCard(grid, card); - }); - - grid.addEventListener('dragover', function(event) { - if (!hmibDashDragging) { - return; - } - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - var before = hmibDashDragReference(grid, event.clientX, event.clientY); - if (before == null) { - grid.appendChild(hmibDashDragging); - } else if (before !== hmibDashDragging) { - grid.insertBefore(hmibDashDragging, before); - } - }); - - // Per-card tool buttons bubble to the grid. - $(grid).off('click.hmibdash').on('click.hmibdash', '.hmibDashCardTool', function() { - var card = this.closest('.hmibDashCard'); - if (!card) { - return; - } - switch (this.dataset.tool) { - case 'expand': card.classList.add('hmibDashCardExpanded'); hmibDashSaveLayout(grid); break; - case 'collapse': card.classList.remove('hmibDashCardExpanded'); hmibDashSaveLayout(grid); break; - case 'maximize': hmibDashMaximize(card); break; - case 'refresh': hmibDashRefreshCard(grid, card); break; - case 'remove': hmibDashRemoveCard(grid, card); break; - } - }); - - // Client-side column sorting for card tables (mouse and keyboard). - $(grid).off('click.hmibdashsort').on('click.hmibdashsort', 'th.hmibDashSortable', function() { - hmibDashSortTable(this); - }); - $(grid).off('keydown.hmibdashsort').on('keydown.hmibdashsort', 'th.hmibDashSortable', function(event) { - if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { - event.preventDefault(); - hmibDashSortTable(this); - } - }); - - var add = document.getElementById('hmib_dashboard_add'); - if (add) { - $(add).off('change.hmibdash').on('change.hmibdash', function() { - var key = this.value; - this.value = ''; - if (key) { - hmibDashAddCard(grid, key); - } - }); - } - - var host = document.getElementById('hmib_dashboard_host'); - if (host) { - // Native change covers the plain- fallback emits change; the select2 + // AJAX control instead invokes hmibDashboardNavigate() by name. + var host = document.getElementById('hmib_dashboard_host'); + if (host) { + $(host).off('change.hmibdash').on('change.hmibdash', function() { + hmibDashboardNavigate(); + }); } - order.push(card.dataset.card); - if (card.classList.contains('hmibDashCardExpanded')) { - expanded[card.dataset.card] = true; + + // Auto-refresh interval: persist through a CSRF-protected POST, then + // reload so Cacti's page refresh applies. + var interval = document.getElementById('hmib_dashboard_refresh'); + if (interval) { + $(interval).off('change.hmibdash').on('change.hmibdash', function() { + $.post('hmib.php', {action: 'dashboard_refresh', refresh: this.value, __csrf_magic: csrfMagicToken}, null, 'json').always(function() { + window.location = 'hmib.php?action=dashboard'; + }); + }); } - }); - $.post('hmib.php', { - action: 'dashboard_layout', - layout: JSON.stringify({order: order, expanded: expanded}), - __csrf_magic: csrfMagicToken - }, null, 'json').always(function() { - hmibDashSaveInFlight = false; - if (hmibDashSaveQueued) { - hmibDashSaveQueued = false; - hmibDashSaveLayout(grid); + var refreshNow = document.getElementById('hmib_dashboard_refresh_now'); + if (refreshNow) { + $(refreshNow).off('click.hmibdash').on('click.hmibdash', function() { + hmibDashRefreshAll(grid, this); + }); } }); } diff --git a/js/hmib_summary_dashboard.js b/js/hmib_summary_dashboard.js index 0fdd262..c3f391c 100644 --- a/js/hmib_summary_dashboard.js +++ b/js/hmib_summary_dashboard.js @@ -6,295 +6,144 @@ | modify it under the terms of the GNU General Public License | | as published by the Free Software Foundation; either version 2 | | of the License, or (at your option) any later version. | + | | + | This program is distributed in the hope that it will be useful, | + | but WITHOUT ANY WARRANTY; without even the implied warranty of | + | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | + | GNU General Public License for more details. | +-------------------------------------------------------------------------+ | Cacti: The Complete RRDtool-based Graphing Solution | +-------------------------------------------------------------------------+ */ -/* Fleet Dashboard: the Summary-tab aggregate card grid. Mirrors the per-device - * dashboard's card interaction model (drag/keyboard reorder, add/remove, - * refresh, maximize, sortable tables, layout persistence) but is scoped by OS - * type (ostype, 0 = all types) rather than a single device, and reuses the - * shared .hmibDash* card chrome. */ - -var hmibSumDragging = null; - -function initHmibSummaryDashboard() { - $(function() { - var grid = document.getElementById('hmib_summary_dashboard'); - if (!grid) { - return; - } - - grid.querySelectorAll('.hmibDashCard').forEach(function(card) { - hmibSumBindCard(grid, card); - }); - - grid.addEventListener('dragover', function(event) { - if (!hmibSumDragging) { - return; - } - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - var before = hmibSumDragReference(grid, event.clientX, event.clientY); - if (before == null) { - grid.appendChild(hmibSumDragging); - } else if (before !== hmibSumDragging) { - grid.insertBefore(hmibSumDragging, before); - } - }); - - $(grid).off('click.hmibsum').on('click.hmibsum', '.hmibDashCardTool', function() { - var card = this.closest('.hmibDashCard'); - if (!card) { - return; - } - switch (this.dataset.tool) { - case 'expand': card.classList.add('hmibDashCardExpanded'); hmibSumSaveLayout(grid); break; - case 'collapse': card.classList.remove('hmibDashCardExpanded'); hmibSumSaveLayout(grid); break; - case 'maximize': hmibSumMaximize(card); break; - case 'refresh': hmibSumRefreshCard(grid, card); break; - case 'remove': hmibSumRemoveCard(grid, card); break; - } - }); - - $(grid).off('click.hmibsumsort').on('click.hmibsumsort', 'th.hmibDashSortable', function() { - hmibSumSortTable(this); - }); - $(grid).off('keydown.hmibsumsort').on('keydown.hmibsumsort', 'th.hmibDashSortable', function(event) { - if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { - event.preventDefault(); - hmibSumSortTable(this); - } - }); +/* + * Fleet (Summary) Dashboard adapter for the shared card chrome (js/cards.js). + * Same model as the per-device Host Dashboard but scoped by OS type (ostype) + * rather than a single device. The CactiCards controller owns drag/reorder and + * the per-card tools; this adapter maps them to hmib's summary endpoints and + * wires the fleet extras (sortable tables, the OS-type picker, the auto-refresh + * interval and manual refresh-all). Card markup uses the shared .cc* contract. + */ - var add = document.getElementById('hmib_summary_add'); - if (add) { - $(add).off('change.hmibsum').on('change.hmibsum', function() { - var key = this.value; - this.value = ''; - if (key) { - hmibSumAddCard(grid, key); - } - }); - } +var hmibSumAdapter = null; - var type = document.getElementById('hmib_summary_type'); - if (type) { - $(type).off('change.hmibsum').on('change.hmibsum', function() { - window.location = 'hmib.php?action=summary_dashboard&ostype=' + encodeURIComponent(this.value); - }); - } +/* Make a container's sortable headers focusable and screen-reader friendly. */ +function hmibSumPrepSortHeaders(container) { + if (!container) { + return; + } - var interval = document.getElementById('hmib_summary_refresh'); - if (interval) { - $(interval).off('change.hmibsum').on('change.hmibsum', function() { - $.post('hmib.php', {action: 'summary_refresh', refresh: this.value, __csrf_magic: csrfMagicToken}, null, 'json').always(function() { - window.location = 'hmib.php?action=summary_dashboard'; - }); - }); + container.querySelectorAll('th.hmibDashSortable').forEach(function(th) { + if (!th.hasAttribute('tabindex')) { + th.setAttribute('tabindex', '0'); } - - var refreshNow = document.getElementById('hmib_summary_refresh_now'); - if (refreshNow) { - $(refreshNow).off('click.hmibsum').on('click.hmibsum', function() { - hmibSumRefreshAll(grid, this); - }); + th.setAttribute('role', 'button'); + if (!th.hasAttribute('aria-sort')) { + th.setAttribute('aria-sort', 'none'); } }); } -/** Wire a single card's drag handle (mouse + keyboard) and drag events. */ -function hmibSumBindCard(grid, card) { - hmibSumPrepSortHeaders(card); +/* 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 hmibSumSortTable(th) { + var table = th.closest('table'); + if (!table) { + return; + } - var handle = card.querySelector('.hmibDashCardDrag'); - if (!handle) { + var tbody = table.tBodies[0]; + if (!tbody) { return; } - 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}); - - 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(); - hmibSumSaveLayout(grid); - }); + 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('hmibDashSortAsc'); - card.addEventListener('dragstart', function(event) { - hmibSumDragging = card; - card.classList.add('hmibDashCardDragging'); - event.dataTransfer.effectAllowed = 'move'; - try { event.dataTransfer.setData('text/plain', card.dataset.card || ''); } catch (error) { /* IE guard */ } + headers.forEach(function(header) { + header.classList.remove('hmibDashSortAsc', 'hmibDashSortDesc'); + if (header.classList.contains('hmibDashSortable')) { + header.setAttribute('aria-sort', 'none'); + } }); + th.classList.add(asc ? 'hmibDashSortAsc' : 'hmibDashSortDesc'); + th.setAttribute('aria-sort', asc ? 'ascending' : 'descending'); - card.addEventListener('dragend', function() { - card.draggable = false; - card.classList.remove('hmibDashCardDragging'); - if (hmibSumDragging) { - hmibSumDragging = null; - hmibSumSaveLayout(grid); - } + var rows = Array.prototype.slice.call(tbody.rows).filter(function(row) { + return !row.classList.contains('hmibDashEmptyRow'); }); -} -/** The card the dragged card should be inserted before for the current pointer - * position, or null to append at the end. */ -function hmibSumDragReference(grid, x, y) { - var cards = Array.prototype.slice.call(grid.querySelectorAll('.hmibDashCard:not(.hmibDashCardDragging)')); - for (var i = 0; i < cards.length; i++) { - var rect = cards[i].getBoundingClientRect(); - if (y < rect.top - 1) { - return cards[i]; + var value = function(row) { + var cell = row.cells[index]; + if (!cell) { + return numeric ? 0 : ''; } - if (y <= rect.bottom && x < rect.left + rect.width / 2) { - return cards[i]; + 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; } - } - return null; -} + return cell.textContent.trim().toLowerCase(); + }; -/** Add a card from the catalogue: fetch its HTML, append it, persist and refresh - * the "Add" options. */ -function hmibSumAddCard(grid, key) { - if (hmibSumHasCard(grid, key)) { - return; - } - $.post('hmib.php', {action: 'summary_card', card: key, ostype: grid.dataset.ostype, __csrf_magic: csrfMagicToken}, null, 'json').done(function(data) { - if (!data || !data.html || hmibSumHasCard(grid, key)) { - return; - } - var card = hmibSumParseCard(data.html); - if (!card) { - return; - } - grid.appendChild(card); - hmibSumBindCard(grid, card); - hmibSumSaveLayout(grid); - hmibSumSyncAddOptions(grid); + 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; }); -} -/** Whether a card with the given key is currently on the grid. */ -function hmibSumHasCard(grid, key) { - var present = false; - grid.querySelectorAll('.hmibDashCard').forEach(function(card) { - if (card.dataset.card === key) { - present = true; - } + rows.forEach(function(row) { + tbody.appendChild(row); }); - return present; } -/** Remove a card from the page and return it to the "Add" catalogue. */ -function hmibSumRemoveCard(grid, card) { - card.parentNode.removeChild(card); - hmibSumSaveLayout(grid); - hmibSumSyncAddOptions(grid); -} +/* Rebuild the "Add" dropdown so it lists only cards not currently on the page. */ +function hmibSumSyncAddOptions(grid) { + var add = document.getElementById('hmib_summary_add'); -/** Re-fetch a single card's HTML and swap it in place, keeping expanded state. */ -function hmibSumRefreshCard(grid, card, done) { - var icon = card.querySelector('.hmibDashCardTool[data-tool="refresh"] .fa, .hmibDashCardTool[data-tool="refresh"] .fas'); - if (icon) { - icon.classList.add('fa-spin'); + if (!add || typeof hmibSummaryCatalog === 'undefined') { + return; } - var settle = function() { - if (icon) { - icon.classList.remove('fa-spin'); - } - if (done) { - done(); - } - }; - var expanded = card.classList.contains('hmibDashCardExpanded') ? '1' : '0'; - $.post('hmib.php', {action: 'summary_card', card: card.dataset.card, ostype: grid.dataset.ostype, expanded: expanded, __csrf_magic: csrfMagicToken}, null, 'json').done(function(data) { - if (!data || !data.html || !card.parentNode) { - settle(); - return; - } - var fresh = hmibSumParseCard(data.html); - if (!fresh) { - settle(); - return; - } - // Use the card's CURRENT expanded state (the user may have toggled it while - // the request was in flight) rather than the snapshot sent with the request. - if (card.classList.contains('hmibDashCardExpanded')) { - fresh.classList.add('hmibDashCardExpanded'); - } else { - fresh.classList.remove('hmibDashCardExpanded'); - } - // Preserve keyboard focus: if a tool button in THIS card was focused, move - // focus to the same tool on the replacement. (Refresh-all focuses a toolbar - // button outside the card, so it is not captured here.) - var active = document.activeElement; - var focusedTool = (active && card.contains(active) && active.classList && active.classList.contains('hmibDashCardTool')) ? active.dataset.tool : null; - card.parentNode.replaceChild(fresh, card); - if (focusedTool) { - var toolEl = fresh.querySelector('.hmibDashCardTool[data-tool="' + focusedTool + '"]'); - if (toolEl) { - toolEl.focus(); - } - } - hmibSumBindCard(grid, fresh); - if (done) { - done(); + + var present = {}; + + grid.querySelectorAll('.ccCard').forEach(function(card) { + if (card.dataset.card) { + present[card.dataset.card] = true; } - }).fail(settle); -} + }); -/** Refresh every card on the page, spinning the toolbar glyph until all land. */ -function hmibSumRefreshAll(grid, button) { - var icon = button ? button.querySelector('.fa, .fas') : null; - var cards = Array.prototype.slice.call(grid.querySelectorAll('.hmibDashCard')); - var pending = cards.length; - if (!pending) { - return; - } - if (icon) { - icon.classList.add('fa-spin'); + while (add.options.length > 1) { + add.remove(1); } - cards.forEach(function(card) { - hmibSumRefreshCard(grid, card, function() { - pending--; - if (pending <= 0 && icon) { - icon.classList.remove('fa-spin'); - } - }); + + Object.keys(hmibSummaryCatalog).forEach(function(key) { + if (!present[key]) { + var option = document.createElement('option'); + option.value = key; + option.textContent = hmibSummaryCatalog[key]; + add.appendChild(option); + } }); } -/** Open a copy of a card's body in a large modal dialog. */ +/* Open a copy of a card's body in a large modal dialog, re-wiring the clone's + * sortable table headers (they live outside the grid). */ function hmibSumMaximize(card) { var dialog = document.getElementById('hmib_summary_dialog'); + if (!dialog) { return; } - var title = card.querySelector('.hmibDashCardTitle'); - var body = card.querySelector('.hmibDashCardBody'); - dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; + + var title = card.querySelector('.ccTitle'); + var body = card.querySelector('.ccCardBody'); + + dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; hmibSumPrepSortHeaders(dialog); $(dialog).off('click.hmibsumsort').on('click.hmibsumsort', 'th.hmibDashSortable', function() { @@ -315,142 +164,135 @@ function hmibSumMaximize(card) { }); } -/** Make a container's sortable headers focusable and screen-reader friendly. */ -function hmibSumPrepSortHeaders(container) { - if (!container) { - return; - } - container.querySelectorAll('th.hmibDashSortable').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. - if (!th.hasAttribute('aria-sort')) { - th.setAttribute('aria-sort', 'none'); - } +/* Fetch a single card's HTML from the server (used by refresh/add). */ +function hmibSumFetch(grid, id, expanded) { + return $.post('hmib.php', { + action: 'summary_card', + card: id, + ostype: grid.dataset.ostype, + expanded: expanded ? '1' : '0', + __csrf_magic: csrfMagicToken + }, null, 'json').then(function(data) { + return data && data.html ? data.html : null; }); } -/** Parse a card HTML string into its
element. */ -function hmibSumParseCard(html) { - var tmp = document.createElement('div'); - tmp.innerHTML = html; - return tmp.querySelector('.hmibDashCard'); -} +/* Persist order + expanded state and resync the "Add" catalogue. */ +function hmibSumPostLayout(grid, state) { + var expanded = {}; -/** Rebuild the "Add" dropdown so it lists only cards not currently on the page. */ -function hmibSumSyncAddOptions(grid) { - var add = document.getElementById('hmib_summary_add'); - if (!add || typeof hmibSummaryCatalog === 'undefined') { - return; - } - var present = {}; - grid.querySelectorAll('.hmibDashCard').forEach(function(card) { - if (card.dataset.card) { - present[card.dataset.card] = true; - } - }); - while (add.options.length > 1) { - add.remove(1); - } - Object.keys(hmibSummaryCatalog).forEach(function(key) { - if (!present[key]) { - var option = document.createElement('option'); - option.value = key; - option.textContent = hmibSummaryCatalog[key]; - add.appendChild(option); + state.order.forEach(function(id) { + if (state.cards[id] && state.cards[id].expanded) { + expanded[id] = true; } }); + + $.post('hmib.php', { + action: 'summary_layout', + layout: JSON.stringify({order: state.order, expanded: expanded}), + __csrf_magic: csrfMagicToken + }, null, 'json'); + + hmibSumSyncAddOptions(grid); } -/** 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 hmibSumSortTable(th) { - var table = th.closest('table'); - if (!table) { +/* Refresh every card on the page, spinning the toolbar glyph until all land. */ +function hmibSumRefreshAll(grid, button) { + var icon = button ? button.querySelector('.fa, .fas') : null; + var cards = Array.prototype.slice.call(grid.querySelectorAll('.ccCard')); + var pending = cards.length; + + if (!pending) { return; } - var tbody = table.tBodies[0]; - if (!tbody) { - return; + + if (icon) { + icon.classList.add('fa-spin'); } - 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('hmibDashSortAsc'); - headers.forEach(function(header) { - header.classList.remove('hmibDashSortAsc', 'hmibDashSortDesc'); - if (header.classList.contains('hmibDashSortable')) { - header.setAttribute('aria-sort', 'none'); - } - }); - th.classList.add(asc ? 'hmibDashSortAsc' : 'hmibDashSortDesc'); - th.setAttribute('aria-sort', asc ? 'ascending' : 'descending'); + cards.forEach(function(card) { + var expanded = card.classList.contains('ccCardExpanded'); - var rows = Array.prototype.slice.call(tbody.rows).filter(function(row) { - return !row.classList.contains('hmibDashEmptyRow'); + hmibSumFetch(grid, card.dataset.card, expanded).then(function(html) { + if (html && card.parentNode && window.CactiCards) { + CactiCards.replaceCard(grid, hmibSumAdapter, card, html); + } + }).always(function() { + pending--; + if (pending <= 0 && icon) { + icon.classList.remove('fa-spin'); + } + }); }); +} - var value = function(row) { - var cell = row.cells[index]; - if (!cell) { - return numeric ? 0 : ''; - } - 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; +/* Wire the Fleet (Summary) Dashboard grid to the shared card chrome plus the + * fleet extras. */ +function initHmibSummaryDashboard() { + $(function() { + var grid = document.getElementById('hmib_summary_dashboard'); + + if (!grid || !window.CactiCards) { + return; } - 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; - }); + hmibSumAdapter = { + addControl: 'hmib_summary_add', - rows.forEach(function(row) { - tbody.appendChild(row); - }); -} + fetchCard: function(id, state) { + return hmibSumFetch(grid, id, state && state.expanded); + }, -/** Serialize layout POSTs so rapid actions can't persist out of order. */ -var hmibSumSaveInFlight = false; -var hmibSumSaveQueued = false; + onAddCard: function(id) { + return hmibSumFetch(grid, id, false); + }, -function hmibSumSaveLayout(grid) { - if (hmibSumSaveInFlight) { - hmibSumSaveQueued = true; - return; - } - hmibSumSaveInFlight = true; + onLayoutChange: function(state) { + hmibSumPostLayout(grid, state); + }, - var order = []; - var expanded = {}; - grid.querySelectorAll('.hmibDashCard').forEach(function(card) { - if (!card.dataset.card) { - return; + maximize: function(id, mode, card) { + hmibSumMaximize(card); + } + }; + + CactiCards.init(grid, hmibSumAdapter); + hmibSumSyncAddOptions(grid); + + // Client-side column sorting for card tables (mouse and keyboard). + $(grid).off('click.hmibsumsort').on('click.hmibsumsort', 'th.hmibDashSortable', function() { + hmibSumSortTable(this); + }); + $(grid).off('keydown.hmibsumsort').on('keydown.hmibsumsort', 'th.hmibDashSortable', function(event) { + if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { + event.preventDefault(); + hmibSumSortTable(this); + } + }); + + // OS-type picker: reload the fleet dashboard scoped to the chosen type. + var type = document.getElementById('hmib_summary_type'); + if (type) { + $(type).off('change.hmibsum').on('change.hmibsum', function() { + window.location = 'hmib.php?action=summary_dashboard&ostype=' + encodeURIComponent(this.value); + }); } - order.push(card.dataset.card); - if (card.classList.contains('hmibDashCardExpanded')) { - expanded[card.dataset.card] = true; + + // Auto-refresh interval: persist through a CSRF-protected POST, then reload. + var interval = document.getElementById('hmib_summary_refresh'); + if (interval) { + $(interval).off('change.hmibsum').on('change.hmibsum', function() { + $.post('hmib.php', {action: 'summary_refresh', refresh: this.value, __csrf_magic: csrfMagicToken}, null, 'json').always(function() { + window.location = 'hmib.php?action=summary_dashboard'; + }); + }); } - }); - $.post('hmib.php', { - action: 'summary_layout', - layout: JSON.stringify({order: order, expanded: expanded}), - __csrf_magic: csrfMagicToken - }, null, 'json').always(function() { - hmibSumSaveInFlight = false; - if (hmibSumSaveQueued) { - hmibSumSaveQueued = false; - hmibSumSaveLayout(grid); + var refreshNow = document.getElementById('hmib_summary_refresh_now'); + if (refreshNow) { + $(refreshNow).off('click.hmibsum').on('click.hmibsum', function() { + hmibSumRefreshAll(grid, this); + }); } }); } From 7bc0cb96683f98db6f325857380d16a4ec7368b1 Mon Sep 17 00:00:00 2001 From: TheWitness Date: Mon, 9 Nov 2026 13:51:39 -0500 Subject: [PATCH 02/13] cards: consolidate the two hmib dashboard adapters into one shared factory Fold js/hmib_summary_dashboard.js into js/hmib_dashboard.js: a single hmibDashInit(opts) factory wires either dashboard (the per-device Host Dashboard or the OS-type-scoped Fleet Dashboard) from a small per-scope config, removing the near-duplicate second adapter that tripped the SonarCloud new-code duplication gate. The summary page now loads js/hmib_dashboard.js and calls initHmibSummaryDashboard(). No behaviour change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- hmib.php | 2 +- js/hmib_dashboard.js | 339 +++++++++++++++++++---------------- js/hmib_summary_dashboard.js | 298 ------------------------------ 4 files changed, 186 insertions(+), 455 deletions(-) delete mode 100644 js/hmib_summary_dashboard.js diff --git a/CHANGELOG.md b/CHANGELOG.md index f3fd57b..8de45cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ ChangeLog --- develop --- -* dev: Adopt the shared Cacti dashboarding Card API across both dashboards: the per-device Host Dashboard and the Fleet (Summary) Dashboard now drive their card grids through the shared `js/cards.js` (`CactiCards`) controller plus thin `js/hmib_dashboard.js` / `js/hmib_summary_dashboard.js` adapters, the card markup uses the shared `.cc*` chrome contract, and the card-body charts (gauge, usage/distribution bars, min/avg/max bullet, stacked bar, stat tiles) use the shared `.cc*` chart-widget primitives. On Cacti 1.2.32+ the chrome and widgets come from core (`include/js/cards.js`, `include/css/cards.css`, `include/css/card-widgets.css`); on older cores hmib bundles its own byte-identical copies, gated by `file_exists`. Card header severity now uses the shared `data-severity` wash. No functional change to the dashboards +* dev: Adopt the shared Cacti dashboarding Card API across both dashboards: the per-device Host Dashboard and the Fleet (Summary) Dashboard now drive their card grids through the shared `js/cards.js` (`CactiCards`) controller plus a thin shared `js/hmib_dashboard.js` adapter, the card markup uses the shared `.cc*` chrome contract, and the card-body charts (gauge, usage/distribution bars, min/avg/max bullet, stacked bar, stat tiles) use the shared `.cc*` chart-widget primitives. On Cacti 1.2.32+ the chrome and widgets come from core (`include/js/cards.js`, `include/css/cards.css`, `include/css/card-widgets.css`); on older cores hmib bundles its own byte-identical copies, gated by `file_exists`. Card header severity now uses the shared `data-severity` wash. No functional change to the dashboards * dev: Restore missing characters in the unmatched device-type regression test so PHP syntax checks and the test can run * dev: Run the CI poller with the shared runner group so RRD files and structured directories pass permission verification * issue: Fix the Fleet Dashboard Uptime Distribution still showing all zeros by sourcing it from the Cacti host table's snmp_sysUpTimeInstance directly instead of the frequently-unreported Host Resources hrSystemUptime/sysUpTime columns diff --git a/hmib.php b/hmib.php index 0911f0b..3f1e61c 100644 --- a/hmib.php +++ b/hmib.php @@ -5283,7 +5283,7 @@ function hmib_summary_dashboard(): void { if (!file_exists($config['base_path'] . '/include/js/cards.js')) { print ''; } - print ''; + print ''; $layout = hmib_summary_layout($ostype); $meta = hmib_summary_card_meta(); diff --git a/js/hmib_dashboard.js b/js/hmib_dashboard.js index a8536a0..3736439 100644 --- a/js/hmib_dashboard.js +++ b/js/hmib_dashboard.js @@ -17,19 +17,19 @@ */ /* - * Host Dashboard adapter for the shared card chrome (js/cards.js). The - * CactiCards controller owns drag/keyboard reorder and the per-card tools; this - * adapter maps those to hmib's server endpoints (hmib.php) and wires hmib's - * dashboard extras - sortable card tables, the device picker, the auto-refresh - * interval and manual refresh-all. The card markup uses the shared .cc* - * contract and the card bodies the shared .cc* chart primitives. + * Host MIB dashboard adapter for the shared card chrome (js/cards.js). One + * factory (hmibDashInit) wires either dashboard - the per-device Host Dashboard + * or the OS-type-scoped Fleet (Summary) Dashboard - to the CactiCards + * controller, which owns drag/keyboard reorder and the per-card tools. The + * factory maps the adapter hooks to hmib's endpoints and adds hmib's extras: + * sortable card tables, a scope picker, the auto-refresh interval and a manual + * refresh-all. Card markup uses the shared .cc* contract and the card bodies + * the shared .cc* chart primitives. */ -var hmibDashAdapter = null; - /* Named navigation callback for the device picker. The select2 drop_callback - * invokes this by name on selection (it does not emit a change event on older - * Cacti), so it must stay global for executeFunctionByName(). */ + * invokes this by name on selection (no change event on older Cacti), so it + * must stay global for executeFunctionByName(). */ function hmibDashboardNavigate() { var host = document.getElementById('hmib_dashboard_host'); @@ -93,7 +93,7 @@ function hmibDashSortTable(th) { } if (numeric) { var raw = cell.dataset.sortValue !== undefined ? cell.dataset.sortValue : cell.textContent; - var num = parseFloat(String(raw).replace(/[^0-9.\-]/g, '')); + var num = Number.parseFloat(String(raw).replace(/[^0-9.\-]/g, '')); return isNaN(num) ? 0 : num; } return cell.textContent.trim().toLowerCase(); @@ -112,199 +112,228 @@ function hmibDashSortTable(th) { }); } -/* Rebuild the "Add" dropdown so it lists only cards not currently on the page. */ -function hmibDashSyncAddOptions(grid) { - var add = document.getElementById('hmib_dashboard_add'); - - if (!add || typeof hmibDashCatalog === 'undefined') { - return; - } - - var present = {}; - - grid.querySelectorAll('.ccCard').forEach(function(card) { - if (card.dataset.card) { - present[card.dataset.card] = true; - } - }); - - while (add.options.length > 1) { - add.remove(1); - } - - Object.keys(hmibDashCatalog).forEach(function(key) { - if (!present[key]) { - var option = document.createElement('option'); - option.value = key; - option.textContent = hmibDashCatalog[key]; - add.appendChild(option); - } - }); -} - -/* Open a copy of a card's body in a large modal dialog, re-wiring the clone's - * sortable table headers (they live outside the grid). */ -function hmibDashMaximize(card) { - var dialog = document.getElementById('hmib_dashboard_dialog'); - - if (!dialog) { - return; - } - - var title = card.querySelector('.ccTitle'); - var body = card.querySelector('.ccCardBody'); - - dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; - - hmibDashPrepSortHeaders(dialog); - $(dialog).off('click.hmibdashsort').on('click.hmibdashsort', 'th.hmibDashSortable', function() { +/* Wire sortable-table handlers (mouse + keyboard) on a container. */ +function hmibDashBindSort(container, namespace) { + $(container).off('click.' + namespace).on('click.' + namespace, 'th.hmibDashSortable', function() { hmibDashSortTable(this); }); - $(dialog).off('keydown.hmibdashsort').on('keydown.hmibdashsort', 'th.hmibDashSortable', function(event) { + $(container).off('keydown.' + namespace).on('keydown.' + namespace, 'th.hmibDashSortable', function(event) { if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { event.preventDefault(); hmibDashSortTable(this); } }); - - $(dialog).dialog({ - modal: true, - appendTo: 'body', - width: Math.min(900, $(window).width() - 40), - title: title ? title.textContent : '' - }); } -/* Fetch a single card's HTML from the server (used by refresh/add). */ -function hmibDashFetch(grid, id, expanded) { - return $.post('hmib.php', { - action: 'dashboard_card', - card: id, - device: grid.dataset.host, - expanded: expanded ? '1' : '0', - __csrf_magic: csrfMagicToken - }, null, 'json').then(function(data) { - return data && data.html ? data.html : null; - }); -} +/* + * Wire one dashboard grid to the shared card chrome plus hmib's extras. opts: + * gridId, addId, dialogId, intervalId, refreshNowId, pickerId - element ids + * cardAction, layoutAction, refreshAction - hmib.php actions + * refreshReload - URL to reload on interval change + * scopeName, scopeAttr - POST param name + grid.dataset key + * catalogVar - global catalogue object name + * onPickerChange(el) - scope picker handler + */ +function hmibDashInit(opts) { + $(function() { + var grid = document.getElementById(opts.gridId); -/* Persist order + expanded state and resync the "Add" catalogue. */ -function hmibDashPostLayout(grid, state) { - var expanded = {}; + if (!grid || !window.CactiCards) { + return; + } - state.order.forEach(function(id) { - if (state.cards[id] && state.cards[id].expanded) { - expanded[id] = true; + function catalogue() { + return typeof window[opts.catalogVar] !== 'undefined' ? window[opts.catalogVar] : null; } - }); - $.post('hmib.php', { - action: 'dashboard_layout', - layout: JSON.stringify({order: state.order, expanded: expanded}), - __csrf_magic: csrfMagicToken - }, null, 'json'); + function syncAddOptions() { + var add = document.getElementById(opts.addId); + var cat = catalogue(); - hmibDashSyncAddOptions(grid); -} + if (!add || !cat) { + return; + } -/* Refresh every card on the page, spinning the toolbar glyph until all land. */ -function hmibDashRefreshAll(grid, button) { - var icon = button ? button.querySelector('.fa, .fas') : null; - var cards = Array.prototype.slice.call(grid.querySelectorAll('.ccCard')); - var pending = cards.length; + var present = {}; - if (!pending) { - return; - } + grid.querySelectorAll('.ccCard').forEach(function(card) { + if (card.dataset.card) { + present[card.dataset.card] = true; + } + }); - if (icon) { - icon.classList.add('fa-spin'); - } + while (add.options.length > 1) { + add.remove(1); + } - cards.forEach(function(card) { - var expanded = card.classList.contains('ccCardExpanded'); + Object.keys(cat).forEach(function(key) { + if (!present[key]) { + var option = document.createElement('option'); + option.value = key; + option.textContent = cat[key]; + add.appendChild(option); + } + }); + } - hmibDashFetch(grid, card.dataset.card, expanded).then(function(html) { - if (html && card.parentNode && window.CactiCards) { - CactiCards.replaceCard(grid, hmibDashAdapter, card, html); - } - }).always(function() { - pending--; - if (pending <= 0 && icon) { - icon.classList.remove('fa-spin'); + function fetchCard(id, expanded) { + var data = {action: opts.cardAction, card: id, expanded: expanded ? '1' : '0', __csrf_magic: csrfMagicToken}; + data[opts.scopeName] = grid.dataset[opts.scopeAttr]; + + return $.post('hmib.php', data, null, 'json').then(function(d) { + return d && d.html ? d.html : null; + }); + } + + function maximize(card) { + var dialog = document.getElementById(opts.dialogId); + + if (!dialog) { + return; } - }); - }); -} -/* Wire the Host Dashboard grid to the shared card chrome plus hmib's extras. */ -function initHmibDashboard() { - $(function() { - var grid = document.getElementById('hmib_dashboard'); + var title = card.querySelector('.ccTitle'); + var body = card.querySelector('.ccCardBody'); - if (!grid || !window.CactiCards) { - return; + dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; + + hmibDashPrepSortHeaders(dialog); + hmibDashBindSort(dialog, 'hmibdlgsort'); + + $(dialog).dialog({ + modal: true, + appendTo: 'body', + width: Math.min(900, $(window).width() - 40), + title: title ? title.textContent : '' + }); } - hmibDashAdapter = { - addControl: 'hmib_dashboard_add', + var adapter = { + addControl: opts.addId, fetchCard: function(id, state) { - return hmibDashFetch(grid, id, state && state.expanded); + return fetchCard(id, state && state.expanded); }, onAddCard: function(id) { - return hmibDashFetch(grid, id, false); + return fetchCard(id, false); }, onLayoutChange: function(state) { - hmibDashPostLayout(grid, state); + var expanded = {}; + + state.order.forEach(function(id) { + if (state.cards[id] && state.cards[id].expanded) { + expanded[id] = true; + } + }); + + $.post('hmib.php', { + action: opts.layoutAction, + layout: JSON.stringify({order: state.order, expanded: expanded}), + __csrf_magic: csrfMagicToken + }, null, 'json'); + + syncAddOptions(); }, maximize: function(id, mode, card) { - hmibDashMaximize(card); + maximize(card); } }; - CactiCards.init(grid, hmibDashAdapter); - hmibDashSyncAddOptions(grid); + CactiCards.init(grid, adapter); + syncAddOptions(); + hmibDashBindSort(grid, 'hmibsort'); - // Client-side column sorting for card tables (mouse and keyboard). - $(grid).off('click.hmibdashsort').on('click.hmibdashsort', 'th.hmibDashSortable', function() { - hmibDashSortTable(this); - }); - $(grid).off('keydown.hmibdashsort').on('keydown.hmibdashsort', 'th.hmibDashSortable', function(event) { - if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { - event.preventDefault(); - hmibDashSortTable(this); - } - }); - - // Device picker: the plain-'; @@ -4820,7 +4844,7 @@ function hmib_summary_bullet(string $label, ?float $min, ?float $avg, ?float $ma $width = max(0.75, ($hi - $lo) / $scale * 100); $mark = $av / $scale * 100; - $sev = in_array($severity, ['up', 'recovering', 'down'], true) ? $severity : 'none'; + $sev = hmib_dashboard_severity_class($severity); return '
' . $head . '
' @@ -4903,7 +4927,7 @@ function hmib_summary_card_body(string $key, int $ostype): string { print '
'; foreach ($tiles as $tile) { - $mod = $tile[0] !== '' ? ' ccTile--' . $tile[0] : ''; + $mod = $tile[0] !== '' ? ' ccTile--' . hmib_dashboard_severity_class($tile[0]) : ''; print '
' . html_escape($tile[1]) . '' . html_escape($tile[2]) . '
'; } print '
'; @@ -4937,14 +4961,14 @@ function hmib_summary_card_body(string $key, int $ostype): string { print '
'; foreach ($segs as $seg) { if ($seg[1] > 0) { - print '
'; + print '
'; } } print '
'; print '
'; foreach ($segs as $seg) { - print '' . html_escape($seg[2]) . ' ' . number_format_i18n($seg[1], 0) . ''; + print '' . html_escape($seg[2]) . ' ' . number_format_i18n($seg[1], 0) . ''; } print '
'; @@ -5303,7 +5327,7 @@ function hmib_summary_dashboard(): void { $page_refresh_interval = [0 => __('No Refresh', 'hmib'), 30 => __('30 Seconds', 'hmib'), 60 => __('1 Minute', 'hmib'), 300 => __('5 Minutes', 'hmib')]; } - print '
'; + print '
'; print ''; print '