diff --git a/CHANGELOG.md b/CHANGELOG.md index dbace7b1..9af3c98d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ --- develop --- * issue#471: Do not return a phantom empty row when tailing newline-terminated log files; return no rows for empty files +* dev: Relocate the shared dashboard card chrome to the standard `js/cards.js` + `css/cards.css` plugin asset paths (from `includes/cards/`) and move the plugin's `intropage.js` to `js/intropage.js`, so all JavaScript lives under `js/`, every plugin that adopts the card interface uses an identical file layout, and the bundle 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#466: Tolerate a small overshoot over 100% in the busiest Used Space panels so DSSTATS averaging artifacts (e.g. used reading 100.004% of total) no longer log a false "Problem with DSSTAT data" warning; only a meaningful overshoot (over 110%) now warns * issue: Size panel charts correctly on reload without waiting for a window resize. A panel's chart is drawn by an inline bb.generate() script that a strict Content-Security-Policy can run asynchronously, after reload_panel()'s resizeCharts() has already run; resizeCharts() was then a no-op and the chart kept its generated size until an unrelated window resize snapped it back. reload_panel() now watches the panel with a one-shot MutationObserver (and a wall-clock deadline) and resizes only that chart once it has actually rendered, and line/bar charts are sized from the server-rendered markup (configured height, container-fitted width) like pie and treemap instead of a fixed 100x150 @@ -37,7 +39,7 @@ * issue#440: Give Cacti theme severity indicators contrasting colors for dark details titlebars and light table rows * issue: Fix the dashboard page not scrolling with the mouse wheel over chart panels: charts were sized from the whole card (header included) and overflowed the card body, turning it into a nested scroller that captured the wheel; charts now keep their server-sized height (which also stops pie/treemap charts growing on every window resize) and card bodies no longer scroll vertically * issue: Keep long Panel Details content inside the dialog and scrollable, instead of spilling under the Close button pane, on themes (e.g. deepness) that force `.ui-dialog-content` to `overflow: visible`; the dialog height is also capped to the viewport -* issue: Render dashboard panels with a shared, self-contained card chrome (bundled `includes/cards/cards.css` + `cards.js`, no cross-plugin dependency): a left-hand drag handle and unified per-card tools (grow/shrink height, maximize, reload, remove), replacing jQuery UI Sortable with a keyboard-accessible drag; growing/shrinking a panel now resizes it immediately before the persist+reload round-trip +* issue: Render dashboard panels with a shared, self-contained card chrome (bundled `css/cards.css` + `js/cards.js`, no cross-plugin dependency): a left-hand drag handle and unified per-card tools (grow/shrink height, maximize, reload, remove), replacing jQuery UI Sortable with a keyboard-accessible drag; growing/shrinking a panel now resizes it immediately before the persist+reload round-trip * issue: Show the panel "Reload Panel" glyph as a refresh icon (fa-sync-alt) that spins while the panel reloads, instead of the retweet glyph * issue: Tune the panel titlebar severity palette per theme so green (good), orange (warning) and red (bad) read as those colors but with theme-appropriate tone and legible text on every theme (replaces the garish/olive green, pure `yellow` and black-on-mid-green text that were copied across all themes); deepness already had this treatment and is unchanged * issue: Keep the toolbar `Actions`/`Timespan`/`Panels` select2 menus on-screen by shifting the open dropdown left when it would overflow the right edge of the viewport (select2 only flips vertically, and Cacti core's `dropdownAutoWidth` widens the dropdown past the narrow control) diff --git a/includes/cards/cards.css b/css/cards.css similarity index 100% rename from includes/cards/cards.css rename to css/cards.css diff --git a/display.php b/display.php index 123bbc0e..d4812b3b 100644 --- a/display.php +++ b/display.php @@ -572,8 +572,12 @@ function display_information(): bool { = 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 ref; + 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. */ - function replaceCard(grid, adapter, card, html) { + /* 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; } - card.parentNode.replaceChild(fresh, card); + // 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); @@ -114,6 +203,22 @@ window.CactiCards = window.CactiCards || (function() { return fresh; } + /* A per-card-id request generation shared by refresh and resize so a slow + * response cannot overwrite the markup of a newer request for the same card + * (for example a refresh that lands after a later grow). The most recently + * started request for an id wins; earlier in-flight responses are discarded. */ + function startRequest(grid, id) { + if (!grid.__ccReq) { + grid.__ccReq = {}; + } + grid.__ccReq[id] = (grid.__ccReq[id] || 0) + 1; + return grid.__ccReq[id]; + } + + function requestSuperseded(grid, id, token) { + return !!grid.__ccReq && grid.__ccReq[id] !== token; + } + function refreshCard(grid, adapter, card) { var id = cardId(card, adapter); // Hosts that inject into an inner body (rather than replacing the whole @@ -127,38 +232,73 @@ window.CactiCards = window.CactiCards || (function() { } var state = { expanded: card.classList.contains('ccCardExpanded'), - height: parseInt(card.getAttribute('data-height') || '1', 10) + height: Number.parseInt(card.getAttribute('data-height') || '1', 10) }; + var token = startRequest(grid, id); Promise.resolve(adapter.fetchCard(id, state)).then(function(html) { - if (html != null) { - replaceCard(grid, adapter, card, 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') { - adapter.onRemoveCard(id, card); + Promise.resolve(adapter.onRemoveCard(id, card)).then(commit).catch(function() { + /* rejected: leave the card and its saved layout untouched */ + }); + } else { + commit(); } - card.parentNode.removeChild(card); - saveLayout(grid, adapter); } function resizeCard(grid, adapter, card, dir) { var id = cardId(card, adapter); if (typeof adapter.onResize === 'function') { + var token = startRequest(grid, id); + 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); + 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. */ @@ -168,6 +308,8 @@ window.CactiCards = window.CactiCards || (function() { } card.__ccBound = true; + normalizeState(card); + var onHandle = function(target) { return target && target.closest && target.closest('.ccDrag'); }; @@ -216,11 +358,24 @@ window.CactiCards = window.CactiCards || (function() { saveLayout(grid, adapter); }); - card.addEventListener('dragstart', function() { + 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); @@ -274,11 +429,13 @@ window.CactiCards = window.CactiCards || (function() { case 'expand': card.classList.add('ccCardExpanded'); card.setAttribute('data-expanded', '1'); + refocusToolCounterpart(card, tool, 'collapse'); saveLayout(grid, adapter); break; case 'collapse': card.classList.remove('ccCardExpanded'); card.setAttribute('data-expanded', '0'); + refocusToolCounterpart(card, tool, 'expand'); saveLayout(grid, adapter); break; case 'grow': resizeCard(grid, adapter, card, 'grow'); break; @@ -310,7 +467,11 @@ window.CactiCards = window.CactiCards || (function() { var tmp = document.createElement('div'); tmp.innerHTML = String(html).trim(); var fresh = tmp.querySelector(cardSel(adapter)) || tmp.firstElementChild; - if (fresh) { + // A second add of the same card can resolve while the first + // is still pending (the option stays selectable until the + // debounced catalogue sync), so skip ids already on the grid + // to avoid appending a duplicate the server then dedupes. + if (fresh && findCard(grid, adapter, cardId(fresh, adapter)) === null) { grid.appendChild(fresh); bindCard(grid, adapter, fresh); if (typeof adapter.applyTheme === 'function') { @@ -318,7 +479,7 @@ window.CactiCards = window.CactiCards || (function() { } saveLayout(grid, adapter); } - }); + }).catch(function() { /* fire-and-forget: the host surfaces adapter errors */ }); } }); } diff --git a/js/index.php b/js/index.php new file mode 100644 index 00000000..828ecbeb --- /dev/null +++ b/js/index.php @@ -0,0 +1,25 @@ +not->toContain('a-theme-that-does-not-exist.css'); }); + +it('bundles the plugin card stylesheet when core does not ship one', function () { + $base = sys_get_temp_dir() . '/intropage-core-' . uniqid('', true); + mkdir($base, 0777, true); + + $previous = $GLOBALS['config']['base_path']; + $GLOBALS['config']['base_path'] = $base; + + try { + ob_start(); + intropage_page_head(); + $output = ob_get_clean(); + } finally { + $GLOBALS['config']['base_path'] = $previous; + rmdir($base); + } + + expect($output)->toContain('plugins/intropage/css/cards.css'); +}); + +it('does not bundle the plugin card stylesheet when core already ships one', function () { + $base = sys_get_temp_dir() . '/intropage-core-' . uniqid('', true); + mkdir($base . '/include/css', 0777, true); + file_put_contents($base . '/include/css/cards.css', '/* core copy */'); + + $previous = $GLOBALS['config']['base_path']; + $GLOBALS['config']['base_path'] = $base; + + try { + ob_start(); + intropage_page_head(); + $output = ob_get_clean(); + } finally { + $GLOBALS['config']['base_path'] = $previous; + unlink($base . '/include/css/cards.css'); + rmdir($base . '/include/css'); + rmdir($base . '/include'); + rmdir($base); + } + + expect($output)->not->toContain('plugins/intropage/css/cards.css'); +}); diff --git a/tests/Unit/IntropagePanelReloadButtonTest.php b/tests/Unit/IntropagePanelReloadButtonTest.php index 051be174..9207cb06 100644 --- a/tests/Unit/IntropagePanelReloadButtonTest.php +++ b/tests/Unit/IntropagePanelReloadButtonTest.php @@ -10,7 +10,7 @@ /* * Unit coverage for intropage_panel_reload_button() in includes/functions.php: * a force-enabled panel header must render the fa-sync-alt reload glyph, which - * includes/intropage.js spins while a reload is in flight. + * js/intropage.js spins while a reload is in flight. */ require_once __DIR__ . '/../../includes/functions.php'; diff --git a/tests/bin/patch-coverage.php b/tests/bin/patch-coverage.php index 2acdaef9..9fdee5cc 100644 --- a/tests/bin/patch-coverage.php +++ b/tests/bin/patch-coverage.php @@ -168,6 +168,10 @@ function changed_lines($base_ref) { // isolated unit process. 'display.php', 'poller_intropage.php', + // Directory-index redirect stub (header('Location:...') + top-level + // execution); added with the new js/ asset directory and not reachable from + // the isolated unit process. Matches the other per-directory index.php stubs. + 'js/index.php', ]; $unmeasured = array_values(array_diff(array_keys($changed), array_keys($measured))); $unexpected_unmeasured = array_values(array_diff($unmeasured, $unmeasured_allowlist)); diff --git a/tests/e2e/cacti-theme.spec.cjs b/tests/e2e/cacti-theme.spec.cjs index 4cad4c93..a98db9e2 100644 --- a/tests/e2e/cacti-theme.spec.cjs +++ b/tests/e2e/cacti-theme.spec.cjs @@ -64,7 +64,7 @@ for (const { theme, palette } of themes) { await page.setContent(readFileSync(resolve(root, 'tests/fixtures/Ui/cacti-theme.html'), 'utf8').replaceAll('Cacti theme', `${theme[0].toUpperCase() + theme.slice(1)} theme`)); await preparePalette(page, palette); if (['sunrise', 'paper-plane'].includes(theme)) await page.locator('h1').evaluate(element => element.style.color = 'lightgrey'); - for (const file of [resolve(core, `include/themes/${theme}/jquery-ui.css`), resolve(core, `include/themes/${theme}/main.css`), resolve(core, 'include/fa/css/all.css'), resolve(root, 'includes/cards/cards.css'), resolve(root, 'css/common.css'), resolve(root, `css/${theme}.css`)]) { + for (const file of [resolve(core, `include/themes/${theme}/jquery-ui.css`), resolve(core, `include/themes/${theme}/main.css`), resolve(core, 'include/fa/css/all.css'), resolve(root, 'css/cards.css'), resolve(root, 'css/common.css'), resolve(root, `css/${theme}.css`)]) { await installCss(page, file); } if (palette) await expect(page.locator('body')).toHaveCSS('opacity', '1'); diff --git a/tests/e2e/chart-resize.spec.cjs b/tests/e2e/chart-resize.spec.cjs index ed927e44..7f8e24dc 100644 --- a/tests/e2e/chart-resize.spec.cjs +++ b/tests/e2e/chart-resize.spec.cjs @@ -7,10 +7,10 @@ const { readFileSync } = require('node:fs'); const root = resolve(__dirname, '../..'); const core = process.env.CACTI_ROOT || resolve(root, '../..'); -/* Load the real resize helpers from includes/intropage.js without running its +/* Load the real resize helpers from js/intropage.js without running its * jQuery ready block (the only top-level statement in the file), which would * call initPage() and the rest of the dashboard bootstrap. */ -const intropageSource = readFileSync(resolve(root, 'includes/intropage.js'), 'utf8') +const intropageSource = readFileSync(resolve(root, 'js/intropage.js'), 'utf8') .replace(/\$\(function\(\) \{[\s\S]*?\n\}\);/, '/* ready block removed for the isolated helper test */'); test('a chart that renders after reload_panel still gets resized to its container', async ({ page }) => {