feature: modern filter bar polish (Rows/Refresh on bar, dialog button labels, separators) (#8191)

* fix: label modern dialog apply/clear with the page button text; show Rows on the bar

The dialog apply button was hardcoded 'Search', which mismatched the page's submit label (e.g. 'Go') and collided with pages that have a filter field named Search (clog). It now uses the configured go/clear button display text. Also route the 'rows' field to the modern bar alongside timespan/refresh so the per-page Rows selector stays visible.

* feature: always label the row-count selector 'Rows'

emit_field() forces the 'rows' field friendly_name to Rows regardless of page-specific naming (Devices, Trees, ...), in both legacy and modern filters. Refresh already renders on the modern bar via field_is_bar.

* feature: order modern bar selectors (Rows, Refresh) and separate them from the buttons

Rows renders first and Refresh second on the modern filter bar, and a vertical separator now divides the selectors (Layouts, Rows, Refresh) from the layout action buttons.

* changelog: 8191.feature fragment for modern filter bar polish

* jQuery 4: replace removed $.isFunction in bundled plugins

jQuery 4.0 removed $.isFunction. contextMenu, colorpicker and timepicker are hand-vendored orphans fixed in place; tablesorter is npm-managed, so it is also rewritten at sync time in build/sync-js.mjs so a rebuild reproduces the fix (no-ops once the upstream fix is released and the pin is bumped).

* Render the Thumbnails and Business Hours graph filter checkboxes as Cacti toggles

* fix: address review — update modern JS docblock and strengthen bar/label tests

Rewrite the create_modern_javascript docblock to describe the page-configured apply/clear labels (and document the change/clear callback params). Extend FilterLayoutsTest to assert the selector|button separator, the applied Rows-then-Refresh ordering, and both go/clear label lookups, and that the hardcoded Search dialog label is gone.

* Filter bar polish: toggle-style filter checkboxes and flicker-free layout buttons

Render the shared filter_checkbox field as a Cacti toggle switch (.checkboxSwitch/.checkboxSlider) so every page's filter checkboxes match the rest of the UI, and start the layout Rename/Delete/Save As buttons hidden so layoutUpdateButtons() reveals them only when applicable instead of flashing visible on load.

* Modern filter: move the timespan selector onto its own second filter line

Timespan controls were rendered inline on the single modern filter bar. Route method=timespan fields into a separate group and emit them as a second filterTable row so the bar isn't overcrowded, matching the legacy multi-row layout. Applies to every modern filter with a timespan (the graph view pages).

* Modern filter: keep toggle checkboxes on the bar with a visible label and tooltip

filter_checkbox fields now count as bar fields so the Thumbnails/Business Hours toggles sit on the single bar instead of the Edit dialog. Their label used .checkboxLabel (display:none by design for forms), which hid the text; switch to .checkboxLabelWanted and always set a title tooltip from the field's title/friendly_name so each toggle is self-describing.

* Modern filter: toggles back in the dialog, restrict auto-apply to bar fields, drop dialog Clear

- Move filter_checkbox toggles back into the Edit dialog (field_is_bar no longer claims them) and render them as a form row: friendly name in the label column, toggle in the value column.
- In modern mode only bar selectors (Rows, Refresh) and the Layout selector auto-trigger a filter change; dialog field changes/clicks no longer call applyFilter (gate changeChain/clickChain on !use_modern_filter() || field_is_bar). Legacy keeps auto-applying on change (text inputs still excluded).
- Remove the Clear button from the modern Edit dialog and the now-unused clearLabel; update the dialog-labels test accordingly.

* Fix filter toggle vertical alignment across themes

The generic .filterTable .filterColumn label { vertical-align: -10% } nudge (meant for text labels) out-specified .checkboxSwitch and dragged the toggle switch down, which also pulled the adjacent label baseline low in the Edit dialog and misaligned the toggle on the legacy filter bar. Add a higher-specificity label.checkboxSwitch { vertical-align: middle } in every theme carrying the rule (midwinter has no such rule).

* Hide the filter search glyph in the modern Edit dialog

Theme main.js appends a ti-search glyph after #rfilter, positioned for a table cell; in the modern Edit dialog #rfilter sits in a wide div (no td), so the glyph wraps below the field. Skip the injection when #rfilter is inside .cactiFilterEditTable (modern dialog); legacy, which has no such ancestor, keeps the glyph.

* jQuery 4: full removed-API sweep of bundled plugins

Replace every jQuery-4-removed helper across the vendored plugins: \$.trim -> String.prototype.trim, \$.isArray -> Array.isArray, \$.proxy -> Function.prototype.bind, \$.parseJSON -> JSON.parse, \$.type -> typeof/\$.isPlainObject, \$.isWindow -> native window check (plus the earlier \$.isFunction). Orphans (colorpicker, timepicker, multiselect, multiselect.filter, tableDnD) are fixed in place; the npm-managed tablesorter core+widgets are rewritten at sync time in build/sync-js.mjs so a rebuild reproduces the fix.

* Modern filter dialog: non-modal, Apply gated on save, Save keeps dialog open

- Rename the dialog apply action to Apply and disable it until the (new or changed) filter is saved (layoutDirty tracking); Close just closes without applying.
- Save no longer reloads the page: it reflects the saved layout in the selector and re-enables Apply, keeping the dialog open.
- Dialogs are now modal: false.
- Switch the layout selector change from a full document.location reload to an AJAX loadUrl().
- Vertically center the modern bar cells so the barSep separator lines up between the buttons.

* Modern filter: add layout to the filter's session variable structure

Register layout (FILTER_VALIDATE_INT, default 0) in sanitize_filter_variables() alongside page so the selected layout is validated and stored in the filter's session object and persists across page views.

* Modern filter: Graph Template amalgam on line 2, timespan on line 3

Tag the Graph Template + Source/Order/CF/Measure group ('bar' => true on graph_template_id and the html_graph_order_filter_array() metrics) so create_modern_filter renders it as its own second filter line on Graph View and Tree View, pushing the timespan to the third line. These bar fields also auto-trigger the filter so the Template->Source->Order callback chain works on the main bar.

* Fix graph_template_id multi-select: allow comma lists, type get_host_graph_list correctly

get_host_graph_list() immediately transforms graph_template_id via html_transform_graph_template_ids() (handles cg_/dq_ prefixes and comma lists), so its parameter is a string, not an int -- correct the type hint and docblock. Also widen the preview and listview graph_template_id validation regexp to accept a comma-separated list like 'cg_118,cg_106,cg_119', matching the tree filter.

* Modern filter: hide the whole cell for hidden layout buttons to even out bar separator spacing

The Rename/Delete/Save As buttons hid only the <button>, leaving their table-cell (with padding) in the bar, so the separator after them was pushed away from Edit. Put the display:none on the .filterColumnButton cell and toggle the cell in layoutUpdateButtons so hidden buttons take no space and the separators sit evenly between the visible buttons.

* Remove legacy .drop-callback/makeCallbacks() autocomplete widget

The Device dropdown and other form_callback() lookups now always use the
ajax-backed select2 selectmenu. Drop the old makeCallbacks() jQuery-UI
autocomplete entirely and have form_callback() render the select2-callback
<select> by default, keeping the plain full-list <select> only when the
'autocomplete' config option is enabled.

* Carry selected layout through the modern dialog Apply action

The layout_save callback already returns the new layout id (and url), and
layoutDialogSave() selects it in #filter_layout. The dialog Apply button,
however, ran the plain filter apply (applyFilter()) which rebuilds the URL
from the field values and omits filter_layout, so the page reloaded as
(New Filter). Apply now navigates to the selected layout's data-url (which
includes filter_layout=<id>) when a layout is selected, falling back to the
normal filter apply when none is.

* Fix Filter Layouts manage page table and use jQuery UI dialogs for delete/rename

The management table was opened with html_start_box(\ = true), emitting a
<div> instead of a <table>, so the header and rows rendered unstyled and
run-together. Switch it to table mode.

Replace the generic confirm()-based delete with a CDEF-style jQuery UI
confirmation dialog loaded over ajax, and add a Rename action that opens a
matching jQuery UI dialog with a name field. Both post to the existing
layout_delete/layout_rename handlers on confirm.

* Use jQuery UI dialogs for filter-bar layout rename/delete; drop rename from manage page

The filter bar (modern and legacy) was still using native prompt()/confirm()
for the layout Rename and Delete actions - convert both to jQuery UI dialogs
(a name-entry dialog for rename, a confirm dialog for delete).

On the Filter Layouts management page, remove the rename action entirely and
instead link the layout name to its page (with filter_layout set) as an edit
link; keep the Delete confirmation dialog and Publish action.

* Rework Layouts manage page: preset filter bar + actions dropdown; rename to Layouts

Model layouts.php on the preset pages (CDEFs, etc.): add the standard
CactiTableFilter search bar in the legacy look, a sortable list with a
checkbox column, a pager, and a draw_actions_dropdown with Delete, Make
Global (publish), and Make Local (reassign to the current user). The
unimpressive per-row action icons and ajax dialogs are replaced by the
checkbox/confirmation flow. Make Global/Make Local are admin-only.

Treat layouts.php as a filter_layouts preset page so its own filter bar
does not offer the layout dropdown. Rename the page title and Console
Presets menu entry from 'Filters'/'Filter Layouts' to 'Layouts'.

* Show friendly page name in the Layouts list Page column

Map the stored page basename to the Console navigation title (e.g. host.php
=> Devices) via a layouts_page_name() lookup against \, falling
back to the raw basename. The Page column is now nosort since the displayed
label no longer matches the sortable database value.

* Fix filter search TypeError: use filter_options key in default search field

sanitize_filter_variables() reads a field's callback options from the
'filter_options' key, but the default search field in create_default() stored
them under 'options', so the key never reached validate_store_request_vars().
That left FILTER_CALLBACK with no callback and raised 'filter_var(): Option
must be a valid callback' whenever a table filter was searched.

* Address PR scan findings: tablesorter useless conditional + layouts SQL

- jquery.tablesorter.js: drop the redundant 'str &&' guard inside the
  already-truthy 'str ?' branch of the digit and currency parsers (CodeQL
  useless-conditional). Add a matching sync-js transform rule so a rebuild
  from upstream keeps the simplification.
- layouts.php: fully parameterize the management list queries with bound
  '?' parameters for the search term and user id, and build the LIMIT from
  explicit (int) page/rows, so no request variable reaches the SQL string
  (Semgrep cacti-request-var-in-sql).

* Address PR review: colorpicker trim, tablesorter JSON guard, bar separator, i18n

- jquery.colorpicker.js: _setAltField() iterated index <= properties.length, so
  the last pass read properties[undefined]; \$.trim(undefined) was '' but native
  .trim() throws. Iterate with < so no TypeError.
- jquery.tablesorter.widgets.js: the retrieveValue feature-check still tested the
  removed \$.parseJSON; under jQuery 4 it was always falsy so saved widget state
  never loaded. Test native window.JSON.parse instead, and add a matching
  build/sync-js.mjs transform rule so a rebuild keeps the guard.
- html_filter.php: the Layouts selector is always rendered, so emit the
  selector-to-button separator unconditionally (graph preview routes fields to
  the amalgam/timespan lines, leaving the bar line without it before).
- changelog/i18n: reword 8191.feature to describe the Apply (save-gated) dialog
  action, and add the new layouts.php/html_filter.php msgids to cacti.pot.

* Add tablesorter transform coverage to the sync-js test

Feed a fixture containing every removed jQuery 4 utility (\$.isFunction,
\$.trim, \$.type ===string/object, \$.isWindow, \$.isArray, \$.parseJSON calls
and the bare if (\$.parseJSON) guard) plus the CodeQL str && simplification
through syncAssets, and assert the synced tablesorter output contains the
native equivalents and none of the removed APIs. Previously the transform ran
against a generic stub, so an incomplete rewrite could pass unnoticed.

* Apply php-cs-fixer: comment style, alignment, and single-quote strings

Run through the project php-cs-fixer config (the mandatory pre-PR check):
line comments for the input-validation banners, aligned assignment, and
single-quoted strings where no interpolation is used. No behaviour change.

* Render the filter Go action as a refresh glyph button (modern + legacy)

Replace the 'Go' text submit with a compact 'ti ti-refresh' glyph button
titled 'Refresh page' for every page filter:
- emit_field() forces the glyph/title on any 'go' submit, so both the shared
  default and pages that define their own 'go' get it on the legacy filter.
- The modern bar (which has no form) gets a JS-wired #layout_refresh glyph
  button right of Edit that loadUrl()s the selected layout url (carrying
  filter_layout) or the page change callback.
Add the 'Refresh page' msgid to cacti.pot and note it in 8191.feature.

* Add a Tabler .icon-rotate spin class and use it for refreshing icons

Tabler ships only the icon webfont, with no fa-spin equivalent, so spinning
reload icons stopped animating (e.g. the Troubleshooting > Data Sources
auto-refresh indicator). Define .icon-rotate in every theme (reusing the
globally loaded fa-spin keyframes) and apply it:
- the modern filter refresh button spins while it loads,
- the realtime graph drill-down loader switches from fa-spin to icon-rotate,
- the data_debug auto-refresh indicators spin again.

* tests: sync FilterLayouts assertions with the reworded separator comment and dw.addClass

The source scan expected the old 'Separate the selectors' comment and a chained
.dialog('widget').addClass() form; update to the current reworded comment and
the 'var dw' + dw.addClass('cactiFilterDialog') the dialog now uses.

* Glyph-ify the timespan Refresh/Clear and the generic Clear action

Replace the timespan 'Refresh' text button with a spinning ti ti-refresh glyph
and 'Clear' with a ti ti-eraser glyph (also fixing a stray double </span>), and
make the generic filter Clear a ti ti-eraser glyph button across legacy and
modern via emit_field (button case now honours a 'glyph' key). The timespan
refresh icon spins (icon-rotate) while it reloads.

* Glyph-ify filter Import/Export, layout, and modern-bar action buttons

Force ti-table-import / ti-table-export glyphs for any filter button named import/export (centralized in emit_field like go/clear), so page-defined Import/Export buttons and the modern bar's always-visible action strip render consistent Tabler glyphs. Add a glyph parameter to layout_button() and glyph the Edit/Rename/Delete/Save As/Save/New/Publish buttons across the modern bar and legacy layouts row.

* Use table-import/table-export glyphs for cactiTableButton Import/Export icons

The filter header Export/Import icons injected into cactiTableButton used generic chevron-down/chevron-up glyphs; switch them to ti ti-table-export / ti ti-table-import to match the rest of the glyph theme.

* Glyph-ify the Save Filter Defaults button on the filter bar

The has_save 'Save' action rendered as a text button on the modern bar (and legacy filter); force a ti ti-device-floppy glyph via emit_field like go/clear/import/export so it matches the rest of the glyph theme.

* Regenerate tree-view graphs when applying a saved filter layout

The modern layout selector loaded a layout's saved data-url (action=tree) directly, so on the Graph Tree view it pulled the tree shell instead of regenerating graphs. Route the layout-url loads (selector change, refresh button, and dialog Apply) through correctUrlParameters() so action=tree becomes action=tree_content and graphs reload into #main, matching applyGraphFilter(). No-op on non-tree pages.

* Keep timespan controls working after ajax reloads and tip custom date fields

On the Graph Preview page the predefined_timespan change and tsrefresh/tsclear/shift click handlers were bound directly inside the filter's inline ready script, so an ajax content reload that replaced the timespan controls dropped the bindings (a full page refresh restored them). Bind them with namespaced event delegation on document so they survive content replacement and never double-bind. Add tooltips to the custom start/end date inputs telling the user to click Refresh to apply the range, plus POT entries and a changelog note.

