diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b387f5..61674742 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ --- develop --- * issue#399: Use the registered Aruba AOS-CX callback names in the built-in 6200/6300 device types and repair existing defaults during upgrade +* dev: Adopt the shared, byte-identical dashboarding card chrome used across the Cacti plugins: the MacTrack dashboard now drives its card grid through the shared `js/cards.js` (`CactiCards`) controller plus a thin `js/mactrack_dashboard.js` adapter, and the card markup/CSS use the shared `.cc*` contract (`css/cards.css`), with MacTrack's `--cc-*` theme bindings and card-body widgets kept in `css/mactrack-dashboard.css`. No functional change to the dashboard; this aligns MacTrack with the other plugins so the chrome can be promoted to Cacti core unchanged +* dev: Load the shared card chrome from Cacti core on 1.2.32+ (`include/js/cards.js` + `include/css/cards.css`) and only bundle the plugin's own copy on older cores * dev: Run the CI poller with the shared runner group so RRD files and structured directories pass permission verification * issue: Show scan results in a single scrollable dialog (with the completion time appended) instead of stacking a separate toast on top of the results dialog * issue: Format the interface Errors, Discards and Unknown Protocol columns with number_format_i18n() for readability diff --git a/css/cards.css b/css/cards.css index 8c3936a7..d68ef00e 100644 --- a/css/cards.css +++ b/css/cards.css @@ -7,75 +7,89 @@ */ /* - * MacTrack Dashboard card chrome. A grid of status cards with a draggable - * header, per-card tools and optional expand. Colours derive from currentColor - * (the active theme's text colour) via color-mix, so the cards follow every - * theme without per-theme overrides. See js/cards.js for the behaviour and - * mactrack_view_dashboard.php for the markup. + * 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) */ -.mtdashToolbar { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 8px; - margin: 10px 4px 0; -} - -.mtdashToolbarLabel { - font-size: 12px; - font-weight: 600; -} - -.mtdashAdd { - box-sizing: border-box; - min-width: 220px; - padding: 4px 8px; - border: 1px solid color-mix(in srgb, currentColor 28%, transparent); - border-radius: 7px; - background: color-mix(in srgb, currentColor 4%, transparent); - color: inherit; - font-size: 12px; -} - -#mactrack_dashboard.mtdashGrid { +.ccGrid { display: grid; - grid-template-columns: repeat(8, minmax(0, 1fr)); + grid-template-columns: repeat(var(--cc-cols, 4), minmax(0, 1fr)); align-items: start; gap: 14px; margin: 10px 4px; font-variant-numeric: tabular-nums; } -.mtdashSpan1 { grid-column: span 2; } -.mtdashSpan2 { grid-column: span 2; } -.mtdashSpan3 { grid-column: span 4; } -.mtdashSpan4 { grid-column: span 4; } +/* 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; } -@media (min-width: 1200px) { - .mtdashSpan1 { grid-column: span 1; } - .mtdashSpan2 { grid-column: span 2; } - .mtdashSpan3 { grid-column: span 3; } - .mtdashSpan4 { grid-column: span 4; } -} +/* Row span (height) for the "steps" size model. */ +.ccH1 { grid-row: span 1; } +.ccH2 { grid-row: span 2; } +.ccH3 { grid-row: span 3; } -.mtdashCard { +.ccCard { box-sizing: border-box; min-width: 0; display: flex; flex-direction: column; - border: 1px solid color-mix(in srgb, currentColor 22%, transparent); - background: color-mix(in srgb, currentColor 5%, transparent); + 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); - border-radius: 4px; overflow: hidden; } -.mtdashCardDragging { +.ccCardDragging { opacity: 0.5; } -.mtdashCardHeader { +.ccCardHeader { box-sizing: border-box; /* fixed row height so a tool/handle hover highlight never reflows the header */ min-height: 34px; @@ -83,11 +97,17 @@ align-items: center; gap: 8px; padding: 7px 10px; - border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent); - background: color-mix(in srgb, currentColor 9%, transparent); + 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)); } -.mtdashCardDrag { +/* 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; @@ -101,19 +121,24 @@ cursor: grab; } -.mtdashCardDrag:hover, -.mtdashCardDrag:focus-visible { +.ccDrag:hover, +.ccDrag:focus-visible { color: currentColor; border-color: transparent; background: color-mix(in srgb, currentColor 12%, transparent); outline: none; } -.mtdashCardDrag:active { +.ccDrag:active { cursor: grabbing; } -.mtdashCardTitle { +/* 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; @@ -125,14 +150,14 @@ white-space: nowrap; } -.mtdashCardTools { +.ccTools { flex: 0 0 auto; display: flex; align-items: center; gap: 1px; } -.mtdashCardTool { +.ccTool { box-sizing: border-box; padding: 2px 5px; /* reserve the border so a hover/focus highlight recolours it instead of resizing the header */ @@ -145,8 +170,8 @@ cursor: pointer; } -.mtdashCardTool:hover, -.mtdashCardTool:focus-visible { +.ccTool:hover, +.ccTool:focus-visible { color: currentColor; border-color: transparent; background: color-mix(in srgb, currentColor 12%, transparent); @@ -154,25 +179,37 @@ } /* Only the control matching the card's current state is shown. */ -.mtdashCard:not(.mtdashCardExpanded) .mtdashCardTool[data-tool="collapse"], -.mtdashCardExpanded .mtdashCardTool[data-tool="expand"] { +.ccCard:not(.ccCardExpanded) .ccTool[data-tool="collapse"], +.ccCardExpanded .ccTool[data-tool="expand"] { display: none; } -.mtdashCardBody { - padding: 6px 12px 10px; +/* 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. */ -.mtdashCardExpandable:not(.mtdashCardExpanded) .mtdashCardBody { +.ccCardExpandable:not(.ccCardExpanded) .ccCardBody { position: relative; - max-height: 220px; + max-height: 210px; overflow: hidden; } -.mtdashCardExpandable:not(.mtdashCardExpanded) .mtdashCardBody::after { +.ccCardExpandable:not(.ccCardExpanded) .ccCardBody::after { content: ''; position: absolute; left: 0; @@ -180,105 +217,82 @@ bottom: 0; height: 30px; pointer-events: none; - background: linear-gradient(transparent, color-mix(in srgb, currentColor 5%, transparent)); -} - -.mtdashTable { - width: 100%; - border-collapse: collapse; - font-size: 12px; -} - -.mtdashTable th, -.mtdashTable td { - padding: 6px 8px; - text-align: left; - vertical-align: top; - overflow-wrap: anywhere; + background: linear-gradient(transparent, color-mix(in srgb, var(--cc-text, #23362f) 4%, var(--cc-card, #fff))); } -.mtdashTable thead th { - font-weight: 600; - border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent); -} - -.mtdashKv tbody th { - font-weight: normal; - color: color-mix(in srgb, currentColor 75%, transparent); +/* + * 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); } -.mtdashKv td { - text-align: right; - font-weight: 600; +.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); } -.mtdashTable tbody tr + tr > th, -.mtdashTable tbody tr + tr > td { - border-top: 1px solid color-mix(in srgb, currentColor 9%, 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); } -.mtdashEmpty { - color: color-mix(in srgb, currentColor 60%, transparent); - font-style: italic; +.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); } -/* Proportion bars (device status, table sizes). */ -.mtdashBars { +/* "Add card" toolbar above the grid. */ +.ccToolbar { display: flex; - flex-direction: column; + flex-wrap: wrap; + align-items: center; gap: 8px; + margin: 10px 4px 0; } -.mtdashBarRow { - display: flex; - flex-direction: column; - gap: 3px; -} - -.mtdashBarHead { - display: flex; - justify-content: space-between; +.ccToolbarLabel { font-size: 12px; + font-weight: 600; + color: var(--cc-text, #23362f); } -.mtdashBar, -.mtdashInlineBar { - position: relative; - height: 8px; - border-radius: 4px; - background: color-mix(in srgb, currentColor 12%, transparent); - overflow: hidden; +.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; } -.mtdashInlineBar { - display: block; - margin-bottom: 2px; +.ccAdd { + min-width: 220px; } -.mtdashBarFill { - display: block; - height: 100%; - border-radius: 4px; - background: color-mix(in srgb, currentColor 45%, transparent); +.ccRefresh { + display: flex; + align-items: center; + gap: 8px; + margin-left: auto; } -.mtdashBarFill.mtdash-up { background: #2b8435; } -.mtdashBarFill.mtdash-warn { background: #a85712; } -.mtdashBarFill.mtdash-down { background: #a12820; } -.mtdashBarFill.mtdash-none { background: color-mix(in srgb, currentColor 40%, transparent); } - -.mtdashDialogBody { +/* Maximize dialog: reuse the card body typography on the themed dialog surface. */ +.ccDialogBody { + color: var(--cc-text, #23362f); font-variant-numeric: tabular-nums; } - -.mtdashDialogBody .mtdashTable { - font-size: 13px; -} - - -/* Scan results dialog (device/site/interface rescan): keep long scanner - output inside the dialog with a vertical scrollbar instead of overflowing. */ -.mactrackScanResults { - max-height: 60vh; - overflow-y: auto; -} \ No newline at end of file diff --git a/css/mactrack-dashboard.css b/css/mactrack-dashboard.css new file mode 100644 index 00000000..2ee1dd8c --- /dev/null +++ b/css/mactrack-dashboard.css @@ -0,0 +1,146 @@ +/* + +-------------------------------------------------------------------------+ + | Copyright (C) 2004-2026 The Cacti Group | + +-------------------------------------------------------------------------+ + | Cacti: The Complete RRDtool-based Graphing Solution | + +-------------------------------------------------------------------------+ +*/ + +/* + * MacTrack dashboard: theme bindings + content widgets for the shared card + * chrome (css/cards.css). The chrome stylesheet is byte-identical across every + * plugin and draws its colours from --cc-* custom properties; this file maps + * those to MacTrack's currentColor-derived palette and styles the MacTrack + * specific card bodies (tables, key/value lists, proportion bars). See + * js/cards.js for behaviour and mactrack_view_dashboard.php for the markup. + */ + +/* Bind the shared chrome variables to MacTrack's theme-agnostic palette. + Everything derives from currentColor (the active theme's text colour) so the + cards follow every Cacti theme without per-theme overrides. These are bound + to the whole dashboard panel and to the maximize dialog (which jQuery UI moves + under ), not just the grid, so the Add toolbar (a sibling of the grid) + and the maximized content inherit the active theme instead of the shared + chrome's light-theme fallbacks. */ +#mactrack_dashboard_panel, +#mactrack_dashboard_dialog { + --cc-card: transparent; + --cc-text: currentColor; + --cc-border: color-mix(in srgb, currentColor 22%, transparent); + --cc-header-bg: color-mix(in srgb, currentColor 9%, transparent); +} + +/* The grid is 8 columns wide. */ +#mactrack_dashboard.ccGrid { + --cc-cols: 8; +} + +/* Below 1200px, widen the narrow spans so cards stay legible (mirrors the + previous MacTrack responsive behaviour). */ +@media (max-width: 1199px) { + #mactrack_dashboard .ccW1 { grid-column: span 2; } + #mactrack_dashboard .ccW2 { grid-column: span 2; } + #mactrack_dashboard .ccW3 { grid-column: span 4; } + #mactrack_dashboard .ccW4 { grid-column: span 4; } +} + +/* ---- MacTrack card-body content widgets ---- */ + +.mtdashTable { + width: 100%; + border-collapse: collapse; + font-size: 12px; +} + +.mtdashTable th, +.mtdashTable td { + padding: 6px 8px; + text-align: left; + vertical-align: top; + overflow-wrap: anywhere; +} + +.mtdashTable thead th { + font-weight: 600; + border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent); +} + +.mtdashKv tbody th { + font-weight: normal; + color: color-mix(in srgb, currentColor 75%, transparent); +} + +.mtdashKv td { + text-align: right; + font-weight: 600; +} + +.mtdashTable tbody tr + tr > th, +.mtdashTable tbody tr + tr > td { + border-top: 1px solid color-mix(in srgb, currentColor 9%, transparent); +} + +.mtdashEmpty { + color: color-mix(in srgb, currentColor 60%, transparent); + font-style: italic; +} + +/* Proportion bars (device status, table sizes). */ +.mtdashBars { + display: flex; + flex-direction: column; + gap: 8px; +} + +.mtdashBarRow { + display: flex; + flex-direction: column; + gap: 3px; +} + +.mtdashBarHead { + display: flex; + justify-content: space-between; + font-size: 12px; +} + +.mtdashBar, +.mtdashInlineBar { + position: relative; + height: 8px; + border-radius: 4px; + background: color-mix(in srgb, currentColor 12%, transparent); + overflow: hidden; +} + +.mtdashInlineBar { + display: block; + margin-bottom: 2px; +} + +.mtdashBarFill { + display: block; + height: 100%; + border-radius: 4px; + background: color-mix(in srgb, currentColor 45%, transparent); +} + +.mtdashBarFill.mtdash-up { background: #2b8435; } +.mtdashBarFill.mtdash-warn { background: #a85712; } +.mtdashBarFill.mtdash-down { background: #a12820; } +.mtdashBarFill.mtdash-none { background: color-mix(in srgb, currentColor 40%, transparent); } + +.ccDialogBody { + font-variant-numeric: tabular-nums; +} + +.ccDialogBody .mtdashTable { + font-size: 13px; +} + +/* Scan results dialog (device/site/interface rescan): keep long scanner + output inside the dialog with a vertical scrollbar instead of overflowing. */ +.mactrackScanResults { + max-height: 60vh; + overflow-y: auto; +} diff --git a/js/cards.js b/js/cards.js index f1f9b843..5005c420 100644 --- a/js/cards.js +++ b/js/cards.js @@ -7,336 +7,405 @@ */ /* - * MacTrack Dashboard card controller. Wires the card grid on the Dashboard tab: - * drag/keyboard reordering, the per-card tools (show more/less, maximize, - * refresh, remove) and the "Add card" catalogue. Layout changes persist - * server-side (settings_user) so they survive page revisits. The card markup - * is rendered by mactrack_view_dashboard.php; this file only drives behaviour. + * 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. */ -var mactrackDashboardDragging = null; +window.CactiCards = window.CactiCards || (function() { + 'use strict'; -function initMactrackDashboard() { - $(function() { - var grid = document.getElementById('mactrack_dashboard'); + var dragging = null; - if (!grid) { - return; - } + function cardSel(adapter) { + return adapter.cardSelector || '.ccCard'; + } - grid.querySelectorAll('.mtdashCard').forEach(function(card) { - mactrackDashboardBindCard(grid, card); - }); + function cardId(card, adapter) { + return card.getAttribute(adapter.idAttr || 'data-card'); + } - grid.addEventListener('dragover', function(event) { - if (!mactrackDashboardDragging) { - return; + /* 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; + } - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - - var before = mactrackDashboardDragReference(grid, event.clientX, event.clientY); + /* 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'); + } - if (before == null) { - grid.appendChild(mactrackDashboardDragging); - } else if (before !== mactrackDashboardDragging) { - grid.insertBefore(mactrackDashboardDragging, before); - } - }); + 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'); + } - // Per-card tool buttons bubble to the grid. - $(grid).off('click.mtdash').on('click.mtdash', '.mtdashCardTool', function() { - var card = this.closest('.mtdashCard'); + /* Collect the current order and per-card state for persistence. */ + function serialize(grid, adapter) { + var order = []; + var cards = {}; - if (!card) { + grid.querySelectorAll(cardSel(adapter)).forEach(function(card) { + var id = cardId(card, adapter); + if (id == null) { return; } - - switch (this.dataset.tool) { - case 'expand': card.classList.add('mtdashCardExpanded'); mactrackDashboardSaveLayout(grid); break; - case 'collapse': card.classList.remove('mtdashCardExpanded'); mactrackDashboardSaveLayout(grid); break; - case 'maximize': mactrackDashboardMaximize(card); break; - case 'refresh': mactrackDashboardRefreshCard(grid, card); break; - case 'remove': mactrackDashboardRemoveCard(grid, card); break; - } + order.push(id); + cards[id] = { + expanded: card.classList.contains('ccCardExpanded'), + height: Number.parseInt(card.getAttribute('data-height') || '1', 10) + }; }); - var add = document.getElementById('mactrack_dashboard_add'); - - if (add) { - $(add).off('change.mtdash').on('change.mtdash', function() { - var key = this.value; - this.value = ''; - - if (key) { - mactrackDashboardAddCard(grid, key); - } - }); - } - }); -} - -/** Wire a single card's drag handle (mouse + keyboard) and drag events. */ -function mactrackDashboardBindCard(grid, card) { - var handle = card.querySelector('.mtdashCardDrag'); - - if (!handle) { - return; + return { order: order, cards: cards }; } - // Arm HTML5 drag only from the handle, and disarm on release when no drag - // began (a plain click/tap) so selecting content elsewhere can't drag the card. - var disarm = function() { card.draggable = false; }; - - handle.addEventListener('mousedown', function() { - card.draggable = true; - document.addEventListener('mouseup', disarm, {once: true}); - }); - - handle.addEventListener('touchstart', function() { - card.draggable = true; - document.addEventListener('touchend', disarm, {once: true}); - document.addEventListener('touchcancel', disarm, {once: true}); - }, {passive: true}); - - // Keyboard-accessible reordering: move the card with the arrow keys. - handle.addEventListener('keydown', function(event) { - var back = event.key === 'ArrowLeft' || event.key === 'ArrowUp'; - var fwd = event.key === 'ArrowRight' || event.key === 'ArrowDown'; - - if (!back && !fwd) { + /* Debounce layout saves so a burst of reorders coalesces into one call. */ + function saveLayout(grid, adapter) { + if (typeof adapter.onLayoutChange !== 'function') { return; } - - event.preventDefault(); - - if (back && card.previousElementSibling) { - grid.insertBefore(card, card.previousElementSibling); - } else if (fwd && card.nextElementSibling) { - grid.insertBefore(card.nextElementSibling, card); - } else { - return; + if (grid.__ccSaveTimer) { + clearTimeout(grid.__ccSaveTimer); } + grid.__ccSaveTimer = setTimeout(function() { + grid.__ccSaveTimer = null; + adapter.onLayoutChange(serialize(grid, adapter)); + }, 250); + } - handle.focus(); - mactrackDashboardSaveLayout(grid); - }); - - card.addEventListener('dragstart', function(event) { - mactrackDashboardDragging = card; - card.classList.add('mtdashCardDragging'); - event.dataTransfer.effectAllowed = 'move'; - try { event.dataTransfer.setData('text/plain', card.dataset.card || ''); } catch (error) { /* IE guard */ } - }); + /* 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; + } + }); - card.addEventListener('dragend', function() { - card.draggable = false; - card.classList.remove('mtdashCardDragging'); + return rowMatch || belowMatch; + } - if (mactrackDashboardDragging) { - mactrackDashboardDragging = null; - mactrackDashboardSaveLayout(grid); + /* 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; } - }); -} - -/** The card the dragged card should be inserted before for the current pointer - * position, or null to append at the end. */ -function mactrackDashboardDragReference(grid, x, y) { - var cards = Array.prototype.slice.call(grid.querySelectorAll('.mtdashCard:not(.mtdashCardDragging)')); - - for (var i = 0; i < cards.length; i++) { - var rect = cards[i].getBoundingClientRect(); - - if (y < rect.top - 1) { - return cards[i]; + // 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 (y <= rect.bottom && x < rect.left + rect.width / 2) { - return cards[i]; + 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; } - return null; -} - -/** Add a card from the catalogue: fetch its HTML, append it, persist and - * refresh the "Add" options. */ -function mactrackDashboardAddCard(grid, key) { - if (mactrackDashboardHasCard(grid, key)) { - return; - } - - $.post('mactrack_view_dashboard.php', {action: 'dash_card', card: key, __csrf_magic: csrfMagicToken}, null, 'json').done(function(data) { - if (!data || !data.html || mactrackDashboardHasCard(grid, key)) { + 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; } - - var card = mactrackDashboardParseCard(data.html); - - if (!card) { + if (typeof adapter.fetchCard !== 'function') { return; } - - grid.appendChild(card); - mactrackDashboardBindCard(grid, card); - mactrackDashboardSaveLayout(grid); - mactrackDashboardSyncAddOptions(grid); - }); -} - -/** Whether a card with the given key is currently on the grid. */ -function mactrackDashboardHasCard(grid, key) { - var present = false; - - grid.querySelectorAll('.mtdashCard').forEach(function(card) { - if (card.dataset.card === key) { - present = true; - } - }); - - return present; -} - -/** Remove a card from the page and return it to the "Add" catalogue. */ -function mactrackDashboardRemoveCard(grid, card) { - card.parentNode.removeChild(card); - mactrackDashboardSaveLayout(grid); - mactrackDashboardSyncAddOptions(grid); -} - -/** Re-fetch a single card's HTML and swap it in place, keeping expanded state. */ -function mactrackDashboardRefreshCard(grid, card, done) { - var icon = card.querySelector('.mtdashCardTool[data-tool="refresh"] .fa'); - - if (icon) { - icon.classList.add('fa-spin'); + 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 */ }); } - var settle = function() { - if (icon) { - icon.classList.remove('fa-spin'); - } - - if (done) { - done(); + function removeCard(grid, adapter, card) { + var id = cardId(card, adapter); + if (typeof adapter.onRemoveCard === 'function') { + adapter.onRemoveCard(id, card); } - }; - - var expanded = card.classList.contains('mtdashCardExpanded') ? '1' : '0'; + card.parentNode.removeChild(card); + saveLayout(grid, adapter); + } - $.post('mactrack_view_dashboard.php', {action: 'dash_card', card: card.dataset.card, expanded: expanded, __csrf_magic: csrfMagicToken}, null, 'json').done(function(data) { - if (!data || !data.html || !card.parentNode) { - settle(); - return; + 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); } + } - var fresh = mactrackDashboardParseCard(data.html); - - if (!fresh) { - settle(); + /* 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; - card.parentNode.replaceChild(fresh, card); - mactrackDashboardBindCard(grid, fresh); - - if (done) { - done(); - } - }).fail(settle); -} - -/** Open a copy of a card's body in a large modal dialog. */ -function mactrackDashboardMaximize(card) { - var dialog = document.getElementById('mactrack_dashboard_dialog'); + normalizeState(card); - if (!dialog) { - return; - } - - var title = card.querySelector('.mtdashCardTitle'); - var body = card.querySelector('.mtdashCardBody'); - - dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; - - $(dialog).dialog({ - modal: true, - appendTo: 'body', - width: Math.min(900, $(window).width() - 40), - title: title ? title.textContent : '' - }); -} - -/** Parse a card HTML string into its
element. */ -function mactrackDashboardParseCard(html) { - var tmp = document.createElement('div'); - tmp.innerHTML = html; + var onHandle = function(target) { + return target && target.closest && target.closest('.ccDrag'); + }; - return tmp.querySelector('.mtdashCard'); -} - -/** Rebuild the "Add" dropdown so it lists only cards not currently on the page. */ -function mactrackDashboardSyncAddOptions(grid) { - var add = document.getElementById('mactrack_dashboard_add'); + // 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); + }); - if (!add) { - return; + 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); + }); } - var present = {}; - - grid.querySelectorAll('.mtdashCard').forEach(function(card) { - if (card.dataset.card) { - present[card.dataset.card] = true; + function init(grid, adapter) { + if (!grid || grid.__ccInit) { + return; } - }); - - // Options for present cards are removed; absent ones are kept/restored by - // leaving the server-rendered option list and only hiding present ones. - for (var i = 1; i < add.options.length; i++) { - add.options[i].hidden = !!present[add.options[i].value]; - } -} - -/** Serialize layout POSTs so rapid actions can't persist out of order. */ -var mactrackDashboardSaveInFlight = false; -var mactrackDashboardSaveQueued = false; + grid.__ccInit = true; + adapter = adapter || {}; -function mactrackDashboardSaveLayout(grid) { - if (mactrackDashboardSaveInFlight) { - mactrackDashboardSaveQueued = true; - return; - } - - mactrackDashboardSaveInFlight = true; + if (typeof adapter.applyTheme === 'function') { + adapter.applyTheme(grid); + } - var order = []; - var expanded = {}; + grid.querySelectorAll(cardSel(adapter)).forEach(function(card) { + bindCard(grid, adapter, card); + }); - grid.querySelectorAll('.mtdashCard').forEach(function(card) { - if (!card.dataset.card) { - return; - } + 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); + } + }); - order.push(card.dataset.card); + // 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; + } + }); - if (card.classList.contains('mtdashCardExpanded')) { - expanded[card.dataset.card] = true; + // Optional "add card" control referenced by adapter.addControl (an element or id). + var add = adapter.addControl; + if (typeof add === 'string') { + add = document.getElementById(add); } - }); - - $.post('mactrack_view_dashboard.php', { - action: 'dash_layout', - layout: JSON.stringify({order: order, expanded: expanded}), - __csrf_magic: csrfMagicToken - }, null, 'json').always(function() { - mactrackDashboardSaveInFlight = false; - - if (mactrackDashboardSaveQueued) { - mactrackDashboardSaveQueued = false; - mactrackDashboardSaveLayout(grid); + 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/mactrack_dashboard.js b/js/mactrack_dashboard.js new file mode 100644 index 00000000..f4468c88 --- /dev/null +++ b/js/mactrack_dashboard.js @@ -0,0 +1,140 @@ +/* + +-------------------------------------------------------------------------+ + | Copyright (C) 2004-2026 The Cacti Group | + +-------------------------------------------------------------------------+ + | Cacti: The Complete RRDtool-based Graphing Solution | + +-------------------------------------------------------------------------+ +*/ + +/* + * MacTrack Dashboard adapter for the shared card chrome (js/cards.js). The + * controller (window.CactiCards) owns drag/keyboard reorder and the per-card + * tools; this adapter maps those to MacTrack's server endpoints + * (mactrack_view_dashboard.php) and keeps the "Add card" catalogue in sync. + * The card markup is rendered by mactrack_view_dashboard.php using the shared + * .cc* contract. + */ + +/** Hide the "Add" options for cards already on the grid; show the rest. */ +function mactrackDashboardSyncAddOptions(grid) { + var add = document.getElementById('mactrack_dashboard_add'); + + if (!add) { + return; + } + + var present = {}; + + grid.querySelectorAll('.ccCard').forEach(function(card) { + if (card.dataset.card) { + present[card.dataset.card] = true; + } + }); + + for (var i = 1; i < add.options.length; i++) { + add.options[i].hidden = !!present[add.options[i].value]; + } +} + +/** Open a copy of a card's body in a large modal dialog. */ +function mactrackDashboardMaximize(card) { + var dialog = document.getElementById('mactrack_dashboard_dialog'); + + if (!dialog) { + return; + } + + var title = card.querySelector('.ccTitle'); + var body = card.querySelector('.ccCardBody'); + + dialog.innerHTML = '
' + (body ? body.innerHTML : '') + '
'; + + $(dialog).dialog({ + modal: true, + appendTo: 'body', + width: Math.min(900, $(window).width() - 40), + title: title ? title.textContent : '' + }); +} + +/* + * Persist the layout, serialized so a reorder started after an earlier one can + * never be overwritten by that earlier request completing last. The dash_layout + * endpoint replaces the entire saved layout, so write order must be preserved; + * chaining each POST after the previous one settles keeps the newest layout + * authoritative (the shared controller only debounces bursts within 250 ms). + */ +function mactrackDashboardSaveLayout(grid, state) { + var expanded = {}; + + state.order.forEach(function(id) { + if (state.cards[id] && state.cards[id].expanded) { + expanded[id] = true; + } + }); + + var data = { + action: 'dash_layout', + layout: JSON.stringify({order: state.order, expanded: expanded}), + __csrf_magic: csrfMagicToken + }; + + var post = function() { + return $.post('mactrack_view_dashboard.php', data, null, 'json'); + }; + + var pending = grid.__mtLayoutSave || $.Deferred().resolve().promise(); + + /* Continue the chain whether the previous save resolved or rejected. */ + grid.__mtLayoutSave = pending.then(post, post); +} + +/** Wire the MacTrack dashboard grid to the shared card chrome. */ +function initMactrackDashboard() { + $(function() { + var grid = document.getElementById('mactrack_dashboard'); + + if (!grid || !window.CactiCards) { + return; + } + + CactiCards.init(grid, { + addControl: 'mactrack_dashboard_add', + + /* Refresh: re-fetch a single card's HTML and swap it in place. */ + fetchCard: function(id, state) { + return $.post('mactrack_view_dashboard.php', { + action: 'dash_card', + card: id, + expanded: state && state.expanded ? '1' : '0', + __csrf_magic: csrfMagicToken + }, null, 'json').then(function(data) { + return data && data.html ? data.html : null; + }); + }, + + /* Add a card from the catalogue. */ + onAddCard: function(id) { + return $.post('mactrack_view_dashboard.php', { + action: 'dash_card', + card: id, + __csrf_magic: csrfMagicToken + }, null, 'json').then(function(data) { + return data && data.html ? data.html : null; + }); + }, + + /* Persist order + expanded state and resync the "Add" catalogue. */ + onLayoutChange: function(state) { + mactrackDashboardSaveLayout(grid, state); + mactrackDashboardSyncAddOptions(grid); + }, + + maximize: function(id, mode, card) { + mactrackDashboardMaximize(card); + } + }); + + mactrackDashboardSyncAddOptions(grid); + }); +} diff --git a/mactrack_view_dashboard.php b/mactrack_view_dashboard.php index 77e732ec..068e80bc 100644 --- a/mactrack_view_dashboard.php +++ b/mactrack_view_dashboard.php @@ -400,31 +400,33 @@ function mactrack_dashboard_render_card(string $key, bool $expanded = false): st $tools = ''; if ($def['expandable']) { - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; } - $tools .= ''; - $tools .= ''; - $tools .= ''; + $tools .= ''; + $tools .= ''; + $tools .= ''; - $classes = 'mtdashCard mtdashSpan' . (int) $def['span']; + $classes = 'ccCard ccW' . (int) $def['span']; if ($def['expandable']) { - $classes .= ' mtdashCardExpandable'; + $classes .= ' ccCardExpandable'; } if ($expanded) { - $classes .= ' mtdashCardExpanded'; + $classes .= ' ccCardExpanded'; } - return '
' - . '
' - . '' - . '

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

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

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

