diff --git a/CHANGELOG.md b/CHANGELOG.md index c160fc0..8de45cd 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 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/css/card-widgets.css b/css/card-widgets.css new file mode 100644 index 0000000..52842f1 --- /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: 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/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..b8c0785 100644 --- a/css/hmib.css +++ b/css/hmib.css @@ -16,6 +16,32 @@ +-------------------------------------------------------------------------+ */ +/* + * 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 palette is applied to the toolbar + * and maximize dialog as well as the grid, because both live outside the grid + * (the dialog is reparented under by jQuery UI when maximized) and would + * otherwise fall back to the shared stylesheet's light-theme defaults. 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_toolbar, +#hmib_dashboard.ccGrid, +#hmib_dashboard_dialog, +#hmib_summary_toolbar, +#hmib_summary_dashboard.ccGrid, +#hmib_summary_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); +} + /* * Base (light-theme) action-glyph colours for the Host MIB views. Each core * theme that needs different (brighter) values ships a same-named override @@ -479,28 +505,34 @@ /* Narrow the grid before cards get cramped. */ @media (max-width: 1200px) { - .hmibDashGrid { + #hmib_dashboard.ccGrid, + #hmib_summary_dashboard.ccGrid { grid-template-columns: repeat(4, minmax(0, 1fr)); } - .hmibDashSpan4, - .hmibDashSpan6, - .hmibDashSpan8 { + #hmib_dashboard.ccGrid .ccW4, + #hmib_dashboard.ccGrid .ccW5, + #hmib_dashboard.ccGrid .ccW6, + #hmib_dashboard.ccGrid .ccW7, + #hmib_dashboard.ccGrid .ccW8, + #hmib_summary_dashboard.ccGrid .ccW4, + #hmib_summary_dashboard.ccGrid .ccW5, + #hmib_summary_dashboard.ccGrid .ccW6, + #hmib_summary_dashboard.ccGrid .ccW7, + #hmib_summary_dashboard.ccGrid .ccW8 { grid-column: 1 / -1; } } @media (max-width: 760px) { - .hmibDashGrid { + #hmib_dashboard.ccGrid, + #hmib_summary_dashboard.ccGrid { grid-template-columns: 1fr; gap: 10px; } - .hmibDashSpan2, - .hmibDashSpan3, - .hmibDashSpan4, - .hmibDashSpan6, - .hmibDashSpan8 { + #hmib_dashboard.ccGrid > .ccCard, + #hmib_summary_dashboard.ccGrid > .ccCard { grid-column: 1 / -1; } } diff --git a/hmib.php b/hmib.php index 263a418..0b1ef0c 100644 --- a/hmib.php +++ b/hmib.php @@ -109,6 +109,20 @@ 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. +// @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/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'); +} +// @codeCoverageIgnoreEnd + // 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'); @@ -3880,6 +3894,30 @@ function hmib_dashboard_severity(float $percent): string { return 'up'; } +/** + * Map an hmib severity token to the suffix the shared chart-widget CSS + * (include/css/card-widgets.css) expects. hmib's palette uses 'recovering'/'rec' + * for the warning band and 'dis' for disabled; the shared widgets expect 'warn' + * and 'none'. Anything unrecognised collapses to the neutral 'none'. + * + * @param string $token An hmib severity token (up/down/recovering/rec/dis/...). + * + * @return string One of 'up', 'warn', 'down' or 'none'. + */ +function hmib_dashboard_severity_class(string $token): string { + switch ($token) { + case 'up': + case 'down': + return $token; + case 'warn': + case 'recovering': + case 'rec': + return 'warn'; + default: + return 'none'; + } +} + /** * The severity accent for a card header, or '' for a neutral header. Only the * utilization gauge cards carry a severity, derived from their live value; a @@ -3925,14 +3963,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 +3985,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 +4028,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 +4052,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 +4065,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 +4078,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 +4091,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 +4126,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 +4166,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 +4200,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 +4226,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 +4246,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 +4260,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 +4288,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 +4321,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 +4531,11 @@ function hmib_dashboard(): void { ]); } + // @codeCoverageIgnoreStart -- bundled copy loads only on cores lacking it. + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } + // @codeCoverageIgnoreEnd print ''; $system = hmib_dashboard_system($host_id); @@ -4538,10 +4583,10 @@ function hmib_dashboard(): void { form_end(); - print '
'; + print '
'; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -4549,9 +4594,9 @@ function hmib_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -4563,11 +4608,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 +4830,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))); @@ -4799,14 +4844,14 @@ 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 - . '
' - . '
' - . '
' + return '
' . $head + . '
' + . '
' + . '
' . '
' - . '
' . html_escape($fmt($min)) . '' . html_escape($fmt($max)) . '
' + . '
' . html_escape($fmt($min)) . '' . html_escape($fmt($max)) . '
' . '
'; } @@ -4861,7 +4906,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 +4925,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--' . hmib_dashboard_severity_class($tile[0]) : ''; + print '
' . html_escape($tile[1]) . '' . html_escape($tile[2]) . '
'; } print '
'; @@ -4913,17 +4958,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 +4977,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,9 +5016,12 @@ 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') . '

'; + // @codeCoverageIgnoreStart -- unreachable: a scope with devices + // always has at least one OS-type group to list here. + print '

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

'; break; + // @codeCoverageIgnoreEnd } $peak = 1; @@ -4983,10 +5031,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 +5086,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 +5122,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,7 +5312,12 @@ function hmib_summary_dashboard(): void { ]); } - print ''; + // @codeCoverageIgnoreStart -- bundled copy loads only on cores lacking it. + if (!file_exists($config['base_path'] . '/include/js/cards.js')) { + print ''; + } + // @codeCoverageIgnoreEnd + print ''; $layout = hmib_summary_layout($ostype); $meta = hmib_summary_card_meta(); @@ -5272,9 +5327,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 +5350,8 @@ function hmib_summary_dashboard(): void { print ''; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -5304,9 +5359,9 @@ function hmib_summary_dashboard(): void { print ''; - print '
'; - print ''; - print ''; print ''; foreach ($page_refresh_interval as $seconds => $display_text) { @@ -5318,11 +5373,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..82503b9 --- /dev/null +++ b/js/cards.js @@ -0,0 +1,494 @@ +/* + +-------------------------------------------------------------------------+ + | 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; + } + + /* Decide, mirroring normalizeState(), whether a fresh card will be + * expandable, so a preserved toggle is never forced onto a card that cannot + * expand (which would leave normalizeState() marking it ccCardExpanded and + * persisting expanded:true for a non-expandable card). */ + function willExpand(card) { + var expandable = card.getAttribute('data-expandable'); + if (expandable === '1' || expandable === 'true') { + return true; + } + if (expandable != null) { + return false; + } + return card.classList.contains('ccCardExpandable'); + } + + /* Swap a card's markup in place (after refresh/add) and re-bind it. + * + * capturedExpanded (optional) is the card's expanded state when an internal + * refresh/resize request started. When it is supplied and the live card has + * since been toggled by the user, the incoming markup reflects the stale + * captured state, so the live state is carried onto the fresh markup to avoid + * reverting that toggle - but only when the fresh card is still expandable. + * When it is omitted (direct callers) or the state is unchanged, the host + * markup's own data-expanded stays authoritative (the normalizeState + * contract, so a host may still drive expansion through returned markup). */ + function replaceCard(grid, adapter, card, html, capturedExpanded) { + 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; + } + if (capturedExpanded != null) { + var liveExpanded = target.classList.contains('ccCardExpanded'); + if (liveExpanded !== capturedExpanded && willExpand(fresh)) { + fresh.setAttribute('data-expanded', liveExpanded ? '1' : '0'); + } + } + target.parentNode.replaceChild(fresh, target); + bindCard(grid, adapter, fresh); + if (typeof adapter.applyTheme === 'function') { + adapter.applyTheme(grid); + } + 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 + // 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) + }; + var token = startRequest(grid, id); + Promise.resolve(adapter.fetchCard(id, state)).then(function(html) { + // 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, state.expanded); + } + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); + } + + 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') { + Promise.resolve(adapter.onRemoveCard(id, card)).then(commit).catch(function() { + /* rejected: leave the card and its saved layout untouched */ + }); + } else { + commit(); + } + } + + function resizeCard(grid, adapter, card, dir) { + var id = cardId(card, adapter); + if (typeof adapter.onResize === 'function') { + var token = startRequest(grid, id); + var capturedExpanded = card.classList.contains('ccCardExpanded'); + 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, capturedExpanded); + } + saveLayout(grid, adapter); + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); + } else { + saveLayout(grid, adapter); + } + } + + /* 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. */ + 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'); + 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; + 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; + // 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') { + 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..76330f4 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. */ - -var hmibDashDragging = null; +/* + * 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. + */ /* 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 (no change event on older Cacti), so it + * must stay global for executeFunctionByName(). */ function hmibDashboardNavigate() { var host = document.getElementById('hmib_dashboard_host'); @@ -35,302 +38,12 @@ 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-