* Record layouts.php static redirect in the sink inventory baseline

The sink and architectural hotspot guard flagged inventory drift: layouts.php's static header('Location: layouts.php') redirect (no request input) was never added to the tracked baseline. Refresh the baseline via tests/security/build_sink_inventory.sh to record it.

* Fix layout Save-As dialog state and use cacti_redirect in layouts.php

Address review findings: (1) use cacti_redirect('layouts.php') instead of a raw header()+exit so the standard redirect checks run (and drop the now-unneeded sink-inventory entry); (2) reset the dialog's force-new flag after the first successful save so later saves update the created layout instead of creating duplicates; (3) preserve an existing dirty state when reopening the Edit dialog so pending edits are not silently discarded by Apply.

* Drop stale layout msgids from the translation template

Remove the Filter Layouts, Published to all users, Publish to all users, and No Filter Layouts Found msgids that this PR replaced (now Layouts, Make Global, Make Local, No Layouts Found); all four are absent from PHP. Keeps the surgically-maintained POT in sync with the shipped strings.

---------

Co-authored-by: TheWitness <TheWitness@users.noreply.github.com>
This commit is contained in:
TheWitnessandTheWitness authored and GitHub committed 2026-10-06 11:35:13 -04:00
1 parent 135d31e406
commit 2a44c7a791
43 files changed
+975 -522

No files matched your search