' + . '' . $tools . '' . '
' - . '
' . mactrack_dashboard_card_body($key) . '
' + . '
' . mactrack_dashboard_card_body($key) . '
' . '
'; } @@ -540,9 +542,9 @@ function mactrack_dashboard(): void { print '
'; - print '
'; - print ''; - print ''; foreach ($absent as $key) { print ''; @@ -551,7 +553,7 @@ function mactrack_dashboard(): void { print ''; print '
'; - print '
'; + print '
'; foreach ($layout['order'] as $key) { print mactrack_dashboard_render_card($key, !empty($layout['expanded'][$key])); diff --git a/setup.php b/setup.php index f4cbd5ee..caa7c430 100644 --- a/setup.php +++ b/setup.php @@ -525,11 +525,22 @@ function mactrack_setup_table_new($operator_initiated = true): bool { function mactrack_page_head() { global $config; + // Cacti 1.2.32+ ships the shared card chrome in core (include/js/cards.js + + // include/css/cards.css); bundle the plugin's own copy only when core does + // not provide it. + $core_cards = file_exists($config['base_path'] . '/include/js/cards.js'); + print get_md5_include_js('plugins/mactrack/js/mactrack.js'); print get_md5_include_js('plugins/mactrack/js/mactrack_snmp.js'); - print get_md5_include_js('plugins/mactrack/js/cards.js'); + if (!$core_cards) { + print get_md5_include_js('plugins/mactrack/js/cards.js'); + } + print get_md5_include_js('plugins/mactrack/js/mactrack_dashboard.js'); - print get_md5_include_css('plugins/mactrack/css/cards.css'); + if (!$core_cards) { + print get_md5_include_css('plugins/mactrack/css/cards.css'); + } + print get_md5_include_css('plugins/mactrack/css/mactrack-dashboard.css'); if (file_exists($config['base_path'] . '/plugins/mactrack/css/' . get_selected_theme() . '.css')) { print get_md5_include_css('plugins/mactrack/css/' . get_selected_theme() . '.css');