Files
cacti/include/js/cards.js
T
fb354dbf5e feature: add a shared dashboarding Card API (chrome + chart widgets) to core (#8683)
* feature: add a shared dashboarding Card API (chrome + chart widgets) to core (#8680)

* feature: add a shared dashboarding Card API to core

Ship the shared card chrome used by the dashboarding plugins as core assets:
include/js/cards.js (the window.CactiCards controller) and
include/css/cards.css (the themeable .cc* markup contract). Both are loaded by
the common page header (lib/html.php) so any plugin or core page can render a
draggable, reorderable grid of cards without bundling its own copy.

The files are byte-identical to the copies currently vendored in the intropage
and mactrack plugins; those plugins load the core copy on Cacti 1.2.32+ and
fall back to their bundled copy on older cores.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* test(security): refresh the sink inventory baseline

The tracked sink baseline had drifted against the current 1.2.x tree: many
source files changed line numbers (and a few redirect sinks) since it was last
regenerated, so the 'sink and architectural hotspot guard' failed for every PR
branched off current 1.2.x. Regenerate it with
tests/security/build_sink_inventory.sh. No new sinks are introduced by the Card
API (cards.js/cards.css are not PHP and add no tracked sinks); this is a
line-number/ordering resync of pre-existing entries.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(ui): harden the CactiCards controller per review feedback

- dragReference: resolve the pointer row before comparing horizontal
  centres so dragging over a later card no longer snaps the insertion
  point to the start of the row
- replaceCard: re-resolve the target by card id when the captured node
  was already swapped out, so overlapping refresh/resize responses no
  longer throw on a detached node (and resize still saves layout)
- normalizeState: sync the documented data-expandable/data-expanded
  attributes with the .ccCardExpandable/.ccCardExpanded classes used for
  CSS clipping and serialize(), bridging the cards.css selector mismatch
- dragstart: only enter reorder mode when the card itself is the armed
  drag source, ignoring native drags bubbling from body links/images
- dragend: disarm card.draggable on every drag end since native DnD
  suppresses the mouseup cleanup path

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* feature: add shared card-widget chart primitives to the Card API

Extend the Card API with a small, JS-free chart-primitive library so any plugin
- including third-party panels surfaced inside another plugin such as Intropage
- can draw rich card bodies with no plugin-specific stylesheet or JavaScript:

- include/css/card-widgets.css: the themeable .cc* primitives (semicircular
  gauge, usage/distribution bars, min/avg/max bullet, stacked proportion bar,
  stat tiles), coloured from currentColor and the shared --cc-sev-* properties.
  Loaded by the common page header alongside cards.css.
- lib/html.php: card_gauge(), card_bar(), card_bullet(), card_stackbar() and
  card_stat() render helpers (plus card_severity()) that emit exactly that
  markup. Available wherever global.php is loaded (web and poller).

These consolidate the near-identical gauge/bullet/bar/stack widgets currently
duplicated across the hmib, apcupsd and mactrack dashboards.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: TheWitness <copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix typo in comment about DOM behaviour

* fix(ci): number and reorder CHANGELOG entries and inventory cards.js

- Move the two Card API feature entries into the 1.3.0-dev feature block and
  number them (#8683) so .github/scripts/check-changelog.py accepts them
  (security->issue->feature ordering, traceable PR number).
- Register include/js/cards.js in build/legacy-js.json applicationFiles so the
  JavaScript contracts library inventory recognises the new core script.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* test(cards): cover the card helper CSS and PHP for the changed-line gates

- Add Playwright coverage fixtures to develop-theme-correctness.spec.ts that
  render every selector in include/css/cards.css and include/css/card-widgets.css
  (triggering the handle/tool hover and active states), so the develop theme
  correctness changed-CSS-line gate reaches 100 percent.
- Add tests/fixtures/Core/CardWidgetMarkup.php, a changed-line coverage probe
  that loads card_severity/card_gauge/card_bar/card_stat/card_stackbar/card_bullet
  in isolation and exercises every branch; register it in run_pr_change_tests.sh.
- Assign-then-return in card_gauge/card_stat/card_bullet (matching card_bar and
  card_stackbar) so Xdebug attributes the return to a covered line; no output
  change.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(cards): harden refresh/resize ordering, async remove, and toggle focus

Address review feedback on the CactiCards controller:

- Share a per-card-id request generation between refreshCard and resizeCard
  (startRequest/requestSuperseded) and discard a superseded response before
  replacing markup, so a slow refresh can no longer revert a newer grow/shrink.
- Await onRemoveCard: only drop the live card and persist the layout once the
  host Promise fulfils, leaving the card and saved layout intact on rejection
  (and re-resolving the node by id before removal).
- Transfer keyboard focus to the revealed counterpart when expand/collapse is
  activated from the keyboard, since cards.css hides the activated button.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* feature(ui): add gauge ticks, bullet avg marker and pill severities to card-widgets

Extend the shared Card API chart-widget library with .ccGaugeTick (gauge
min/max ticks), .ccBulletAvgMarker (a dashed historical-average marker on the
min/avg/max bullet) and .ccPill--up/--warn/--down/--none (status-pill severity
colours), all themed from the existing --cc-sev-* custom properties. This lets
converging plugin dashboards draw their richer card bodies from the shared .cc*
contract. Mirrors the 1.2.x change in #8684.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(cards): skip adding a card id already on the grid

Converge the controller: 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 present to avoid appending a duplicate the
server then dedupes. Brings the develop controller to the shared baseline that
the 1.2.x PR and every plugin bundle now carry.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Darken Card API severity pills to meet WCAG 4.5:1 contrast

The .ccPill--up/--warn/--down fallback backgrounds rendered 11px text at
3.51:1 (warn) to below the 4.5:1 WCAG AA threshold, and .ccPill--none used
currentColor as a background that resolved to white (invisible on light
themes). Mix each severity hue 70% with black for >=4.5:1 contrast with the
white label, and give --none a translucent currentColor wash that inherits
the theme foreground. Render the severity pill variants in the theme-
correctness fixture so the changed .cc* rules satisfy the CSS-line gate.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Preserve live card expand/collapse state across a Card API refresh

replaceCard() now carries the live card's current expand/collapse state onto the
fresh markup at swap time, so expanding or collapsing a card while its refresh
(or resize) response is in flight is no longer reverted. Applies to the per-card
refresh, resize and the plugins' Refresh-all paths, which all swap through
replaceCard(). Adds an e2e test that drives the controller through a refresh
landing mid-toggle, covering the changed line.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Only preserve a live card toggle when the user changed it mid-refresh

Mirror the 1.2.x review fix (#8700): replaceCard() carries the live expand/
collapse state onto fresh markup only when the user toggled during the request
(live differs from the state captured when the request started) and the fresh
card is still expandable; direct callers with no captured state keep host markup
authoritative (normalizeState contract). refreshCard() passes its captured
state; resizeCard() captures it before onResize(). Adds a second e2e case
asserting refreshed markup drives expansion when the user did not toggle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: TheWitness <copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-11 11:46:03 -05:00

495 lines
17 KiB
JavaScript

/*
+-------------------------------------------------------------------------+
| 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<outerHTML string>; },
* onLayoutChange:function(state) { ... persist {order, cards} ... },
* onAddCard: function(id) { return Promise<outerHTML string>; },
* 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
};
})();