+21
View File
@@ -5,6 +5,8 @@
// patches/tablesorter+2.32.0.patch) before this runs. screenfull ships ESM-only
// since v6, so its copy is rewritten below (see postCopyTransforms) instead of
// via patch-package, since node_modules/screenfull/index.js is itself valid.
// tablesorter is also rewritten below to drop jQuery-4-incompatible utility
// calls ($.isFunction, $.trim, $.isArray, ...) that its latest release still ships.
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -37,6 +39,23 @@ export const assetMap = Object.freeze({
// when loaded as a classic <script>. Rewrite that line to a global assignment.
// Throws if the export line isn't found, so an upstream format change fails the
// build instead of silently shipping a broken asset.
// tablesorter 2.32.0 (latest release) still calls several jQuery utilities that
// jQuery 4 removed ($.isFunction, $.trim, $.isArray, $.type, $.isWindow,
// $.parseJSON); rewrite them natively at sync time for both the core and widgets
// files. No-ops once the upstream fixes are released and the pin is bumped.
const tablesorterJquery4 = content => content
.replace(/\$\.isFunction\(\s*([^()]+?)\s*\)/g, "typeof $1 === 'function'")
.replace(/\$\.trim\(((?:[^()]|\([^()]*\))*)\)/g, '($1).trim()')
.replace(/\$\.type\(\s*([^()]+?)\s*\)\s*===\s*'string'/g, "typeof $1 === 'string'")
.replace(/\$\.type\(\s*([^()]+?)\s*\)\s*===\s*'object'/g, '$$.isPlainObject($1)')
.replace(/\$\.isWindow\(\s*([^()]+?)\s*\)/g, '($1 != null && $1 === $1.window)')
.replace(/\$\.isArray\(/g, 'Array.isArray(')
.replace(/\$\.parseJSON\(/g, 'JSON.parse(')
// the bare `if ($.parseJSON)` feature-check references an API jQuery 4 removed; test native JSON.parse
.replace(/if \(\$\.parseJSON\)/g, 'if (window.JSON && window.JSON.parse)')
// drop the redundant `str &&` guard inside the already-truthy `str ?` branch that CodeQL flags
.replace(/\( str && table\.config\.ignoreCase \?/g, '( table.config.ignoreCase ?');
const postCopyTransforms = Object.freeze({
'include/js/screenfull.js': content => {
const transformed = content.replace(/\nexport default screenfull;\s*$/, '\nwindow.screenfull = screenfull;\n');
@@ -47,6 +66,8 @@ const postCopyTransforms = Object.freeze({
return transformed;
},
'include/js/jquery.tablesorter.js': tablesorterJquery4,
'include/js/jquery.tablesorter.widgets.js': tablesorterJquery4,
});
export function syncAssets(root = process.cwd(), log = console.log) {
+1
View File
@@ -0,0 +1 @@
Polish the modern page filter bar: show the Rows and Refresh selectors on the bar (Rows first, Refresh second), always label the row-count selector Rows, always separate the selectors from the layout buttons, give the Edit dialog an Apply action that stays disabled until the layout is saved, and render the Go/Refresh and Clear actions as compact glyph buttons (a spinning refresh icon and an eraser) across the modern bar, the legacy filters, and the timespan controls; glyph the Import/Export, Save and layout buttons, regenerate tree-view graphs when applying a saved layout, keep the timespan controls responsive after ajax reloads, and tip the custom date fields to press Refresh to apply the range
+1
View File
@@ -0,0 +1 @@
Complete the jQuery 4 compatibility sweep of the bundled contextMenu, colorpicker, timepicker, tablesorter, multiselect and tableDnD plugins by replacing all removed helpers ($.isFunction, $.trim, $.isArray, $.proxy, $.type, $.isWindow, $.parseJSON)
+2 -2
View File
@@ -764,9 +764,9 @@ function debug_view() : void {
$debug_status = debug_process_status($id);
if ($debug_status == 'waiting') {
html_start_box(__('Data Source Troubleshooter [ Auto Refreshing till Complete ] %s', '<i class="reloadquery ti ti-refresh" data-id="' . $id . '" title="' . __esc('Refresh Now') . '"></i>'), '100%', false, 3, 'center', '');
html_start_box(__('Data Source Troubleshooter [ Auto Refreshing till Complete ] %s', '<i class="reloadquery ti ti-refresh icon-rotate" data-id="' . $id . '" title="' . __esc('Refresh Now') . '"></i>'), '100%', false, 3, 'center', '');
} elseif ($debug_status == 'analysis') {
html_start_box(__('Data Source Troubleshooter [ Auto Refreshing till RRDfile Update ] %s', '<i class="reloadquery ti ti-refresh" data-id="' . $id . '" title="' . __esc('Refresh Now') . '"></i>'), '100%', false, 3, 'center', '');
html_start_box(__('Data Source Troubleshooter [ Auto Refreshing till RRDfile Update ] %s', '<i class="reloadquery ti ti-refresh icon-rotate" data-id="' . $id . '" title="' . __esc('Refresh Now') . '"></i>'), '100%', false, 3, 'center', '');
} else {
html_start_box(__('Data Source Troubleshooter [ Analysis Complete! %s ]', '<a href="#" class="rerun linkEditMain" data-id="' . $id . '" style="cursor:pointer;">' . __('Rerun Analysis') . '</a>'), '100%', false, 3, 'center', '');
}
+2 -2
View File
@@ -1122,7 +1122,7 @@ if (POLLER_ID || $config['connection'] == 'online') { // @phpstan-ignore-line
'vdef.php' => __('VDEFs'),
'color.php' => __('Colors'),
'gprint_presets.php' => __('GPRINTs'),
'layouts.php' => __('Filters'),
'layouts.php' => __('Layouts'),
],
__('Import/Export') => [
'package_import.php' => __('Import Packages'),
@@ -2309,7 +2309,7 @@ $navigation = [
'level' => '2'
],
'layouts.php:' => [
'title' => __('Filter Layouts'),
'title' => __('Layouts'),
'mapping' => 'index.php:',
'url' => 'layouts.php',
'level' => '1'
+7 -7
View File
@@ -414,7 +414,7 @@
}
}
, 'NAME': function(color, that) {
var c = that._getSwatch($.trim(color));
var c = that._getSwatch((color).trim());
if (c) {
return new $.colorpicker.Color(c.r, c.g, c.b);
}
@@ -2553,8 +2553,8 @@
property,
properties = this.options.altProperties.split(',');
for (index = 0; index <= properties.length; ++index) {
property = $.trim(properties[index]);
for (index = 0; index < properties.length; ++index) {
property = (properties[index]).trim();
switch (property) {
case 'color':
case 'fill':
@@ -2751,7 +2751,7 @@
: (that.options.showAnim === 'fadeIn' ?
fade
: show))]((that.options.showAnim ? that.options.duration : null), callback);
if ($.isFunction(callback) && (!that.options.showAnim || !that.options.duration)) {
if (typeof callback === 'function' && (!that.options.showAnim || !that.options.duration)) {
callback();
}
}
@@ -3061,7 +3061,7 @@
var currentSwatches = this._getSwatches(),
name;
$.each(currentSwatches, function (nameOrIndex, swatch) {
name = $.isArray(currentSwatches) ? swatch.name : nameOrIndex;
name = Array.isArray(currentSwatches) ? swatch.name : nameOrIndex;
return callback(name, swatch);
});
},
@@ -3168,7 +3168,7 @@
var that = this,
color;
var formats = $.isArray(that.options.colorFormat)
var formats = Array.isArray(that.options.colorFormat)
? that.options.colorFormat
: [ that.options.colorFormat ];
@@ -3244,7 +3244,7 @@
},
channels = color.getChannels();
if (!$.isArray(formats)) {
if (!Array.isArray(formats)) {
formats = [formats];
}
+8 -8
View File
@@ -885,10 +885,10 @@
e.preventDefault();
e.stopImmediatePropagation();
if ($.isFunction(opt.callbacks[key]) && Object.prototype.hasOwnProperty.call(opt.callbacks, key)) {
if (typeof opt.callbacks[key] === 'function' && Object.prototype.hasOwnProperty.call(opt.callbacks, key)) {
// item-specific callback
callback = opt.callbacks[key];
} else if ($.isFunction(root.callback)) {
} else if (typeof root.callback === 'function') {
// default callback
callback = root.callback;
} else {
@@ -1214,7 +1214,7 @@
k.commands[key] = item;
// Overwrite only if undefined or the item is appended to the root. This so it
// doesn't overwrite callbacks of root elements if the name is the same.
if ($.isFunction(item.callback) && (typeof k.callbacks[key] === 'undefined' || typeof opt.type === 'undefined')) {
if (typeof item.callback === 'function' && (typeof k.callbacks[key] === 'undefined' || typeof opt.type === 'undefined')) {
k.callbacks[key] = item.callback;
}
});
@@ -1315,7 +1315,7 @@
k.commands[key] = item;
// Overwrite only if undefined or the item is appended to the root. This so it
// doesn't overwrite callbacks of root elements if the name is the same.
if ($.isFunction(item.callback) && (typeof k.callbacks[key] === 'undefined' || typeof opt.type === 'undefined')) {
if (typeof item.callback === 'function' && (typeof k.callbacks[key] === 'undefined' || typeof opt.type === 'undefined')) {
k.callbacks[key] = item.callback;
}
});
@@ -1336,7 +1336,7 @@
// add icons
if (item.icon) {
if ($.isFunction(item.icon)) {
if (typeof item.icon === 'function') {
item._icon = item.icon.call(this, this, $t, key, item);
} else {
if (typeof(item.icon) === 'string' && (
@@ -1435,9 +1435,9 @@
var $item = $(this),
key = $item.data('contextMenuKey'),
item = opt.items[key],
disabled = ($.isFunction(item.disabled) && item.disabled.call($trigger, key, root)) || item.disabled === true,
disabled = (typeof item.disabled === 'function' && item.disabled.call($trigger, key, root)) || item.disabled === true,
visible;
if ($.isFunction(item.visible)) {
if (typeof item.visible === 'function') {
visible = item.visible.call($trigger, key, root);
} else if (typeof item.visible !== 'undefined') {
visible = item.visible === true;
@@ -1454,7 +1454,7 @@
// dis- / enable item
$item[disabled ? 'addClass' : 'removeClass'](root.classNames.disabled);
if ($.isFunction(item.icon)) {
if (typeof item.icon === 'function') {
$item.removeClass(item._icon);
var iconResult = item.icon.call(this, $trigger, $item, key, item);
if(typeof(iconResult) === "string"){
+3 -3
View File
@@ -107,7 +107,7 @@
this._bindInputEvents();
// automatically reset the widget on close?
if (this.options.autoReset) {
$element.on('multiselectbeforeclose', $.proxy(this._reset, this));
$element.on('multiselectbeforeclose', this._reset.bind(this));
}
var $label = $(document.createElement('label')).text(opts.label).append(this.$input).addClass('ui-multiselect-filter-label');
@@ -172,8 +172,8 @@
}
}
},
input: $.proxy(debounce(this._handler, this.options.debounceMS), this),
search: $.proxy(this._handler, this),
input: debounce(this._handler, this.options.debounceMS).bind(this),
search: this._handler.bind(this),
});
},
+2 -2
View File
@@ -738,7 +738,7 @@
$button
.on({
click: buttonClickHandler,
keydown: $.proxy(self._handleButtonKeyboardNav, self),
keydown: self._handleButtonKeyboardNav.bind(self),
mouseenter: function() {
if (!this.classList.contains('ui-state-disabled')) {
this.classList.add('ui-state-hover');
@@ -993,7 +993,7 @@
// setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
// http://bugs.jquery.com/ticket/3827
setTimeout($.proxy(self.update, self), 10);
setTimeout(self.update.bind(self), 10);
});
},
+3 -3
View File
@@ -564,7 +564,7 @@ jQuery.tableDnD = {
}
currentLevel = indentLevel;
if (!$.isArray(data[currentID]))
if (!Array.isArray(data[currentID]))
data[currentID] = [];
rowID = getSerializeRegexp(rows[i].id);
rowID && data[currentID].push(rowID);
@@ -582,9 +582,9 @@ jQuery.fn.extend(
{
tableDnD : $.tableDnD.build,
tableDnDUpdate : $.tableDnD.updateTables,
tableDnDSerialize : $.proxy($.tableDnD.serialize, $.tableDnD),
tableDnDSerialize : $.tableDnD.serialize.bind($.tableDnD),
tableDnDSerializeAll : $.tableDnD.serializeTables,
tableDnDData : $.proxy($.tableDnD.tableData, $.tableDnD)
tableDnDData : $.tableDnD.tableData.bind($.tableDnD)
}
);
+20 -20
View File
@@ -414,7 +414,7 @@
.bind( 'appendCache' + namespace, function( e, callback, init ) {
e.stopPropagation();
ts.appendCache( this.config, init );
if ( $.isFunction( callback ) ) {
if ( typeof callback === 'function' ) {
callback( this );
}
})
@@ -830,18 +830,18 @@
// check data-attribute first when set to 'basic'; don't use node.innerText - it's really slow!
// http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/
if ( extract === 'basic' && typeof ( tmp = $node.attr( c.textAttribute ) ) !== 'undefined' ) {
return $.trim( tmp );
return ( tmp ).trim();
}
return $.trim( node.textContent || $node.text() );
return ( node.textContent || $node.text() ).trim();
} else {
if ( typeof extract === 'function' ) {
return $.trim( extract( $node[ 0 ], c.table, cellIndex ) );
return ( extract( $node[ 0 ], c.table, cellIndex ) ).trim();
} else if ( typeof ( tmp = ts.getColumnData( c.table, extract, cellIndex ) ) === 'function' ) {
return $.trim( tmp( $node[ 0 ], c.table, cellIndex ) );
return ( tmp( $node[ 0 ], c.table, cellIndex ) ).trim();
}
}
// fallback
return $.trim( $node[ 0 ].textContent || $node.text() );
return ( $node[ 0 ].textContent || $node.text() ).trim();
},
// centralized function to extract/parse cell contents
@@ -1027,7 +1027,7 @@
console[ console.table ? 'table' : 'log' ]( val );
if ( console.groupEnd ) { console.groupEnd(); }
}
if ( $.isFunction( callback ) ) {
if ( typeof callback === 'function' ) {
callback( table );
}
},
@@ -1190,7 +1190,7 @@
tmp = $header.hasClass( ts.css.sortAsc ) ?
'sortAsc' :
$header.hasClass( ts.css.sortDesc ) ? 'sortDesc' : 'sortNone',
txt = $.trim( $header.text() ) + ': ' + ts.language[ tmp ];
txt = ( $header.text() ).trim() + ': ' + ts.language[ tmp ];
if ( $header.hasClass( 'sorter-false' ) || nextSort === false ) {
txt += ts.language.sortDisabled;
} else {
@@ -1651,7 +1651,7 @@
// save sort before applying sortAppend
c.last.sortList = $.extend( [], c.sortList );
if ( c.sortList.length && c.sortAppend ) {
arry = $.isArray( c.sortAppend ) ? c.sortAppend : c.sortAppend[ c.sortList[ 0 ][ 0 ] ];
arry = Array.isArray( c.sortAppend ) ? c.sortAppend : c.sortAppend[ c.sortList[ 0 ][ 0 ] ];
if ( !ts.isEmptyObject( arry ) ) {
for ( indx = 0; indx < arry.length; indx++ ) {
if ( arry[ indx ][ 0 ] !== col && ts.isValueInArray( arry[ indx ][ 0 ], c.sortList ) < 0 ) {
@@ -1781,13 +1781,13 @@
if ( c.table.isUpdating ) {
c.$table.triggerHandler( 'updateComplete', c.table );
}
if ( $.isFunction( callback ) ) {
if ( typeof callback === 'function' ) {
callback( c.table );
}
},
checkResort : function( c, resort, callback ) {
var sortList = $.isArray( resort ) ? resort : c.sortList,
var sortList = Array.isArray( resort ) ? resort : c.sortList,
// if no resort parameter is passed, fallback to config.resort (true by default)
resrt = typeof resort === 'undefined' ? c.resort : resort;
// don't try to resort if the table is still processing
@@ -1831,7 +1831,7 @@
c.$table.triggerHandler( 'sortBeforeEnd', table );
c.$table.triggerHandler( 'sortEnd', table );
ts.applyWidget( table );
if ( $.isFunction( callback ) ) {
if ( typeof callback === 'function' ) {
callback( table );
}
},
@@ -1846,7 +1846,7 @@
ts.setHeadersCss( c );
ts.multisort( c );
ts.appendCache( c );
if ( $.isFunction( callback ) ) {
if ( typeof callback === 'function' ) {
callback( c.table );
}
},
@@ -2156,7 +2156,7 @@
} else {
// name can be either an array of widgets names,
// or a space/comma separated list of widget names
name = ( $.isArray( name ) ? name.join( ',' ) : name || '' ).toLowerCase().split( /[\s,]+/ );
name = ( Array.isArray( name ) ? name.join( ',' ) : name || '' ).toLowerCase().split( /[\s,]+/ );
}
len = name.length;
for ( index = 0; index < len; index++ ) {
@@ -2268,7 +2268,7 @@
}
num = parseFloat( str );
// return the text instead of zero
return isNaN( num ) ? $.trim( str ) : num;
return isNaN( num ) ? ( str ).trim() : num;
},
isDigit : function( str ) {
@@ -2409,7 +2409,7 @@
// include sorter class name 'sorter-text', etc; now works with 'sorter-my-custom-parser'
val = cl4ss.match( new RegExp( '\\s' + key + '-([\\w-]+)' ) )[ 1 ] || '';
}
return $.trim( val );
return ( val ).trim();
},
getColumnData : function( table, obj, indx, getCell, $headers ) {
@@ -2672,7 +2672,7 @@
format : function( str, table ) {
var c = table.config;
if ( str ) {
str = $.trim( c.ignoreCase ? str.toLocaleLowerCase() : str );
str = ( c.ignoreCase ? str.toLocaleLowerCase() : str ).trim();
str = c.sortLocaleCompare ? ts.replaceAccents( str ) : str;
}
return str;
@@ -2689,7 +2689,7 @@
format : function( str, table ) {
var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
return str && typeof num === 'number' ? num :
str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
str ? ( table.config.ignoreCase ? str.toLocaleLowerCase() : str ).trim() : str;
},
type : 'numeric'
});
@@ -2706,7 +2706,7 @@
format : function( str, table ) {
var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
return str && typeof num === 'number' ? num :
str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
str ? ( table.config.ignoreCase ? str.toLocaleLowerCase() : str ).trim() : str;
},
type : 'numeric'
});
@@ -2721,7 +2721,7 @@
return ts.regex.urlProtocolTest.test( str );
},
format : function( str ) {
return str ? $.trim( str.replace( ts.regex.urlProtocolReplace, '' ) ) : str;
return str ? ( str.replace( ts.regex.urlProtocolReplace, '' ) ).trim() : str;
},
type : 'text'
});
+108 -108
View File
@@ -84,15 +84,15 @@
console.log('Storage >> Using', hasStorage ? storageType : 'cookies');
}
// *** get value ***
if ($.parseJSON) {
if (window.JSON && window.JSON.parse) {
if (hasStorage) {
values = $.parseJSON( window[storageType][key] || 'null' ) || {};
values = JSON.parse( window[storageType][key] || 'null' ) || {};
} else {
// old browser, using cookies
cookies = document.cookie.split(/[;\s|=]/);
// add one to get from the key to the value
cookieIndex = $.inArray(key, cookies) + 1;
values = (cookieIndex !== 0) ? $.parseJSON(cookies[cookieIndex] || 'null') || {} : {};
values = (cookieIndex !== 0) ? JSON.parse(cookies[cookieIndex] || 'null') || {} : {};
}
}
// allow value to be an empty string too
@@ -181,8 +181,8 @@
$headers = c.$headers.add( $( c.namespace + '_extra_headers' ) ),
theme = c.theme || 'jui',
themes = themesAll[theme] || {},
remove = $.trim( [ themes.sortNone, themes.sortDesc, themes.sortAsc, themes.active ].join( ' ' ) ),
iconRmv = $.trim( [ themes.iconSortNone, themes.iconSortDesc, themes.iconSortAsc ].join( ' ' ) ),
remove = ( [ themes.sortNone, themes.sortDesc, themes.sortAsc, themes.active ].join( ' ' ) ).trim(),
iconRmv = ( [ themes.iconSortNone, themes.iconSortDesc, themes.iconSortAsc ].join( ' ' ) ).trim(),
debug = ts.debug(c, 'uitheme');
if (debug) { time = new Date(); }
// initialization code - run once
@@ -193,8 +193,8 @@
oldremove = hasOldTheme ? [ oldtheme.sortNone, oldtheme.sortDesc, oldtheme.sortAsc, oldtheme.active ].join( ' ' ) : '';
oldIconRmv = hasOldTheme ? [ oldtheme.iconSortNone, oldtheme.iconSortDesc, oldtheme.iconSortAsc ].join( ' ' ) : '';
if (hasOldTheme) {
wo.zebra[0] = $.trim( ' ' + wo.zebra[0].replace(' ' + oldtheme.even, '') );
wo.zebra[1] = $.trim( ' ' + wo.zebra[1].replace(' ' + oldtheme.odd, '') );
wo.zebra[0] = ( ' ' + wo.zebra[0].replace(' ' + oldtheme.even, '') ).trim();
wo.zebra[1] = ( ' ' + wo.zebra[1].replace(' ' + oldtheme.odd, '') ).trim();
c.$tbodies.children().removeClass( [ oldtheme.even, oldtheme.odd ].join(' ') );
}
// update zebra stripes
@@ -314,84 +314,84 @@
})(jQuery);
/*! Widget: columns - updated 5/24/2017 (v2.28.11) */
;(function ($) {
'use strict';
var ts = $.tablesorter || {};
ts.addWidget({
id: 'columns',
priority: 65,
options : {
columns : [ 'primary', 'secondary', 'tertiary' ]
},
format: function(table, c, wo) {
var $tbody, tbodyIndex, $rows, rows, $row, $cells, remove, indx,
$table = c.$table,
$tbodies = c.$tbodies,
sortList = c.sortList,
len = sortList.length,
// removed c.widgetColumns support
css = wo && wo.columns || [ 'primary', 'secondary', 'tertiary' ],
last = css.length - 1;
remove = css.join(' ');
// check if there is a sort (on initialization there may not be one)
for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
$tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // detach tbody
$rows = $tbody.children('tr');
// loop through the visible rows
$rows.each(function() {
$row = $(this);
if (this.style.display !== 'none') {
// remove all columns class names
$cells = $row.children().removeClass(remove);
// add appropriate column class names
if (sortList && sortList[0]) {
// primary sort column class
$cells.eq(sortList[0][0]).addClass(css[0]);
if (len > 1) {
for (indx = 1; indx < len; indx++) {
// secondary, tertiary, etc sort column classes
$cells.eq(sortList[indx][0]).addClass( css[indx] || css[last] );
}
}
}
}
});
ts.processTbody(table, $tbody, false);
}
// add classes to thead and tfoot
rows = wo.columns_thead !== false ? [ 'thead tr' ] : [];
if (wo.columns_tfoot !== false) {
rows.push('tfoot tr');
}
if (rows.length) {
$rows = $table.find( rows.join(',') ).children().removeClass(remove);
if (len) {
for (indx = 0; indx < len; indx++) {
// add primary. secondary, tertiary, etc sort column classes
$rows.filter('[data-column="' + sortList[indx][0] + '"]').addClass(css[indx] || css[last]);
}
}
}
},
remove: function(table, c, wo) {
var tbodyIndex, $tbody,
$tbodies = c.$tbodies,
remove = (wo.columns || [ 'primary', 'secondary', 'tertiary' ]).join(' ');
c.$headers.removeClass(remove);
c.$table.children('tfoot').children('tr').children('th, td').removeClass(remove);
for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
$tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // remove tbody
$tbody.children('tr').each(function() {
$(this).children().removeClass(remove);
});
ts.processTbody(table, $tbody, false); // restore tbody
}
}
});
})(jQuery);
/*! Widget: columns - updated 5/24/2017 (v2.28.11) */
;(function ($) {
'use strict';
var ts = $.tablesorter || {};
ts.addWidget({
id: 'columns',
priority: 65,
options : {
columns : [ 'primary', 'secondary', 'tertiary' ]
},
format: function(table, c, wo) {
var $tbody, tbodyIndex, $rows, rows, $row, $cells, remove, indx,
$table = c.$table,
$tbodies = c.$tbodies,
sortList = c.sortList,
len = sortList.length,
// removed c.widgetColumns support
css = wo && wo.columns || [ 'primary', 'secondary', 'tertiary' ],
last = css.length - 1;
remove = css.join(' ');
// check if there is a sort (on initialization there may not be one)
for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
$tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // detach tbody
$rows = $tbody.children('tr');
// loop through the visible rows
$rows.each(function() {
$row = $(this);
if (this.style.display !== 'none') {
// remove all columns class names
$cells = $row.children().removeClass(remove);
// add appropriate column class names
if (sortList && sortList[0]) {
// primary sort column class
$cells.eq(sortList[0][0]).addClass(css[0]);
if (len > 1) {
for (indx = 1; indx < len; indx++) {
// secondary, tertiary, etc sort column classes
$cells.eq(sortList[indx][0]).addClass( css[indx] || css[last] );
}
}
}
}
});
ts.processTbody(table, $tbody, false);
}
// add classes to thead and tfoot
rows = wo.columns_thead !== false ? [ 'thead tr' ] : [];
if (wo.columns_tfoot !== false) {
rows.push('tfoot tr');
}
if (rows.length) {
$rows = $table.find( rows.join(',') ).children().removeClass(remove);
if (len) {
for (indx = 0; indx < len; indx++) {
// add primary. secondary, tertiary, etc sort column classes
$rows.filter('[data-column="' + sortList[indx][0] + '"]').addClass(css[indx] || css[last]);
}
}
}
},
remove: function(table, c, wo) {
var tbodyIndex, $tbody,
$tbodies = c.$tbodies,
remove = (wo.columns || [ 'primary', 'secondary', 'tertiary' ]).join(' ');
c.$headers.removeClass(remove);
c.$table.children('tfoot').children('tr').children('th, td').removeClass(remove);
for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
$tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // remove tbody
$tbody.children('tr').each(function() {
$(this).children().removeClass(remove);
});
ts.processTbody(table, $tbody, false); // restore tbody
}
}
});
})(jQuery);
/*! Widget: filter - updated 2018-03-18 (v2.30.0) *//*
* Requires tablesorter v2.8+ and jQuery 1.7+
@@ -622,7 +622,7 @@
savedSearch = query;
// parse filter value in case we're comparing numbers ( dates )
if ( parsed || parser.type === 'numeric' ) {
txt = $.trim( '' + data.iFilter.replace( tsfRegex.operators, '' ) );
txt = ( '' + data.iFilter.replace( tsfRegex.operators, '' ) ).trim();
result = tsf.parseFilter( c, txt, data, true );
query = ( typeof result === 'number' && result !== '' && !isNaN( result ) ) ? result : query;
}
@@ -657,9 +657,9 @@
if ( tsfRegex.exact.test( filter ) ) {
// look for exact not matches - see #628
filter = filter.replace( tsfRegex.exact, '' );
return filter === '' ? true : $.trim( filter ) !== data.iExact;
return filter === '' ? true : ( filter ).trim() !== data.iExact;
} else {
indx = data.iExact.search( $.trim( filter ) );
indx = data.iExact.search( ( filter ).trim() );
return filter === '' ? true :
// return true if not found
data.anyMatch ? indx < 0 :
@@ -1068,7 +1068,7 @@
filters = ts.getFilters( table ) || [];
if ( wo.filter_saveFilters && ts.storage ) {
saved = ts.storage( table, 'tablesorter-filters' ) || [];
isArray = $.isArray( saved );
isArray = Array.isArray( saved );
// make sure we're not just getting an empty array
if ( !( isArray && saved.join( '' ) === '' || !isArray ) ) {
filters = tsf.processFilters( saved );
@@ -1100,7 +1100,7 @@
// c.columns defined in computeThIndexes()
cellFilter = wo.filter_cellFilter,
columns = c.columns,
arry = $.isArray( cellFilter ),
arry = Array.isArray( cellFilter ),
buildFilter = '<tr role="search" class="' + tscss.filterRow + ' ' + c.cssIgnoreRow + '">';
for ( column = 0; column < columns; column++ ) {
if ( c.$headerIndexed[ column ].length ) {
@@ -1166,7 +1166,7 @@
}
if ( buildFilter ) {
// add filter class name
name = ( $.isArray( wo.filter_cssFilter ) ?
name = ( Array.isArray( wo.filter_cssFilter ) ?
( typeof wo.filter_cssFilter[column] !== 'undefined' ? wo.filter_cssFilter[column] || '' : '' ) :
wo.filter_cssFilter ) || '';
// copy data-column from table cell (it will include colspan)
@@ -1180,7 +1180,7 @@
var regex = new RegExp(attr, 'g'),
data = $header.attr('data-' + attr.replace(/{{|}}/g, '')),
text = typeof data === 'undefined' ? $header.text() : data;
name = name.replace( regex, $.trim( text ) );
name = name.replace( regex, ( text ).trim() );
});
buildFilter.attr({
'data-column': $filter.attr( 'data-column' ),
@@ -1317,8 +1317,8 @@
f1 = [],
f2 = [],
len = c.columns + 1; // add one to include anyMatch filter
filter1 = $.isArray(filter1) ? filter1 : [];
filter2 = $.isArray(filter2) ? filter2 : [];
filter1 = Array.isArray(filter1) ? filter1 : [];
filter2 = Array.isArray(filter2) ? filter2 : [];
for (indx = 0; indx < len; indx++) {
f1[indx] = filter1[indx] || '';
f2[indx] = filter2[indx] || '';
@@ -1328,7 +1328,7 @@
checkFilters: function( table, filter, skipFirst ) {
var c = table.config,
wo = c.widgetOptions,
filterArray = $.isArray( filter ),
filterArray = Array.isArray( filter ),
filters = ( filterArray ) ? filter : ts.getFilters( table, true ),
currentFilters = filters || []; // current filter values
// prevent errors if delay init is set
@@ -1435,7 +1435,7 @@
if ( filter === '' ) { return filter; }
var regex = tsfRegex.iQuery,
maskLen = mask.match( tsfRegex.igQuery ).length,
query = maskLen > 1 ? $.trim( filter ).split( /\s/ ) : [ $.trim( filter ) ],
query = maskLen > 1 ? ( filter ).trim().split( /\s/ ) : [ ( filter ).trim() ],
len = query.length - 1,
indx = 0,
val = mask;
@@ -1526,7 +1526,7 @@
// only target 'all' column inputs on initialization
// & don't target 'all' column inputs if they don't exist
targets = wo.filter_initialized || !$input.filter( wo.filter_anyColumnSelector ).length,
val = $.trim( tsf.getLatestSearch( $input ).attr( 'data-column' ) || '' );
val = ( tsf.getLatestSearch( $input ).attr( 'data-column' ) || '' ).trim();
return tsf.findRange( c, val, !targets );
},
processTypes: function( c, data, vars ) {
@@ -1595,7 +1595,7 @@
txt = data.cacheArray[ i ];
} else {
txt = data.rawArray[ i ];
txt = $.trim( wo.filter_ignoreCase ? txt.toLowerCase() : txt );
txt = ( wo.filter_ignoreCase ? txt.toLowerCase() : txt ).trim();
if ( c.sortLocaleCompare ) {
txt = ts.replaceAccents( txt );
}
@@ -1996,12 +1996,12 @@
if ( fxn === true ) {
// OVERALL source
arry = source( table, column, onlyAvail );
} else if ( fxn instanceof $ || ( $.type( fxn ) === 'string' && fxn.indexOf( '</option>' ) >= 0 ) ) {
} else if ( fxn instanceof $ || ( typeof fxn === 'string' && fxn.indexOf( '</option>' ) >= 0 ) ) {
// selectSource is a jQuery object or string of options
return fxn;
} else if ( $.isArray( fxn ) ) {
} else if ( Array.isArray( fxn ) ) {
arry = fxn;
} else if ( $.type( source ) === 'object' && fxn ) {
} else if ( $.isPlainObject(source) && fxn ) {
// custom select source function for a SPECIFIC COLUMN
arry = fxn( table, column, onlyAvail );
// abort - updating the selects from an external method
@@ -2018,7 +2018,7 @@
},
processOptions: function( table, column, arry ) {
if ( !$.isArray( arry ) ) {
if ( !Array.isArray( arry ) ) {
return false;
}
table = $( table )[0];
@@ -2171,7 +2171,7 @@
}
}
if ( $.isArray( arry ) ) {
if ( Array.isArray( arry ) ) {
// build option list
for ( indx = 0; indx < arry.length; indx++ ) {
option = arry[ indx ];
@@ -2232,7 +2232,7 @@
// make sure there is a select there!
if ( $filter.length ) {
$filter[ updating ? 'html' : 'append' ]( options );
if ( !$.isArray( arry ) ) {
if ( !Array.isArray( arry ) ) {
// append options if arry is provided externally as a string or jQuery object
// options ( default value ) was already added
$filter.append( arry ).val( currentValue );
@@ -2269,7 +2269,7 @@
if ( ( getRaw !== true && wo && !wo.filter_columnFilters ) ||
// setFilters called, but last search is exactly the same as the current
// fixes issue #733 & #903 where calling update causes the input values to reset
( $.isArray(setFilters) && tsf.equalFilters(c, setFilters, c.lastSearch) )
( Array.isArray(setFilters) && tsf.equalFilters(c, setFilters, c.lastSearch) )
) {
return $( table ).data( 'lastSearch' ) || [];
}
@@ -2293,7 +2293,7 @@
if ( $column.length ) {
// move the latest search to the first slot in the array
$column = tsf.getLatestSearch( $column );
if ( $.isArray( setFilters ) ) {
if ( Array.isArray( setFilters ) ) {
// skip first ( latest input ) to maintain cursor position while typing
if ( skipFirst && $column.length > 1 ) {
$column = $column.slice( 1 );
@@ -2527,7 +2527,7 @@
var tmp,
offset = $table.offset(),
stickyOffset = getStickyOffset(c, wo),
yWindow = $.isWindow( $yScroll[0] ), // $.isWindow needs jQuery 1.4.3
yWindow = ($yScroll[0] != null && $yScroll[0] === $yScroll[0].window), // $.isWindow needs jQuery 1.4.3
yScroll = yWindow ?
$yScroll.scrollTop() :
// use parent sticky position if nested AND inside of a scrollable element - see #1512
@@ -3103,7 +3103,7 @@
function getStoredSortList(c) {
var stored = ts.storage( c.table, 'tablesorter-savesort' );
return (stored && stored.hasOwnProperty('sortList') && $.isArray(stored.sortList)) ? stored.sortList : [];
return (stored && stored.hasOwnProperty('sortList') && Array.isArray(stored.sortList)) ? stored.sortList : [];
}
function sortListChanged(c, sortList) {
+6 -6
View File
@@ -187,14 +187,14 @@
overrides = {
beforeShow: function (input, dp_inst) {
if ($.isFunction(tp_inst._defaults.evnts.beforeShow)) {
if (typeof tp_inst._defaults.evnts.beforeShow === 'function') {
return tp_inst._defaults.evnts.beforeShow.call($input[0], input, dp_inst, tp_inst);
}
},
onChangeMonthYear: function (year, month, dp_inst) {
// Update the time as well : this prevents the time from disappearing from the $input field.
// tp_inst._updateDateTime(dp_inst);
if ($.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)) {
if (typeof tp_inst._defaults.evnts.onChangeMonthYear === 'function') {
tp_inst._defaults.evnts.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst);
}
},
@@ -202,7 +202,7 @@
if (tp_inst.timeDefined === true && $input.val() !== '') {
tp_inst._updateDateTime(dp_inst);
}
if ($.isFunction(tp_inst._defaults.evnts.onClose)) {
if (typeof tp_inst._defaults.evnts.onClose === 'function') {
tp_inst._defaults.evnts.onClose.call($input[0], dateText, dp_inst, tp_inst);
}
}
@@ -315,7 +315,7 @@
* add our sliders to the calendar
*/
_addTimePicker: function (dp_inst) {
var currDT = $.trim((this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val());
var currDT = ((this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val()).trim();
this.timeDefined = this._parseTime(currDT);
this._limitMinMaxDateTime(dp_inst, false);
@@ -362,7 +362,7 @@
*/
_afterInject: function() {
var o = this.inst.settings;
if ($.isFunction(o.afterInject)) {
if (typeof o.afterInject === 'function') {
o.afterInject.call(this);
}
},
@@ -1077,7 +1077,7 @@
for (var i = min; i <= max; i += step) {
sel += '<option value="' + i + '"' + (i === val ? ' selected' : '') + '>';
if (unit === 'hour') {
sel += $.datepicker.formatTime($.trim(format.replace(/[^ht ]/ig, '')), {hour: i}, tp_inst._defaults);
sel += $.datepicker.formatTime((format.replace(/[^ht ]/ig, '')).trim(), {hour: i}, tp_inst._defaults);
}
else if (unit === 'millisec' || unit === 'microsec' || i >= 10) { sel += i; }
else {sel += '0' + i.toString(); }
+5 -168
View File
@@ -1037,12 +1037,11 @@ function applySkin() {
applySelectorVisibilityAndActions();
makeCallbacks();
setupObjectChange();
$('.helpPage').off('click').on('click', function (event) {
event.stopPropagation();
getCactiHelp($(this).attr('data-page'));
});
@@ -1336,8 +1335,7 @@ function applySkin() {
}
});
/* ajax-backed lookup select: replaces the legacy .drop-callback/makeCallbacks() autocomplete
* widget for filter fields opted into it (see form_callback()'s $class parameter) */
/* ajax-backed lookup select used by form_callback() lookup fields (see its $class parameter) */
$('select.select2-callback:not(.select2-hidden-accessible)').each(function() {
var $select = $(this);
var action = $select.data('action');
@@ -1800,7 +1798,7 @@ function makeFiltersResponsive() {
if (filterContents.find('#export').length) {
title = $('#export').attr('title');
filterHeader.find('div.cactiTableButton').append($('<span style="display:none;" class="cactiFilterExport"><i class="ti ti-chevron-down"></i></span>').attr('title', title));
filterHeader.find('div.cactiTableButton').append($('<span style="display:none;" class="cactiFilterExport"><i class="ti ti-table-export"></i></span>').attr('title', title));
$('.cactiFilterExport').off('click').on('click', function (event) {
event.stopPropagation();
@@ -1810,7 +1808,7 @@ function makeFiltersResponsive() {
if (filterContents.find('#import').length) {
title = $('#import').attr('title');
filterHeader.find('div.cactiTableButton').append($('<span style="display:none;" class="cactiFilterImport"><i class="ti ti-chevron-up"></i></span>').attr('title', title));
filterHeader.find('div.cactiTableButton').append($('<span style="display:none;" class="cactiFilterImport"><i class="ti ti-table-import"></i></span>').attr('title', title));
$('.cactiFilterImport').off('click').on('click', function (event) {
event.stopPropagation();
@@ -5080,7 +5078,7 @@ function initializeGraphs(disable_cache) {
setFilters();
} else {
keepRealtime[graph_id] = $('#wrapper_' + graph_id).html();
$(this).html("<i style='text-align:center;padding:0px;' title='" + realtimeClickOff + "' class='drillDown ti ti-loader-2 fa-spin'></i>");
$(this).html("<i style='text-align:center;padding:0px;' title='" + realtimeClickOff + "' class='drillDown ti ti-loader-2 icon-rotate'></i>");
$(this).find('i').tooltip();
realtimeArray[graph_id] = true;
setFilters();
@@ -5402,167 +5400,6 @@ $.widget('custom.dropcolor', {
}
});
function makeCallbacks() {
var cn = 0;
$('.drop-callback').each(function() {
var title = searchSelect;
var action = $(this).attr('data-action');
var value = $(this).attr('data-value');
var reqvars = $(this).attr('data-variables');
var Id = $(this).attr('id');
var dcId = '#' + Id;
var dcWrap = dcId + '_wrap';
var dcWrapId = Id + '_wrap';
var dcClickId = Id + '_click';
var dcInput = dcId + '_input';
var dcInputId = Id + '_input';
var dcDisable = $(dcId).hasClass('ui-state-disabled');
var dcInputFields = 'input' + dcId + '_input';
$(dcId).attr('data-callback-id', cn);
if ($(dcWrap).length) {
$(dcWrap).remove();
}
if (value == '') {
value = title;
}
var dialogForm = $('<span class="ui-selectmenu-button ui-selectmenu-button-closed ui-corner-all ui-button ui-widget">')
.attr('id', dcWrapId)
.toggleClass('ui-selectmenu-disabled ui-state-disabled', !!dcDisable);
dialogForm.append($('<span style="z-index:4" class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s">').attr('id', dcClickId));
dialogForm.append($('<span class="ui-select-text">').append($('<input type="text" class="ui-state-default ui-corner-all">').attr('id', dcInputId).val(value)));
$(this).after(dialogForm, document.createTextNode(' '));
$(this).hide();
$(dcInput).autocomplete({
source: function(request, response) {
var _action = pageName + '?action=' + action;
if (reqvars != '') {
var variables = reqvars.split(',');
$.each(variables, function(index, data) {
if ($('#'+data).length) {
_action += "&" + data + "=" + $('#'+data).val();
}
});
}
_action += '&term=' + request.term;
$.getJSON(_action, function(data) {
response(data);
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui) {
var callBack = $(dcId).attr('data-callback');
$(dcInput).val(ui.item.label);
if (ui.item.id) {
$(dcId).val(ui.item.id);
} else {
$(dcId).val(ui.item.value);
}
if (callBack != '') {
callBack = callBack.replace('(', '').replace(')', '');
executeFunctionByName(callBack, window);
}
},
open: function(event, ui) {
$('.ui-dialog').css('z-index', '20');
$(this).css('z-index', '5000');
},
close: function(event, ui) {
var cn = $(dcId).attr('data-callback-id');
callbackOpen[cn] = false;
clearTimeout(callbackTimer[cn]);
}
}).css('border', 'none').css('background-color', 'transparent');
$(dcWrap).on('dblclick', function() {
var cn = $(dcId).attr('data-callback-id');
callbackOpen[cn] = false;
clearTimeout(callbackTimer[cn]);
clearTimeout(callbackClickTimer[cn]);
$(dcInput).autocomplete('close').select();
}).on('click', function() {
var cn = $(dcId).attr('data-callback-id');
if (callbackOpen[cn]) {
$(dcInput).autocomplete('close');
clearTimeout(callbackTimer[cn]);
callbackOpen[cn] = false;
} else {
callbackClickTimer[cn] = setTimeout(function() {
var cn = $(dcId).attr('data-callback-id');
$(dcInput).autocomplete('search', '');
clearTimeout(callbackTimer[cn]);
callbackOpen[cn] = true;
}, 200);
}
$(dcInput).select();
}).on('mouseleave', function() {
var cn = $(dcId).attr('data-callback-id');
callbackTimer[cn] = setTimeout(function() { $(dcInput).autocomplete('close'); }, 800);
});
var width = $(dcInput).textBoxWidth();
if (width < 200) {
width = 200;
}
$(dcWrap).css('width', width+20);
$(dcInput).css('width', width);
$(dcWrap).find('.ui-select-text').css('width', width);
$('ul[id^="ui-id"]').on('mouseenter', function() {
var cn = $(dcId).attr('data-callback-id');
clearTimeout(callbackTimer[cn]);
}).on('mouseleave', function() {
var cn = $(dcId).attr('data-callback-id');
callbackTimer[cn] = setTimeout(function() {
$(dcInput).autocomplete('close');
}, 800);
});
$('ul[id^="ui-id"] > li').on('mouseenter', function() {
$(this).addClass('ui-state-hover');
}).on('mouseleave', function() {
$(this).removeClass('ui-state-hover');
});
$(dcWrap).on('mouseenter', function() {
$(this).addClass('ui-state-hover');
if ($('input#' + id + '_input').length) {
$('input#' + id + '_input').addClass('ui-state-hover');
}
}).on('mouseleave', function() {
$(this).removeClass('ui-state-hover');
$(dcInputFields).removeClass('ui-state-hover');
});
cn++;
});
}
function expandClipboardSection(section) {
var isVisible = section.is(':visible');
if (!isVisible) {
+14
View File
@@ -1256,6 +1256,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1268,6 +1272,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -38,7 +38,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1262,6 +1262,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1274,6 +1278,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -38,7 +38,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1447,6 +1447,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1459,6 +1463,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -39,7 +39,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1299,6 +1299,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1311,6 +1315,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -38,7 +38,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+5
View File
@@ -281,3 +281,8 @@ select.select2-multi-count.select2-hidden-accessible + .select2-container:not(.s
.jstree-default .jstree-closed:not(.jstree-loading) > .jstree-ocl::before { content: "\ea61"; }
.jstree-default .jstree-open:not(.jstree-loading) > .jstree-ocl::before { content: "\ea5f"; }
.jstree-default .jstree-leaf:not(.jstree-loading) > .jstree-ocl::before { content: ""; }
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
+1 -1
View File
@@ -797,7 +797,7 @@ function setupDefaultElements() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"] > i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"] > i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1470,6 +1470,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1482,6 +1486,16 @@ legend {
/* Modern page filter (page_filter_format = modern): the Layouts bar and the
jQuery UI Edit dialog (dialogClass cactiFilterDialog). */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -40,7 +40,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1454,6 +1454,10 @@ tr>td.textInfo.right {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1466,6 +1470,16 @@ tr>td.textInfo.right {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -34,7 +34,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1287,6 +1287,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1299,6 +1303,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -38,7 +38,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1274,6 +1274,10 @@ legend {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1286,6 +1290,16 @@ legend {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -38,7 +38,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+14
View File
@@ -1491,6 +1491,10 @@ table.cactiTable {
vertical-align: -10%;
}
.filterTable .filterColumn label.checkboxSwitch {
vertical-align: middle;
}
.filterTable .filterColumnButton {
display: table-cell;
padding: 5px 0px 5px 5px;
@@ -1503,6 +1507,16 @@ table.cactiTable {
/* Modern page filter dialog skin (page_filter_format = modern), scoped to the
cactiFilterDialog widget so other dialogs are unaffected. */
.cactiFilterModernBar .filterColumn,
.cactiFilterModernBar .filterColumnButton {
vertical-align: middle;
}
.icon-rotate {
display: inline-block;
animation: fa-spin 1.5s linear infinite;
}
.cactiFilterModernBar .barSep {
display: inline-block;
width: 1px;
+1 -1
View File
@@ -40,7 +40,7 @@ function themeReady() {
$('input[id="filterd"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchFilter).parent('td').css('white-space', 'nowrap');
}
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1) {
if ($('input[id="rfilter"]').length > 0 && $('input[id="rfilter"]').next('i[class="ti ti-search filter"]').length < 1 && $('input[id="rfilter"]').closest('.cactiFilterEditTable').length < 1) {
$('input[id="rfilter"]').after("<i class='ti ti-search filter'/>").attr('autocomplete', 'off').attr('placeholder', searchRFilter).parent('td').css('white-space', 'nowrap');
}
+211 -64
View File
@@ -29,9 +29,22 @@ require('./include/auth.php');
// invoked from include/auth.php before this point. Only the management view
// remains here.
$actions = [
1 => __('Delete'),
];
if (filter_layouts_can_manage_global()) {
$actions[2] = __('Make Global');
$actions[3] = __('Make Local');
}
set_default_action();
switch (get_nfilter_request_var('action')) {
case 'actions':
layouts_form_actions();
break;
default:
top_header();
@@ -43,107 +56,241 @@ switch (get_nfilter_request_var('action')) {
}
/**
* Render the filter-layout management page. Administrators holding the
* Settings/Utilities realm manage every user's layouts and may publish them
* globally; other users manage only their own saved layouts.
* Apply a bulk action (Delete, Make Global, Make Local) to the layouts selected
* on the management list, showing the standard confirmation first.
*
* @return void
*/
function layouts_form_actions() : void {
global $actions;
// ================= input validation =================
get_filter_request_var('drp_action', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^([a-zA-Z0-9_]+)$/']]);
// ====================================================
$user_id = isset($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0;
if (isset_request_var('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(get_nfilter_request_var('selected_items'));
if ($selected_items != false) {
$selected_items = array_values(array_map('intval', $selected_items));
switch (get_nfilter_request_var('drp_action')) {
case '1': // delete
foreach ($selected_items as $id) {
filter_layouts_delete($id);
}
break;
case '2': // make global (publish to all users)
foreach ($selected_items as $id) {
filter_layouts_publish($id);
}
break;
case '3': // make local to the current user
foreach ($selected_items as $id) {
filter_layouts_unpublish($id, $user_id);
}
break;
}
}
cacti_redirect('layouts.php');
}
$ilist = '';
$iarray = [];
foreach ($_POST as $var => $val) {
if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
// ==== input validation ====
input_validate_input_number($matches[1], 'chk[1]');
// ==========================
$ilist .= '<li>' . htmle(db_fetch_cell_prepared('SELECT name FROM user_layouts WHERE id = ?', [$matches[1]])) . '</li>';
$iarray[] = $matches[1];
}
}
$form_data = [
'general' => [
'page' => 'layouts.php',
'actions' => $actions,
'optvar' => 'drp_action',
'item_array' => $iarray,
'item_list' => $ilist
],
'options' => [
1 => [
'smessage' => __('Click \'Continue\' to Delete the following Layout.'),
'pmessage' => __('Click \'Continue\' to Delete the following Layouts.'),
'scont' => __('Delete Layout'),
'pcont' => __('Delete Layouts')
],
2 => [
'smessage' => __('Click \'Continue\' to make the following Layout Global to all users.'),
'pmessage' => __('Click \'Continue\' to make the following Layouts Global to all users.'),
'scont' => __('Make Layout Global'),
'pcont' => __('Make Layouts Global')
],
3 => [
'smessage' => __('Click \'Continue\' to make the following Layout Local to you.'),
'pmessage' => __('Click \'Continue\' to make the following Layouts Local to you.'),
'scont' => __('Make Layout Local'),
'pcont' => __('Make Layouts Local')
]
]
];
form_continue_confirmation($form_data);
}
/**
* Render the Layouts management list with the standard preset filter bar and a
* checkbox-driven actions dropdown. Administrators holding the Settings/Utilities
* realm manage every user's layouts; other users manage only their own.
*
* @return void
*/
function layouts_manage() : void {
global $actions;
$is_admin = filter_layouts_can_manage_global();
$user_id = isset($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0;
if ($is_admin) {
$layouts = db_fetch_assoc('SELECT ul.id, ul.user_id, ul.page, ul.name, ul.data, ua.username
FROM user_layouts AS ul
LEFT JOIN user_auth AS ua
ON ua.id = ul.user_id
ORDER BY ul.page, (ul.user_id = 0), ul.name');
} else {
$layouts = db_fetch_assoc_prepared('SELECT ul.id, ul.user_id, ul.page, ul.name, ul.data, ua.username
FROM user_layouts AS ul
LEFT JOIN user_auth AS ua
ON ua.id = ul.user_id
WHERE ul.user_id = ?
ORDER BY ul.page, ul.name', [$user_id]);
$pageFilter = new CactiTableFilter(__('Layouts'), 'layouts.php', 'form_layouts', 'sess_layouts');
$pageFilter->rows_label = __('Layouts');
$pageFilter->render();
$rows = (grv('rows') == '-1') ? read_config_option('num_rows_table') : grv('rows');
$rows = (int) $rows;
$page = (int) grv('page');
$sql_where = '';
$sql_params = [];
if (grv('filter') != '') {
$sql_where = 'WHERE ul.name LIKE ?';
$sql_params[] = '%' . grv('filter') . '%';
}
html_start_box(__('Filter Layouts'), '100%', true, 3, 'center', '');
if (!$is_admin) {
$sql_where .= ($sql_where != '' ? ' AND ' : 'WHERE ') . 'ul.user_id = ?';
$sql_params[] = $user_id;
}
$total_rows = db_fetch_cell_prepared("SELECT COUNT(*)
FROM user_layouts AS ul
$sql_where", $sql_params);
$sql_order = get_order_string();
$sql_limit = ' LIMIT ' . (($page - 1) * $rows) . ', ' . $rows;
$layouts = db_fetch_assoc_prepared("SELECT ul.id, ul.user_id, ul.page, ul.name, ul.data, ua.username
FROM user_layouts AS ul
LEFT JOIN user_auth AS ua
ON ua.id = ul.user_id
$sql_where
$sql_order
$sql_limit", $sql_params);
$nav = html_nav_bar('layouts.php?filter=' . grv('filter'), MAX_DISPLAY_PAGES, grv('page'), $rows, $total_rows, 5, __('Layouts'), 'page', 'main');
form_start('layouts.php', 'chk');
print $nav;
html_start_box('', '100%', false, 3, 'center', '');
$display_text = [
'name' => ['display' => __('Name')],
'page' => ['display' => __('Page')],
'owner' => ['display' => __('Owner')],
'url' => ['display' => __('Filter')],
'nosort' => ['display' => __('Actions'), 'align' => 'right'],
'name' => [
'display' => __('Name'),
'align' => 'left',
'sort' => 'ASC',
'tip' => __('The name of this Layout.')
],
'nosort' => [
'display' => __('Page'),
'align' => 'left',
'tip' => __('The page this Layout applies to.')
],
'nosort2' => [
'display' => __('Owner'),
'align' => 'left',
'tip' => __('The owner of this Layout, or Global when shared with all users.')
],
'nosort3' => [
'display' => __('Filter'),
'align' => 'left',
'tip' => __('The stored filter this Layout applies.')
]
];
html_header($display_text, 1);
html_header_sort_checkbox($display_text, grv('sort_column'), grv('sort_direction'), false);
if (cacti_sizeof($layouts)) {
foreach ($layouts as $layout) {
if ($layout['user_id'] == 0) {
$owner = '<em>' . __('Global') . '</em>';
$owner = __('Global');
} elseif (!empty($layout['username'])) {
$owner = html_escape($layout['username']);
} else {
$owner = __('User %d', $layout['user_id']);
}
form_alternate_row('line' . $layout['id'], true);
$document = filter_layouts_decode($layout['data']);
$summary = $document !== false ? filter_layouts_document_url($document) : '';
form_selectable_cell(filter_value($layout['name'], ''), $layout['id']);
form_selectable_cell(html_escape($layout['page']), $layout['id']);
form_selectable_cell($owner, $layout['id']);
form_selectable_cell(html_escape($summary), $layout['id']);
$actions = "<a class='pic layoutAction' href='#' data-action='layout_delete' data-id='" . $layout['id'] . "' title='" . __esc('Delete') . "'><i class='fa fa-times deviceDown'></i></a>";
if ($is_admin) {
if ($layout['user_id'] == 0) {
$actions = "<span title='" . __esc('Published to all users') . "'><i class='fa fa-globe'></i></span> " . $actions;
} else {
$actions = "<a class='pic layoutAction' href='#' data-action='layout_publish' data-id='" . $layout['id'] . "' title='" . __esc('Publish to all users') . "'><i class='fa fa-upload'></i></a> " . $actions;
}
if ($summary != '') {
$sep = (strpos($summary, '?') !== false) ? '&' : '?';
$edit_url = $summary . $sep . 'filter_layout=' . $layout['id'];
} else {
$edit_url = '';
}
form_selectable_cell($actions, $layout['id'], '', 'right');
form_alternate_row('line' . $layout['id'], true);
form_selectable_cell(filter_value($layout['name'], grv('filter'), $edit_url), $layout['id']);
form_selectable_cell(html_escape(layouts_page_name($layout['page'])), $layout['id']);
form_selectable_cell($owner, $layout['id']);
form_selectable_cell(html_escape($summary), $layout['id']);
form_checkbox_cell($layout['name'], $layout['id']);
form_end_row();
}
} else {
print "<tr class='tableRow'><td colspan='5'><em>" . __('No Filter Layouts Found') . '</em></td></tr>';
print "<tr class='tableRow odd'><td colspan='" . (cacti_sizeof($display_text) + 1) . "'><em>" . __('No Layouts Found') . '</em></td></tr>';
}
html_end_box(false);
?>
<script type='text/javascript'>
$(function() {
$('.layoutAction').click(function(event) {
event.preventDefault();
if (cacti_sizeof($layouts)) {
print $nav;
}
var action = $(this).attr('data-action');
var id = $(this).attr('data-id');
draw_actions_dropdown($actions);
if (action == 'layout_delete' && !confirm(<?php print json_encode(__('Delete the selected layout?')); ?>)) {
return;
}
form_end();
}
$.post('layouts.php', { action: action, id: id, __csrf_magic: csrfMagicToken }, function(result) {
if (result && result.ok) {
document.location.reload();
} else {
alert(<?php print json_encode(__('The layout operation failed.')); ?>);
}
}, 'json').fail(function() {
alert(<?php print json_encode(__('The layout operation failed.')); ?>);
});
});
});
</script>
<?php
/**
* Resolve a layout's stored page basename to the friendly name the user sees in
* the Console navigation (e.g. 'host.php' becomes 'Devices'), falling back to the
* raw basename when the page is not registered.
*
* @param string $page The stored page basename.
*
* @return string
*/
function layouts_page_name(string $page) : string {
global $navigation;
if (isset($navigation[$page . ':']['title']) && $navigation[$page . ':']['title'] != '') {
return $navigation[$page . ':']['title'];
}
return $page;
}
+16 -4
View File
@@ -2756,20 +2756,32 @@ function html_graph_order_filter_array() : array {
}
}
foreach (array_keys($return) as $return_key) {
$return[$return_key]['bar'] = true;
}
return $return;
}
function html_thumbnails_filter(string $callBack = 'applyGraphFilter') : string {
$output = "<input id='thumbnails' type='checkbox' onClick='$callBack()' " . (grv('thumbnails') == 'true' ? 'checked' : '') . '>';
$output .= "<label for='thumbnails'>" . __('Thumbnails') . '</label>';
$checked = (grv('thumbnails') == 'true' ? ' checked' : '');
$output = "<span class='nowrap'>";
$output .= "<label class='checkboxSwitch'><input class='formCheckbox' id='thumbnails' name='thumbnails' type='checkbox' onClick='$callBack()'$checked><span class='checkboxSlider checkboxRound'></span></label>";
$output .= "<label class='checkboxLabelWanted' for='thumbnails'>" . __('Thumbnails') . '</label>';
$output .= '</span>';
return $output;
}
function html_business_hours_filter(string $callBack = 'applyGraphFilter') : string {
if (read_config_option('business_hours_enable') == 'on') {
$output = "<input id='business_hours' type='checkbox' onClick='$callBack()' " . (grv('business_hours') == 'true' ? 'checked' : '') . '>';
$output .= "<label for='business_hours'>" . __('Business Hours') . '</label>';
$checked = (grv('business_hours') == 'true' ? ' checked' : '');
$output = "<span class='nowrap'>";
$output .= "<label class='checkboxSwitch'><input class='formCheckbox' id='business_hours' name='business_hours' type='checkbox' onClick='$callBack()'$checked><span class='checkboxSlider checkboxRound'></span></label>";
$output .= "<label class='checkboxLabelWanted' for='business_hours'>" . __('Business Hours') . '</label>';
$output .= '</span>';
return $output;
}
+210 -58
View File
@@ -137,7 +137,7 @@ class CactiTableFilter {
'method' => 'textbox',
'friendly_name' => __('Search'),
'filter' => FILTER_CALLBACK,
'options' => ['options' => 'sanitize_search_string'],
'filter_options' => ['options' => 'sanitize_search_string'],
'placeholder' => __('Enter a search term'),
'size' => '30',
'default' => '',
@@ -451,7 +451,7 @@ class CactiTableFilter {
* @return bool
*/
private function field_is_bar(string $field_name, array $field_array) : bool {
return ($field_array['method'] ?? '') === 'timespan' || $field_name === 'refresh';
return ($field_array['method'] ?? '') === 'timespan' || $field_name === 'refresh' || $field_name === 'rows';
}
/**
@@ -467,6 +467,41 @@ class CactiTableFilter {
private function emit_field(string $field_name, array $field_array) : string {
ob_start();
// The row-count selector is always labeled "Rows", regardless of any
// page-specific name (Devices, Trees, ...).
if ($field_name === 'rows' && isset($field_array['friendly_name'])) {
$field_array['friendly_name'] = __('Rows');
}
// Every page's Go submit action renders as a compact refresh glyph button.
if ($field_name === 'go' && ($field_array['method'] ?? '') === 'submit') {
$field_array['glyph'] = 'ti ti-refresh';
$field_array['title'] = __('Refresh page');
}
// The Clear action renders as a compact eraser glyph button across every filter.
if ($field_name === 'clear' && ($field_array['method'] ?? '') === 'button') {
$field_array['glyph'] = 'ti ti-eraser';
if (empty($field_array['title'])) {
$field_array['title'] = __('Clear');
}
}
// Import/Export actions render as table-import / table-export glyph buttons.
if ($field_name === 'import' && ($field_array['method'] ?? '') === 'button') {
$field_array['glyph'] = 'ti ti-table-import';
}
if ($field_name === 'export' && ($field_array['method'] ?? '') === 'button') {
$field_array['glyph'] = 'ti ti-table-export';
}
// The Save Filter Defaults action renders as a floppy glyph button.
if ($field_name === 'save' && ($field_array['method'] ?? '') === 'button') {
$field_array['glyph'] = 'ti ti-device-floppy';
}
if (isset($field_array['class'])) {
$class = ' ' . $field_array['class'];
} else {
@@ -496,7 +531,9 @@ class CactiTableFilter {
case 'button':
print '<div class="filterColumnButton">' . PHP_EOL;
if (isset($field_array['display'])) {
if (!empty($field_array['glyph'])) {
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="' . $field_name . '"' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '"><i class="' . $field_array['glyph'] . '"></i></button>';
} elseif (isset($field_array['display'])) {
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="' . $field_name . '"' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '"><span class="button-text">' . $field_array['display'] . '</span></button>';
} else {
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="' . $field_name . '"' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '"><i class="' . $field_array['class'] . '"></i></button>';
@@ -507,15 +544,15 @@ class CactiTableFilter {
break;
case 'submit':
print '<div class="filterColumnButton">' . PHP_EOL;
print '<button type="submit" class="ui-button ui-corner-all ui-widget ui-state-active ' . $class . '" id="' . $field_name . '" ' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '"><span class="button-text">' . $field_array['display'] . '</span></button>';
print '<button type="submit" class="ui-button ui-corner-all ui-widget ui-state-active ' . $class . '" id="' . $field_name . '" ' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '">' . (!empty($field_array['glyph']) ? '<i class="' . $field_array['glyph'] . '"></i>' : '<span class="button-text">' . $field_array['display'] . '</span>') . '</button>';
print '</div>' . PHP_EOL;
break;
case 'filter_checkbox':
print '<div class="filterColumn"><span>' . PHP_EOL;
print '<input type="checkbox" class="ui-button ui-corner-all ui-widget' . $class . '" id="' . $field_name . '"' . (isset($field_array['title']) ? ' title="' . $field_array['title'] : '') . '"' . ($field_array['value'] == 'on' || $field_array['value'] == 'true' ? ' checked' : '') . '>';
print '&nbsp;<label for="' . $field_name . '">' . $field_array['friendly_name'] . '</label>';
print '</span></div>' . PHP_EOL;
$cb_title = html_escape_attr($field_array['title'] ?? $field_array['friendly_name']);
print '<div class="filterColumn"><div class="filterFieldName">' . $field_array['friendly_name'] . '</div></div>' . PHP_EOL;
print '<div class="filterColumn"><label class="checkboxSwitch" title="' . $cb_title . '"><input type="checkbox" class="formCheckbox' . $class . '" id="' . $field_name . '" title="' . $cb_title . '"' . ($field_array['value'] == 'on' || $field_array['value'] == 'true' ? ' checked' : '') . '><span class="checkboxSlider checkboxRound"></span></label></div>' . PHP_EOL;
break;
case 'timespan':
@@ -543,7 +580,7 @@ class CactiTableFilter {
print '</div>';
print '<div class="filterColumn">';
print '<span>';
print '<input type="text" class="ui-state-default ui-corner-all' . $class . '" id="date1" size="18" value="' . ($_SESSION['sess_current_date1'] ?? '') . '">';
print '<input type="text" class="ui-state-default ui-corner-all' . $class . '" id="date1" size="18" title="' . __esc('Start of the custom time range. After setting the start and end dates, click the Refresh button to apply the time range.') . '" value="' . ($_SESSION['sess_current_date1'] ?? '') . '">';
print '<i id="startDate" class="calendar ti ti-calendar-clock" title="' . __esc('Start Date Selector') . '"></i>';
print '</span>';
print '</div>';
@@ -554,7 +591,7 @@ class CactiTableFilter {
print '</div>';
print '<div class="filterColumn">';
print '<span>';
print '<input type="text" class="ui-state-default ui-corner-all' . $class . '" id="date2" size="18" value="' . ($_SESSION['sess_current_date2'] ?? '') . '">';
print '<input type="text" class="ui-state-default ui-corner-all' . $class . '" id="date2" size="18" title="' . __esc('End of the custom time range. After setting the start and end dates, click the Refresh button to apply the time range.') . '" value="' . ($_SESSION['sess_current_date2'] ?? '') . '">';
print '<i id="endDate" class="calendar ti ti-calendar-clock" title="' . __esc('End Date Selector') . '"></i>';
print '</span>';
print '</div>';
@@ -587,11 +624,11 @@ class CactiTableFilter {
print '<span>';
if (isset($field_array['refresh'])) {
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="tsrefresh"' . ' title="' . __esc('Refresh Selected Timespan') . '"><span class="button-text">' . __esc('Refresh') . '</span></button>';
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="tsrefresh"' . ' title="' . __esc('Refresh Selected Timespan') . '"><i class="ti ti-refresh"></i></button>';
}
if (isset($field_array['clear'])) {
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="tsclear"' . ' title="' . __esc('Clear Selected Timespan') . '"><span class="button-text">' . __esc('Clear') . '</span></span></button>';
print '<button type="button" class="ui-button ui-corner-all ui-widget" id="tsclear"' . ' title="' . __esc('Clear Selected Timespan') . '"><i class="ti ti-eraser"></i></button>';
}
print '</span>';
@@ -725,16 +762,22 @@ class CactiTableFilter {
// page action buttons (Import, Export, Purge, Save, sort, ...) stay on the
// bar; the filter inputs move into the Edit dialog. go/clear are replaced
// by the dialog's Search/Clear footer actions.
$bar_fields = [];
$bar_actions = [];
$dialog_fields = [];
$bar_fields = [];
$bar_actions = [];
$amalgam_fields = [];
$timespan_fields = [];
$dialog_fields = [];
if (isset($this->filter_array['rows'])) {
foreach ($this->filter_array['rows'] as $row) {
foreach ($row as $field_name => $field_array) {
$method = $field_array['method'] ?? '';
if ($this->field_is_bar($field_name, $field_array)) {
if (!empty($field_array['bar'])) {
$amalgam_fields[$field_name] = $field_array;
} elseif ($method === 'timespan') {
$timespan_fields[$field_name] = $field_array;
} elseif ($this->field_is_bar($field_name, $field_array)) {
$bar_fields[$field_name] = $field_array;
} elseif ($method === 'submit' || $method === 'button') {
if ($field_name !== 'go' && $field_name !== 'clear') {
@@ -747,6 +790,20 @@ class CactiTableFilter {
}
}
// Keep the bar selectors in a stable order: Rows first, Refresh second.
if (cacti_sizeof($bar_fields)) {
$ordered = [];
foreach (['rows', 'refresh'] as $pref) {
if (isset($bar_fields[$pref])) {
$ordered[$pref] = $bar_fields[$pref];
unset($bar_fields[$pref]);
}
}
$bar_fields = $ordered + $bar_fields;
}
ob_start();
// Filter bar.
@@ -760,10 +817,16 @@ class CactiTableFilter {
print $this->emit_field($field_name, $field_array);
}
print $this->layout_button('layout_edit', __('Edit'), __('Edit the current filter'));
print $this->layout_button('layout_rename', __('Rename'), __('Rename the selected layout'));
print $this->layout_button('layout_delete', __('Delete'), __('Delete the selected layout'));
print $this->layout_button('layout_saveas', __('Save As'), __('Save this layout as a new personal layout'));
// Separate the always-present Layouts selector (plus any Rows/Refresh) from the layout buttons.
print "<div class='filterColumnButton'><span class='barSep'></span></div>";
print $this->layout_button('layout_edit', __('Edit'), __('Edit the current filter'), false, 'ti ti-edit');
print $this->layout_button('layout_rename', __('Rename'), __('Rename the selected layout'), true, 'ti ti-forms');
print $this->layout_button('layout_delete', __('Delete'), __('Delete the selected layout'), true, 'ti ti-trash');
print $this->layout_button('layout_saveas', __('Save As'), __('Save this layout as a new personal layout'), true, 'ti ti-device-floppy');
// Refresh (reload the current view, keeping the selected layout) as a glyph button, right of the Edit group.
print "<div class='filterColumnButton'><button type='button' class='ui-button ui-corner-all ui-widget' id='layout_refresh' title='" . __esc('Refresh page') . "'><i class='ti ti-refresh'></i></button></div>" . PHP_EOL;
// Page actions (Import, Export, Purge, Save, sort asc/desc, ...) belong on
// the bar beside the Layouts selector, not inside the Edit dialog.
@@ -778,6 +841,33 @@ class CactiTableFilter {
print '</div>';
print '</div>' . PHP_EOL;
// The Graph Template amalgam (Template + Source/Order/CF/Measure) gets its
// own second filter line.
if (cacti_sizeof($amalgam_fields)) {
print "<div class='filterTable even cactiFilterModernBar'>";
print "<div class='filterRow'>";
foreach ($amalgam_fields as $field_name => $field_array) {
print $this->emit_field($field_name, $field_array);
}
print '</div>';
print '</div>' . PHP_EOL;
}
// Timespan controls get their own third filter line.
if (cacti_sizeof($timespan_fields)) {
print "<div class='filterTable even cactiFilterModernBar'>";
print "<div class='filterRow'>";
foreach ($timespan_fields as $field_name => $field_array) {
print $this->emit_field($field_name, $field_array);
}
print '</div>';
print '</div>' . PHP_EOL;
}
// Edit dialog.
$title = $this->form_header != '' ? $this->form_header : __('Edit Filter');
@@ -989,7 +1079,7 @@ class CactiTableFilter {
break;
case 'filter_checkbox':
if ($this->dynamic) {
if ($this->dynamic && !$this->use_modern_filter()) {
$clickChain .= ($clickChain != '' ? ', ' : '') . '#' . $field_name;
}
@@ -998,36 +1088,37 @@ class CactiTableFilter {
break;
case 'timespan':
// Delegated bindings survive ajax content reloads that replace the timespan controls; direct .change()/.click() handlers would be lost after the first filter apply.
if (!isset($field_array['span_function'])) {
$readyAdd .= "$('#predefined_timespan').change( function() { applyGraphTimespan(); });" . PHP_EOL;
$readyAdd .= "$(document).off('change.cactiTimespan', '#predefined_timespan').on('change.cactiTimespan', '#predefined_timespan', function() { applyGraphTimespan(); });" . PHP_EOL;
} else {
$readyAdd .= "$('#predefined_timespan').change( function() { " . $field_array['span_function'] . '; });' . PHP_EOL;
$readyAdd .= "$(document).off('change.cactiTimespan', '#predefined_timespan').on('change.cactiTimespan', '#predefined_timespan', function() { " . $field_array['span_function'] . '; });' . PHP_EOL;
}
if (isset($field_array['shifter']) && $field_array['shifter'] === true) {
if (!isset($field_array['lshift_function'])) {
$readyAdd .= "$('#shift_left').click( function() { timeshiftGraphFilterLeft(); });" . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#shift_left').on('click.cactiTimespan', '#shift_left', function() { timeshiftGraphFilterLeft(); });" . PHP_EOL;
} else {
$readyAdd .= "$('#shift_left').click( function() { " . $field_array['lshift_function'] . '; });' . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#shift_left').on('click.cactiTimespan', '#shift_left', function() { " . $field_array['lshift_function'] . '; });' . PHP_EOL;
}
if (!isset($field_array['rshift_function'])) {
$readyAdd .= "$('#shift_right').click( function() { timeshiftGraphFilterRight(); });" . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#shift_right').on('click.cactiTimespan', '#shift_right', function() { timeshiftGraphFilterRight(); });" . PHP_EOL;
} else {
$readyAdd .= "$('#shift_right').click( function() { " . $field_array['rshift_function'] . '; });' . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#shift_right').on('click.cactiTimespan', '#shift_right', function() { " . $field_array['rshift_function'] . '; });' . PHP_EOL;
}
}
if (!isset($field_array['refresh_function'])) {
$readyAdd .= "$('#tsrefresh').click( function() { refreshGraphTimespanFilter(); });" . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#tsrefresh').on('click.cactiTimespan', '#tsrefresh', function() { $(this).find('i').addClass('icon-rotate'); refreshGraphTimespanFilter(); });" . PHP_EOL;
} else {
$readyAdd .= "$('#tsrefresh').click( function() { " . $field_array['refresh_function'] . '; });' . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#tsrefresh').on('click.cactiTimespan', '#tsrefresh', function() { $(this).find('i').addClass('icon-rotate'); " . $field_array['refresh_function'] . '; });' . PHP_EOL;
}
if (!isset($field_array['clear_function'])) {
$readyAdd .= "$('#tsclear').click( function() { clearGraphTimespanFilter(); });" . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#tsclear').on('click.cactiTimespan', '#tsclear', function() { clearGraphTimespanFilter(); });" . PHP_EOL;
} else {
$readyAdd .= "$('#tsclear').click( function() { " . $field_array['clear_function'] . '; });' . PHP_EOL;
$readyAdd .= "$(document).off('click.cactiTimespan', '#tsclear').on('click.cactiTimespan', '#tsclear', function() { " . $field_array['clear_function'] . '; });' . PHP_EOL;
}
break;
@@ -1041,7 +1132,9 @@ class CactiTableFilter {
case 'drop_tree':
if ($field_array['method'] != 'textbox' && $this->dynamic) {
if (!isset($field_array['dynamic']) || $field_array['dynamic'] === true) {
$changeChain .= ($changeChain != '' ? ', ' : '') . '#' . $field_name;
if (!$this->use_modern_filter() || $this->field_is_bar($field_name, $field_array) || !empty($field_array['bar'])) {
$changeChain .= ($changeChain != '' ? ', ' : '') . '#' . $field_name;
}
}
}
@@ -1197,6 +1290,9 @@ class CactiTableFilter {
$filters['page']['filter'] = FILTER_VALIDATE_INT;
$filters['page']['default'] = 1;
$filters['layout']['filter'] = FILTER_VALIDATE_INT;
$filters['layout']['default'] = 0;
if (!isrv('page')) {
srv('page', 1);
}
@@ -1214,9 +1310,11 @@ class CactiTableFilter {
validate_store_request_vars($filters, $this->session_var);
}
private function layout_button(string $id, string $display, string $title) : string {
return '<div class="filterColumnButton">' .
'<button type="button" class="ui-button ui-corner-all ui-widget" id="' . $id . '" title="' . html_escape($title) . '"><span class="button-text">' . html_escape($display) . '</span></button>' .
private function layout_button(string $id, string $display, string $title, bool $hidden = false, string $glyph = '') : string {
$content = $glyph !== '' ? '<i class="' . html_escape($glyph) . '"></i>' : '<span class="button-text">' . html_escape($display) . '</span>';
return '<div class="filterColumnButton"' . ($hidden ? ' style="display:none"' : '') . '>' .
'<button type="button" class="ui-button ui-corner-all ui-widget" id="' . $id . '" title="' . html_escape($title) . '">' . $content . '</button>' .
'</div>' . PHP_EOL;
}
@@ -1236,13 +1334,13 @@ class CactiTableFilter {
print $this->layout_select($layouts, $can_glob);
print '</div>';
print $this->layout_button('layout_save', __('Save'), __('Overwrite the selected layout with the current filter'));
print $this->layout_button('layout_new', __('New'), __('Save the current filter as a new layout'));
print $this->layout_button('layout_rename', __('Rename'), __('Rename the selected layout'));
print $this->layout_button('layout_delete', __('Delete'), __('Delete the selected layout'));
print $this->layout_button('layout_save', __('Save'), __('Overwrite the selected layout with the current filter'), false, 'ti ti-device-floppy');
print $this->layout_button('layout_new', __('New'), __('Save the current filter as a new layout'), false, 'ti ti-file-plus');
print $this->layout_button('layout_rename', __('Rename'), __('Rename the selected layout'), false, 'ti ti-forms');
print $this->layout_button('layout_delete', __('Delete'), __('Delete the selected layout'), false, 'ti ti-trash');
if ($can_glob) {
print $this->layout_button('layout_publish', __('Publish'), __('Publish the selected layout so all users can see it'));
print $this->layout_button('layout_publish', __('Publish'), __('Publish the selected layout so all users can see it'), false, 'ti ti-world-up');
}
print '</div>';
@@ -1300,7 +1398,7 @@ class CactiTableFilter {
$js .= "\t$('#layout_rename').click(function() { var id = layoutSelectedId(); if (id == 0) { alert(" . json_encode(__('Please select a layout to rename.')) . '); return; } if (!layoutEditable()) { alert(' . json_encode(__('You are not permitted to modify this layout.')) . "); return; } var cur = $('#filter_layout option:selected').attr('data-name'); layoutNameDialog(" . json_encode(__('Rename Layout')) . ", cur, function(name) { layoutPost('layout_rename', { id: id, name: name }, function(r) { if (layoutResultOk(r)) { window.location.reload(); } }); }); });" . PHP_EOL;
$js .= "\t$('#layout_delete').click(function() { var id = layoutSelectedId(); if (id == 0) { alert(" . json_encode(__('Please select a layout to delete.')) . '); return; } if (!layoutEditable()) { alert(' . json_encode(__('You are not permitted to modify this layout.')) . '); return; } if (confirm(' . json_encode(__('Delete the selected layout?')) . ")) { layoutPost('layout_delete', { id: id }, function(r) { if (layoutResultOk(r)) { document.location = " . json_encode($page) . '; } }); } });' . PHP_EOL;
$js .= "\t$('#layout_delete').click(function() { var id = layoutSelectedId(); if (id == 0) { alert(" . json_encode(__('Please select a layout to delete.')) . '); return; } if (!layoutEditable()) { alert(' . json_encode(__('You are not permitted to modify this layout.')) . "); return; } var d = $('<div>').append($('<p>').text(" . json_encode(__('Delete the selected layout?')) . ")); $('body').append(d); d.dialog({ title: " . json_encode(__('Delete Layout')) . ', modal: true, width: 420, resizable: false, buttons: [ { text: ' . json_encode(__('Delete')) . ", click: function() { $(this).dialog('close'); layoutPost('layout_delete', { id: id }, function(r) { if (layoutResultOk(r)) { document.location = " . json_encode($page) . '; } }); } }, { text: ' . json_encode(__('Cancel')) . ", click: function() { $(this).dialog('close'); } } ], close: function() { $(this).dialog('destroy').remove(); } }); });" . PHP_EOL;
$js .= "\t$('#layout_publish').click(function() { var id = layoutSelectedId(); if (id == 0) { alert(" . json_encode(__('Please select a layout to publish.')) . "); return; } layoutPost('layout_publish', { id: id }, function(r) { if (layoutResultOk(r)) { window.location.reload(); } }); });" . PHP_EOL;
@@ -1312,10 +1410,13 @@ class CactiTableFilter {
/**
* Emit the modern filter JavaScript: the Layouts selector navigation, the
* bar action buttons, and the Edit dialog (Search/Save/Publish/Clear/Cancel)
* that applies, saves, or publishes the current filter.
* bar action buttons, and the Edit dialog. The dialog's apply and clear
* actions reuse the page's configured go/clear button labels (e.g. Go), so
* they match the inline filter and do not collide with a filter field.
*
* @param string $applyFilter The JS expression that builds the filter url.
* @param string $applyFilter The JS expression that builds the filter url.
* @param string $changeFunction The JS apply callback (e.g. applyFilter()).
* @param string $clearFunction The JS clear callback (e.g. clearFilter()).
*
* @return string
*/
@@ -1324,8 +1425,15 @@ class CactiTableFilter {
$can_glob = filter_layouts_can_manage_global();
$title = $this->form_header != '' ? $this->form_header : __('Edit Filter');
$applyLabel = __('Apply');
$js = PHP_EOL . "<script type='text/javascript'>" . PHP_EOL;
$js .= 'var layoutDirty = false;' . PHP_EOL;
// Tracks whether the open dialog is still in "save as new" mode; cleared after the first successful save so later saves update the created layout.
$js .= 'var layoutDialogForceNew = false;' . PHP_EOL;
$js .= 'function layoutFilterUrl() {' . PHP_EOL;
$js .= "\treturn " . $applyFilter . PHP_EOL;
$js .= '}' . PHP_EOL;
@@ -1354,43 +1462,86 @@ class CactiTableFilter {
$js .= 'function layoutUpdateButtons() {' . PHP_EOL;
$js .= "\tvar id = layoutSelectedId();" . PHP_EOL;
$js .= "\tvar editable = layoutEditable();" . PHP_EOL;
$js .= "\t$('#layout_rename').toggle(id != 0 && editable);" . PHP_EOL;
$js .= "\t$('#layout_delete').toggle(id != 0 && editable);" . PHP_EOL;
$js .= "\t$('#layout_saveas').toggle(id != 0 && !editable);" . PHP_EOL;
$js .= "\t$('#layout_rename').closest('.filterColumnButton').toggle(id != 0 && editable);" . PHP_EOL;
$js .= "\t$('#layout_delete').closest('.filterColumnButton').toggle(id != 0 && editable);" . PHP_EOL;
$js .= "\t$('#layout_saveas').closest('.filterColumnButton').toggle(id != 0 && !editable);" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= 'function layoutSetDirty(dirty) {' . PHP_EOL;
$js .= "\tlayoutDirty = dirty;" . PHP_EOL;
$js .= "\tvar b = $('#" . $this->form_id . "_dialog').dialog('widget').find('.ui-dialog-buttonpane button.layoutApplyBtn');" . PHP_EOL;
$js .= "\tif (b.length) { b.button(dirty ? 'disable' : 'enable'); }" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= 'function layoutDialogSave(forceNew) {' . PHP_EOL;
$js .= "\tvar name = $('#layout_name').val();" . PHP_EOL;
$js .= "\tif (name == '') { alert(" . json_encode(__('Please enter a filter name.')) . '); return; }' . PHP_EOL;
$js .= "\tvar id = (forceNew || !layoutEditable()) ? 0 : layoutSelectedId();" . PHP_EOL;
$js .= "\tlayoutPost('layout_save', { id: id, name: name, url: layoutFilterUrl() }, function(r) { if (layoutResultOk(r) && r.url) { document.location = r.url; } });" . PHP_EOL;
$js .= "\tlayoutPost('layout_save', { id: id, name: name, url: layoutFilterUrl() }, function(r) {" . PHP_EOL;
$js .= "\t\tif (!layoutResultOk(r)) { return; }" . PHP_EOL;
$js .= "\t\tif (r.id) {" . PHP_EOL;
$js .= "\t\t\tvar opt = $('#filter_layout option[value=\"' + r.id + '\"]');" . PHP_EOL;
$js .= "\t\t\tif (opt.length == 0) { opt = $('<option>').appendTo('#filter_layout'); }" . PHP_EOL;
$js .= "\t\t\topt.val(r.id).text(r.name).attr('data-url', r.url || '').attr('data-name', r.name).attr('data-editable', '1');" . PHP_EOL;
$js .= "\t\t\t$('#filter_layout').val(r.id);" . PHP_EOL;
$js .= "\t\t\tlayoutUpdateButtons();" . PHP_EOL;
$js .= "\t\t\tlayoutDialogForceNew = false;" . PHP_EOL;
$js .= "\t\t}" . PHP_EOL;
$js .= "\t\tlayoutSetDirty(false);" . PHP_EOL;
$js .= "\t});" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= 'function layoutOpenDialog(forceNew) {' . PHP_EOL;
$js .= "\tlayoutDialogForceNew = forceNew;" . PHP_EOL;
$js .= "\t$('#layout_name').val(forceNew ? '' : (layoutSelectedOption().attr('data-name') || ''));" . PHP_EOL;
$js .= "\tvar buttons = [" . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Search')) . ", click: function() { $(this).dialog('close'); " . $changeFunction . '; } },' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Save')) . ', click: function() { layoutDialogSave(forceNew); } },' . PHP_EOL;
// when a layout is selected (incl. one just saved) apply its own url so filter_layout carries through, otherwise run the plain filter apply
$js .= "\t\t{ text: " . json_encode($applyLabel) . ", click: function() { if (!layoutDirty) { $(this).dialog('close'); var lu = layoutSelectedOption().attr('data-url'); if (layoutSelectedId() != 0 && lu != undefined && lu != '') { loadUrl({ url: correctUrlParameters(lu) }); } else { " . $changeFunction . '; } } } },' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Save')) . ', click: function() { layoutDialogSave(layoutDialogForceNew); } },' . PHP_EOL;
if ($can_glob) {
$js .= "\t\t{ text: " . json_encode(__('Publish')) . ', click: function() { var id = layoutSelectedId(); if (id == 0 || !layoutEditable()) { alert(' . json_encode(__('Save the layout before publishing it.')) . "); return; } layoutPost('layout_publish', { id: id }, function(r) { if (layoutResultOk(r)) { window.location.reload(); } }); } }," . PHP_EOL;
}
$js .= "\t\t{ text: " . json_encode(__('Clear')) . ', click: function() { ' . $clearFunction . '; } },' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Cancel')) . ", click: function() { $(this).dialog('close'); } }" . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Close')) . ", click: function() { $(this).dialog('close'); } }" . PHP_EOL;
$js .= "\t];" . PHP_EOL;
$js .= "\t$('#" . $this->form_id . "_dialog').dialog({ title: " . json_encode($title) . ", modal: true, width: 'auto', minWidth: 500, resizable: false, buttons: buttons });" . PHP_EOL;
$js .= "\t$('#" . $this->form_id . "_dialog').dialog('widget').addClass('cactiFilterDialog');" . PHP_EOL;
$js .= "\t$('#" . $this->form_id . "_dialog').dialog({ title: " . json_encode($title) . ", modal: false, width: 'auto', minWidth: 500, resizable: false, buttons: buttons });" . PHP_EOL;
$js .= "\tvar dw = $('#" . $this->form_id . "_dialog').dialog('widget');" . PHP_EOL;
$js .= "\tdw.addClass('cactiFilterDialog');" . PHP_EOL;
$js .= "\tdw.find('.ui-dialog-buttonpane button').first().addClass('layoutApplyBtn');" . PHP_EOL;
$js .= "\tlayoutSetDirty(forceNew || layoutSelectedId() == 0 || layoutDirty);" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= 'function layoutRenameDialog(id, cur) {' . PHP_EOL;
$js .= "\tvar d = $('<div>').append($('<p>').text(" . json_encode(__('Enter a new name for the layout.')) . ")).append($('<input type=\"text\" id=\"layoutRenameInput\" class=\"ui-state-default ui-corner-all\" size=\"40\" maxlength=\"128\">').val(cur));" . PHP_EOL;
$js .= "\t$('body').append(d);" . PHP_EOL;
$js .= "\td.dialog({ title: " . json_encode(__('Rename Layout')) . ', modal: true, width: 420, resizable: false, buttons: [' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('OK')) . ", click: function() { var n = $('#layoutRenameInput').val(); if (n == '') { return; } $(this).dialog('close'); layoutPost('layout_rename', { id: id, name: n }, function(r) { if (layoutResultOk(r)) { window.location.reload(); } }); } }," . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Cancel')) . ", click: function() { $(this).dialog('close'); } }" . PHP_EOL;
$js .= "\t], close: function() { $(this).dialog('destroy').remove(); } });" . PHP_EOL;
$js .= "\t$('#layoutRenameInput').focus().select().keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); d.dialog('widget').find('.ui-dialog-buttonpane button').first().trigger('click'); } });" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= 'function layoutDeleteDialog(id) {' . PHP_EOL;
$js .= "\tvar d = $('<div>').append($('<p>').text(" . json_encode(__('Delete the selected layout?')) . '));' . PHP_EOL;
$js .= "\t$('body').append(d);" . PHP_EOL;
$js .= "\td.dialog({ title: " . json_encode(__('Delete Layout')) . ', modal: true, width: 420, resizable: false, buttons: [' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Delete')) . ", click: function() { $(this).dialog('close'); layoutPost('layout_delete', { id: id }, function(r) { if (layoutResultOk(r)) { document.location = " . json_encode($page) . '; } }); } },' . PHP_EOL;
$js .= "\t\t{ text: " . json_encode(__('Cancel')) . ", click: function() { $(this).dialog('close'); } }" . PHP_EOL;
$js .= "\t], close: function() { $(this).dialog('destroy').remove(); } });" . PHP_EOL;
$js .= '}' . PHP_EOL;
$js .= '$(function() {' . PHP_EOL;
$js .= "\tlayoutUpdateButtons();" . PHP_EOL;
$js .= "\t$('#filter_layout').change(function() { var u = layoutSelectedOption().attr('data-url'); if (u != undefined && u != '') { document.location = u; } else { layoutUpdateButtons(); } });" . PHP_EOL;
// correctUrlParameters rewrites action=tree to action=tree_content so the tree view regenerates graphs in #main instead of reloading the tree shell (no-op on other pages).
$js .= "\t$('#filter_layout').change(function() { layoutUpdateButtons(); var u = layoutSelectedOption().attr('data-url'); if (u != undefined && u != '') { loadUrl({ url: correctUrlParameters(u) }); } });" . PHP_EOL;
$js .= "\t$('#" . $this->form_id . "_dialog').on('change keyup', 'input, select, textarea', function() { layoutSetDirty(true); });" . PHP_EOL;
$js .= "\t$('#layout_edit').click(function() { layoutOpenDialog(false); });" . PHP_EOL;
$js .= "\t$('#layout_saveas').click(function() { layoutOpenDialog(true); });" . PHP_EOL;
$js .= "\t$('#layout_rename').click(function() { var id = layoutSelectedId(); if (id == 0 || !layoutEditable()) { return; } var cur = layoutSelectedOption().attr('data-name'); var name = prompt(" . json_encode(__('Rename Layout')) . ", cur); if (name != null && name != '') { layoutPost('layout_rename', { id: id, name: name }, function(r) { if (layoutResultOk(r)) { window.location.reload(); } }); } });" . PHP_EOL;
$js .= "\t$('#layout_delete').click(function() { var id = layoutSelectedId(); if (id == 0 || !layoutEditable()) { return; } if (confirm(" . json_encode(__('Delete the selected layout?')) . ")) { layoutPost('layout_delete', { id: id }, function(r) { if (layoutResultOk(r)) { document.location = " . json_encode($page) . '; } }); } });' . PHP_EOL;
$js .= "\t$('#layout_name').keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); layoutDialogSave(false); } });" . PHP_EOL;
$js .= "\t$('#layout_refresh').click(function() { $(this).find('i').addClass('icon-rotate'); var u = layoutSelectedOption().attr('data-url'); if (layoutSelectedId() != 0 && u != undefined && u != '') { loadUrl({ url: correctUrlParameters(u) }); } else { " . $changeFunction . '; } });' . PHP_EOL;
$js .= "\t$('#layout_rename').click(function() { var id = layoutSelectedId(); if (id == 0 || !layoutEditable()) { return; } layoutRenameDialog(id, layoutSelectedOption().attr('data-name') || ''); });" . PHP_EOL;
$js .= "\t$('#layout_delete').click(function() { var id = layoutSelectedId(); if (id == 0 || !layoutEditable()) { return; } layoutDeleteDialog(id); });" . PHP_EOL;
$js .= "\t$('#layout_name').keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); layoutDialogSave(layoutDialogForceNew); } });" . PHP_EOL;
$js .= '});' . PHP_EOL;
$js .= '</script>' . PHP_EOL;
@@ -1413,6 +1564,7 @@ function filter_layouts_preset_pages() : array {
'vdef.php',
'color.php',
'gprint_presets.php',
'layouts.php',
];
}
+25 -35
View File
@@ -1174,36 +1174,11 @@ function form_callback(string $form_name, string $classic_sql, string $column_di
}
}
/* opt-in via $class: preserves the legacy .drop-callback/makeCallbacks() autocomplete
* widget below for every existing caller (including plugins) that does not explicitly
* request the newer ajax-backed select2-callback rendering. */
if (preg_match('/(^|\s)select2-callback(\s|$)/', $class)) {
if (empty($previous_id) && $prev_val == '') {
$prev_val = $none_entry;
}
print "<select id='" . html_escape_attr($form_name) . "' name='" . html_escape_attr($form_name) . "' class='" . html_escape_attr($class) . "'"
. " data-action='" . html_escape_attr($action) . "' data-variables='" . html_escape_attr($request_vars) . "' data-callback='" . html_escape_attr($on_change) . "'>";
if ($previous_id != '' && $prev_val != '') {
print "<option value='" . html_escape_attr($previous_id) . "' selected>" . htmle($prev_val) . '</option>';
} elseif (!empty($none_entry)) {
print "<option value='0' selected>" . htmle($none_entry) . '</option>';
}
print '</select>';
return;
}
if ($class != '') {
$class = " class='$class' ";
}
$theme = get_selected_theme();
if (read_config_option('autocomplete') > 0) {
print "<select id='" . htmle($form_name) . "' name='" . htmle($form_name) . "'" . $class . '>';
/* A non-zero 'autocomplete' config renders the full option list inline as a
* plain <select>; every other case uses the ajax-backed select2 lookup that
* replaced the old .drop-callback autocomplete widget. */
if (read_config_option('autocomplete') > 0 && !preg_match('/(^|\s)select2-callback(\s|$)/', $class)) {
print "<select id='" . htmle($form_name) . "' name='" . htmle($form_name) . "'" . ($class != '' ? " class='$class'" : '') . '>';
if (!empty($none_entry)) {
print "<option value='0'" . (empty($prev_val) ? ' selected' : '') . ">$none_entry</option>";
@@ -1214,13 +1189,28 @@ function form_callback(string $form_name, string $classic_sql, string $column_di
html_create_list($form_data, $column_display, $column_id, $previous_id);
print '</select>';
} else {
if (empty($previous_id) && $prev_val == '') {
$prev_val = $none_entry;
}
print "<input id='$form_name' name='$form_name' type='text' class='drop-callback ui-state-default ui-corner-all' data-action='$action' data-variables='$request_vars' data-callback='$on_change' data-value='" . htmle($prev_val) . "' value='" . htmle($previous_id) . "'>";
return;
}
if (!preg_match('/(^|\s)select2-callback(\s|$)/', $class)) {
$class .= ($class != '' ? ' ' : '') . 'select2-callback';
}
if (empty($previous_id) && $prev_val == '') {
$prev_val = $none_entry;
}
print "<select id='" . html_escape_attr($form_name) . "' name='" . html_escape_attr($form_name) . "' class='" . html_escape_attr($class) . "'"
. " data-action='" . html_escape_attr($action) . "' data-variables='" . html_escape_attr($request_vars) . "' data-callback='" . html_escape_attr($on_change) . "'>";
if ($previous_id != '' && $prev_val != '') {
print "<option value='" . html_escape_attr($previous_id) . "' selected>" . htmle($prev_val) . '</option>';
} elseif (!empty($none_entry)) {
print "<option value='0' selected>" . htmle($none_entry) . '</option>';
}
print '</select>';
}
/**
+3 -2
View File
@@ -311,9 +311,10 @@ function create_graphs_preview_filter(string $session_var) : array {
[
'graph_template_id' => [
'method' => 'drop_multi',
'bar' => true,
'friendly_name' => __('Template'),
'filter' => FILTER_VALIDATE_REGEXP,
'filter_options' => ['options' => ['regexp' => '/^(cg_[0-9]+|dq_[0-9]+|-?[0-9]+)$/']],
'filter_options' => ['options' => ['regexp' => '/^(cg_[0-9]+|dq_[0-9]+|-?[0-9]+)(,(cg_[0-9]+|dq_[0-9]+|-?[0-9]+))*$/']],
'default' => '-1',
'dynamic' => false,
'class' => 'select2-multi-count',
@@ -1156,7 +1157,7 @@ function create_listview_filter(string $session_var) : array {
'method' => 'drop_multi',
'friendly_name' => __('Template'),
'filter' => FILTER_VALIDATE_REGEXP,
'filter_options' => ['options' => ['regexp' => '/^(cg_[0-9]+|dq_[0-9]+|-?[0-9]+)$/']],
'filter_options' => ['options' => ['regexp' => '/^(cg_[0-9]+|dq_[0-9]+|-?[0-9]+)(,(cg_[0-9]+|dq_[0-9]+|-?[0-9]+))*$/']],
'default' => '-1',
'dynamic' => false,
'class' => 'select2-multi-count',
+3 -2
View File
@@ -1018,6 +1018,7 @@ function create_tree_filter() : array {
[
'graph_template_id' => [
'method' => 'drop_multi',
'bar' => true,
'friendly_name' => __('Template'),
'filter' => FILTER_VALIDATE_REGEXP,
'filter_options' => ['options' => ['regexp' => '/^(cg_[0-9]+|dq_[0-9]+|-?[0-9]+)(,(cg_[0-9]+|dq_[0-9]+|-?[0-9]+))*$/']],
@@ -1580,14 +1581,14 @@ function grow_right_pane_tree(int $tree_id, int $leaf_id, string $host_group_dat
* Retrieves a list of graphs for a given host, graph template, and data query.
*
* @param int $host_id The ID of the host.
* @param int $graph_template_id The ID of the graph template.
* @param string $graph_template_id The ID(s) of the graph template(s).
* @param int $data_query_id The ID of the data query.
* @param string $host_grouping_type The type of host grouping (optional).
* @param string $data_query_index The index of the data query (optional).
*
* @return array An array of graphs for the specified host, graph template, and data query.
*/
function get_host_graph_list(int $host_id, int $graph_template_id, int $data_query_id, string $host_grouping_type = '', string $data_query_index = '') : array {
function get_host_graph_list(int $host_id, string $graph_template_id, int $data_query_id, string $host_grouping_type = '', string $data_query_index = '') : array {
$graph_list = [];
$sql_where = '';
+96 -16
View File
@@ -25312,26 +25312,10 @@ msgstr ""
msgid "Delete the selected layout?"
msgstr ""
#: layouts.php
msgid "Filter Layouts"
msgstr ""
#: layouts.php
msgid "User %d"
msgstr ""
#: layouts.php
msgid "Published to all users"
msgstr ""
#: layouts.php
msgid "Publish to all users"
msgstr ""
#: layouts.php
msgid "No Filter Layouts Found"
msgstr ""
#: lib/html_filter.php layouts.php
msgid "Global"
msgstr ""
@@ -25375,3 +25359,99 @@ msgstr ""
#: lib/html_filter.php
msgid "Save the layout before publishing it."
msgstr ""
#: lib/html_filter.php
msgid "Apply"
msgstr ""
#: lib/html_filter.php
msgid "Enter a new name for the layout."
msgstr ""
#: lib/html_filter.php
msgid "Refresh page"
msgstr ""
#: lib/html_filter.php
msgid "Start of the custom time range. After setting the start and end dates, click the Refresh button to apply the time range."
msgstr ""
#: lib/html_filter.php
msgid "End of the custom time range. After setting the start and end dates, click the Refresh button to apply the time range."
msgstr ""
#: layouts.php
msgid "Make Global"
msgstr ""
#: layouts.php
msgid "Make Local"
msgstr ""
#: layouts.php
msgid "Make Layout Global"
msgstr ""
#: layouts.php
msgid "Make Layouts Global"
msgstr ""
#: layouts.php
msgid "Make Layout Local"
msgstr ""
#: layouts.php
msgid "Make Layouts Local"
msgstr ""
#: layouts.php
msgid "Delete Layout"
msgstr ""
#: layouts.php
msgid "Delete Layouts"
msgstr ""
#: layouts.php
msgid "No Layouts Found"
msgstr ""
#: layouts.php
msgid "The name of this Layout."
msgstr ""
#: layouts.php
msgid "The page this Layout applies to."
msgstr ""
#: layouts.php
msgid "The owner of this Layout, or Global when shared with all users."
msgstr ""
#: layouts.php
msgid "The stored filter this Layout applies."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to Delete the following Layout."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to Delete the following Layouts."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to make the following Layout Global to all users."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to make the following Layouts Global to all users."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to make the following Layout Local to you."
msgstr ""
#: layouts.php
msgid "Click 'Continue' to make the following Layouts Local to you."
msgstr ""
+28 -2
View File
@@ -152,6 +152,15 @@ test('the modern filter keeps time controls on the bar and fields in the dialog'
expect($src)->toContain('private function field_is_bar(string $field_name, array $field_array) : bool {');
expect($src)->toContain("=== 'timespan' || \$field_name === 'refresh'");
expect($src)->toContain("\$field_name === 'rows'");
// The row-count selector is always labeled Rows.
expect($src)->toContain("\$field_array['friendly_name'] = __('Rows');");
// Bar selectors are ordered Rows then Refresh and separated from the buttons.
expect($src)->toContain("foreach (['rows', 'refresh'] as \$pref) {");
expect($src)->toContain('$bar_fields = $ordered + $bar_fields;');
expect($src)->toContain('// Separate the always-present Layouts selector (plus any Rows/Refresh) from the layout buttons.');
// Two separators: selectors|buttons and buttons|page-actions.
expect(substr_count($src, "<span class='barSep'></span>"))->toBeGreaterThan(1);
expect($src)->toContain('cactiFilterEditDialog');
expect($src)->toContain("\$this->layout_button('layout_edit',");
expect($src)->toContain("\$this->layout_button('layout_saveas',");
@@ -163,6 +172,23 @@ test('the modern filter keeps time controls on the bar and fields in the dialog'
expect($src)->not->toContain('$dialog_rows');
});
test('the modern dialog Apply action is labelled Apply and gated on a saved layout', function () use ($root) {
$src = file_get_contents($root . '/lib/html_filter.php');
// The apply action is labelled Apply and only fires once the filter is saved.
expect($src)->toContain("\$applyLabel = __('Apply');");
expect($src)->toContain('json_encode($applyLabel)');
expect($src)->toContain('if (!layoutDirty) {');
// Saving no longer reloads the page and the dialog is non-modal.
expect($src)->toContain('layoutSetDirty(false)');
expect($src)->toContain('modal: false');
// The stale hardcoded Search label and the Clear action are gone.
expect($src)->not->toContain('json_encode(__(\'Search\'))');
expect($src)->not->toContain('json_encode($clearLabel)');
});
test('page action buttons (import, export, sort) render on the bar, not the dialog', function () use ($root) {
$src = file_get_contents($root . '/lib/html_filter.php');
@@ -188,7 +214,7 @@ test('the edit dialog is tagged for theming and the modern theme skins it', func
$css = file_get_contents($root . '/include/themes/modern/main.css');
// The widget wrapper is tagged so themes can skin the dialog chrome.
expect($src)->toContain(".dialog('widget').addClass('cactiFilterDialog');");
expect($src)->toContain("dw.addClass('cactiFilterDialog');");
expect($css)->toContain('.ui-dialog.cactiFilterDialog .ui-dialog-titlebar');
expect($css)->toContain('.ui-dialog.cactiFilterDialog .ui-dialog-buttonpane');
@@ -211,7 +237,7 @@ test('layouts.php is admin-only and registered in the Presets menu', function ()
$arrays = file_get_contents($root . '/include/global_arrays.php');
expect($arrays)->toContain("'layouts.php' => 15,");
expect($arrays)->toContain("'layouts.php' => __('Filters'),");
expect($arrays)->toContain("'layouts.php' => __('Layouts'),");
});
test('user_layouts is defined consistently across the schema files', function () use ($root) {
+53
View File
@@ -90,3 +90,56 @@ test('syncAssets fails loudly if screenfull stops shipping the expected ESM expo
/expected 'export default screenfull;'/,
);
});
test('the tablesorter transform replaces every removed jQuery API with native equivalents', () => {
const root = fixture();
const transformed = [
'node_modules/tablesorter/dist/js/jquery.tablesorter.js',
'node_modules/tablesorter/dist/js/jquery.tablesorter.widgets.js',
];
const source = [
'if ( $.isFunction( fn ) ) { call(); }',
'var trimmed = $.trim( raw );',
"if ( $.type( val ) === 'string' ) { ok(); }",
"if ( $.type( obj ) === 'object' ) { ok(); }",
'var scoped = $.isWindow( scope );',
'var arr = $.isArray( list );',
'var parsed = $.parseJSON( text );',
'if ($.parseJSON) { load(); }',
'return str ? ( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ).trim() : str;',
'',
].join('\n');
for (const asset of transformed) {
writeFileSync(join(root, asset), source);
}
syncAssets(root, () => {});
for (const asset of transformed) {
const output = readFileSync(join(root, assetMap[asset]), 'utf8');
// every removed jQuery 4 utility is rewritten to its native equivalent
assert.match(output, /typeof fn === 'function'/);
assert.match(output, /\( raw \)\.trim\(\)/);
assert.match(output, /typeof val === 'string'/);
assert.match(output, /\$\.isPlainObject\(obj\)/);
assert.match(output, /scope != null && scope === scope\.window/);
assert.match(output, /Array\.isArray\(/);
assert.match(output, /JSON\.parse\(/);
assert.match(output, /if \(window\.JSON && window\.JSON\.parse\)/);
// the CodeQL useless-conditional simplification is applied too
assert.match(output, /\( table\.config\.ignoreCase \?/);
// none of the removed APIs (nor the redundant guard) survive
assert.doesNotMatch(output, /\$\.isFunction/);
assert.doesNotMatch(output, /\$\.trim\(/);
assert.doesNotMatch(output, /\$\.type\(/);
assert.doesNotMatch(output, /\$\.isWindow/);
assert.doesNotMatch(output, /\$\.isArray/);
assert.doesNotMatch(output, /\$\.parseJSON/);
assert.doesNotMatch(output, /str && table\.config\.ignoreCase/);
}
});