diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-13 11:44:46 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-13 11:44:46 +0000 |
commit | b18bc644404e02b57635bfcc8258e85abb141146 (patch) | |
tree | 686512eacb2dba0055277ef7ec2f28695b3418ea /public/js | |
parent | Initial commit. (diff) | |
download | icingadb-web-b18bc644404e02b57635bfcc8258e85abb141146.tar.xz icingadb-web-b18bc644404e02b57635bfcc8258e85abb141146.zip |
Adding upstream version 1.1.1.upstream/1.1.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'public/js')
-rw-r--r-- | public/js/action-list.js | 788 | ||||
-rw-r--r-- | public/js/migrate.js | 654 | ||||
-rw-r--r-- | public/js/progress-bar.js | 110 |
3 files changed, 1552 insertions, 0 deletions
diff --git a/public/js/action-list.js b/public/js/action-list.js new file mode 100644 index 0000000..69cab05 --- /dev/null +++ b/public/js/action-list.js @@ -0,0 +1,788 @@ +/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */ + +;(function (Icinga) { + + "use strict"; + + try { + var notjQuery = require('icinga/icinga-php-library/notjQuery'); + } catch (e) { + console.warn('Unable to provide input enrichments. Libraries not available:', e); + return; + } + + Icinga.Behaviors = Icinga.Behaviors || {}; + + class ActionList extends Icinga.EventListener { + constructor(icinga) { + super(icinga); + + this.on('click', '.action-list [data-action-item]:not(.page-separator), .action-list [data-action-item] a[href]', this.onClick, this); + this.on('close-column', '#main > #col2', this.onColumnClose, this); + this.on('column-moved', this.onColumnMoved, this); + + this.on('rendered', '#main .container', this.onRendered, this); + this.on('keydown', '#body', this.onKeyDown, this); + + this.on('click', '.load-more[data-no-icinga-ajax] a', this.onLoadMoreClick, this); + this.on('keypress', '.load-more[data-no-icinga-ajax] a', this.onKeyPress, this); + + this.lastActivatedItemUrl = null; + this.lastTimeoutId = null; + this.isProcessingLoadMore = false; + this.activeRequests = {}; + } + + /** + * Parse the filter query contained in the given URL query string + * + * @param {string} queryString + * + * @returns {array} + */ + parseSelectionQuery(queryString) { + return queryString.split('|'); + } + + /** + * Suspend auto refresh for the given item's container + * + * @param {Element} item + * + * @return {string} The container's id + */ + suspendAutoRefresh(item) { + const container = item.closest('.container'); + container.dataset.suspendAutorefresh = ''; + + return container.id; + } + + /** + * Enable auto refresh on the given container + * + * @param {string} containerId + */ + enableAutoRefresh(containerId) { + delete document.getElementById(containerId).dataset.suspendAutorefresh; + } + + onClick(event) { + let _this = event.data.self; + let target = event.currentTarget; + + if (target.matches('a') && (! target.matches('.subject') || event.ctrlKey || event.metaKey)) { + return true; + } + + event.preventDefault(); + event.stopImmediatePropagation(); + event.stopPropagation(); + + let item = target.closest('[data-action-item]'); + let list = target.closest('.action-list'); + let activeItems = _this.getActiveItems(list); + let toActiveItems = [], + toDeactivateItems = []; + + const isBeingMultiSelected = list.matches('[data-icinga-multiselect-url]') + && (event.ctrlKey || event.metaKey || event.shiftKey); + + if (isBeingMultiSelected) { + if (event.ctrlKey || event.metaKey) { + if (item.classList.contains('active')) { + toDeactivateItems.push(item); + } else { + toActiveItems.push(item); + } + } else { + document.getSelection().removeAllRanges(); + + let allItems = _this.getAllItems(list); + + let startIndex = allItems.indexOf(item); + if(startIndex < 0) { + startIndex = 0; + } + + let endIndex = activeItems.length ? allItems.indexOf(activeItems[0]) : 0; + if (startIndex > endIndex) { + toActiveItems = allItems.slice(endIndex, startIndex + 1); + } else { + endIndex = activeItems.length ? allItems.indexOf(activeItems[activeItems.length - 1]) : 0; + toActiveItems = allItems.slice(startIndex, endIndex + 1); + } + + toDeactivateItems = activeItems.filter(item => ! toActiveItems.includes(item)); + toActiveItems = toActiveItems.filter(item => ! activeItems.includes(item)); + } + } else { + toDeactivateItems = activeItems; + toActiveItems.push(item); + } + + if (activeItems.length === 1 + && toActiveItems.length === 0 + && _this.icinga.loader.getLinkTargetFor($(target)).attr('id') === 'col2' + ) { + _this.icinga.ui.layout1col(); + _this.enableAutoRefresh('col1'); + return; + } + + let dashboard = list.closest('.dashboard'); + if (dashboard) { + dashboard.querySelectorAll('.action-list').forEach(otherList => { + if (otherList !== list) { + toDeactivateItems.push(..._this.getAllItems(otherList)); + } + }) + } + + let lastActivatedUrl = null; + if (toActiveItems.includes(item)) { + lastActivatedUrl = item.dataset.icingaDetailFilter; + } else if (activeItems.length > 1) { + lastActivatedUrl = activeItems[activeItems.length - 1] === item + ? activeItems[activeItems.length - 2].dataset.icingaDetailFilter + : activeItems[activeItems.length - 1].dataset.icingaDetailFilter; + } + + _this.clearSelection(toDeactivateItems); + _this.setActive(toActiveItems); + + if (! dashboard) { + _this.addSelectionCountToFooter(list); + } + + _this.setLastActivatedItemUrl(lastActivatedUrl); + _this.loadDetailUrl(list, target.matches('a') ? target.getAttribute('href') : null); + } + + /** + * Add the selection count to footer if list allow multi selection + * + * @param list + */ + addSelectionCountToFooter(list) { + if (! list.matches('[data-icinga-multiselect-url]')) { + return; + } + + let activeItemCount = this.getActiveItems(list).length; + let footer = list.closest('.container').querySelector('.footer'); + + // For items that do not have a bottom status bar like Downtimes, Comments... + if (footer === null) { + footer = notjQuery.render( + '<div class="footer" data-action-list-automatically-added>' + + '<div class="selection-count"><span class="selected-items"></span></div>' + + '</div>' + ) + + list.closest('.container').appendChild(footer); + } + + let selectionCount = footer.querySelector('.selection-count'); + if (selectionCount === null) { + selectionCount = notjQuery.render( + '<div class="selection-count"><span class="selected-items"></span></div>' + ); + + footer.prepend(selectionCount); + } + + let selectedItems = selectionCount.querySelector('.selected-items'); + selectedItems.innerText = activeItemCount + ? list.dataset.icingaMultiselectCountLabel.replace('%d', activeItemCount) + : list.dataset.icingaMultiselectHintLabel; + + if (activeItemCount === 0) { + selectedItems.classList.add('hint'); + } else { + selectedItems.classList.remove('hint'); + } + } + + /** + * Key navigation for .action-list + * + * - `Shift + ArrowUp|ArrowDown` = Multiselect + * - `ArrowUp|ArrowDown` = Select next/previous + * - `Ctrl|cmd + A` = Select all on currect page + * + * @param event + */ + onKeyDown(event) { + let _this = event.data.self; + let list = null; + let pressedArrowDownKey = event.key === 'ArrowDown'; + let pressedArrowUpKey = event.key === 'ArrowUp'; + let focusedElement = document.activeElement; + + if ( + _this.isProcessingLoadMore + || ! event.key // input auto-completion is triggered + || (event.key.toLowerCase() !== 'a' && ! pressedArrowDownKey && ! pressedArrowUpKey) + ) { + return; + } + + if (focusedElement && ( + focusedElement.matches('#main > :scope') + || focusedElement.matches('#body')) + ) { + let activeItem = document.querySelector( + '#main > .container > .content > .action-list [data-action-item].active' + ); + if (activeItem) { + list = activeItem.closest('.action-list'); + } else { + list = focusedElement.querySelector('#main > .container > .content > .action-list'); + } + } else if (focusedElement) { + list = focusedElement.closest('.content > .action-list'); + } + + if (! list) { + return; + } + + let isMultiSelectableList = list.matches('[data-icinga-multiselect-url]'); + + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'a') { + if (! isMultiSelectableList) { + return; + } + + event.preventDefault(); + _this.selectAll(list); + return; + } + + event.preventDefault(); + + let allItems = _this.getAllItems(list); + let firstListItem = allItems[0]; + let lastListItem = allItems[allItems.length -1]; + let activeItems = _this.getActiveItems(list); + let markAsLastActive = null; // initialized only if it is different from toActiveItem + let toActiveItem = null; + let wasAllSelected = activeItems.length === allItems.length; + let lastActivatedItem = list.querySelector( + `[data-icinga-detail-filter="${ _this.lastActivatedItemUrl }"]` + ); + + if (! lastActivatedItem && activeItems.length) { + lastActivatedItem = activeItems[activeItems.length - 1]; + } + + let directionalNextItem = _this.getDirectionalNext(lastActivatedItem, event.key); + + if (activeItems.length === 0) { + toActiveItem = pressedArrowDownKey ? firstListItem : lastListItem; + // reset all on manual page refresh + _this.clearSelection(activeItems); + if (toActiveItem.classList.contains('load-more')) { + toActiveItem = toActiveItem.previousElementSibling; + } + } else if (isMultiSelectableList && event.shiftKey) { + if (activeItems.length === 1) { + toActiveItem = directionalNextItem; + } else if (wasAllSelected && ( + (lastActivatedItem !== firstListItem && pressedArrowDownKey) + || (lastActivatedItem !== lastListItem && pressedArrowUpKey) + )) { + if (pressedArrowDownKey) { + toActiveItem = lastActivatedItem === lastListItem ? null : lastListItem; + } else { + toActiveItem = lastActivatedItem === firstListItem ? null : lastListItem; + } + + } else if (directionalNextItem && directionalNextItem.classList.contains('active')) { + // deactivate last activated by down to up select + _this.clearSelection([lastActivatedItem]); + if (wasAllSelected) { + _this.scrollItemIntoView(lastActivatedItem, event.key); + } + + toActiveItem = directionalNextItem; + } else { + [toActiveItem, markAsLastActive] = _this.findToActiveItem(lastActivatedItem, event.key); + } + } else { + toActiveItem = directionalNextItem ?? lastActivatedItem; + + if (toActiveItem) { + if (toActiveItem.classList.contains('load-more')) { + clearTimeout(_this.lastTimeoutId); + _this.handleLoadMoreNavigate(toActiveItem, lastActivatedItem, event.key); + return; + } + + _this.clearSelection(activeItems); + if (toActiveItem.classList.contains('page-separator')) { + toActiveItem = _this.getDirectionalNext(toActiveItem, event.key); + } + } + } + + if (! toActiveItem) { + return; + } + + _this.setActive(toActiveItem); + _this.setLastActivatedItemUrl( + markAsLastActive ? markAsLastActive.dataset.icingaDetailFilter : toActiveItem.dataset.icingaDetailFilter + ); + _this.scrollItemIntoView(toActiveItem, event.key); + _this.addSelectionCountToFooter(list); + _this.loadDetailUrl(list); + } + + /** + * Get the next list item according to the pressed key (`ArrowUp` or `ArrowDown`) + * + * @param item The list item from which we want the next item + * @param eventKey Pressed key (`ArrowUp` or `ArrowDown`) + * + * @returns {Element|null} + */ + getDirectionalNext(item, eventKey) { + if (! item) { + return null; + } + + return eventKey === 'ArrowUp' ? item.previousElementSibling : item.nextElementSibling; + } + + /** + * Find the list item that should be activated next + * + * @param lastActivatedItem + * @param eventKey Pressed key (`ArrowUp` or `ArrowDown`) + * + * @returns {Element[]} + */ + findToActiveItem(lastActivatedItem, eventKey) { + let toActiveItem; + let markAsLastActive; + + toActiveItem = this.getDirectionalNext(lastActivatedItem, eventKey); + + while (toActiveItem) { + if (! toActiveItem.classList.contains('active')) { + break; + } + + toActiveItem = this.getDirectionalNext(toActiveItem, eventKey); + } + + markAsLastActive = toActiveItem; + // if the next/previous sibling element is already active, + // mark the last/first active element in list as last active + while (markAsLastActive && this.getDirectionalNext(markAsLastActive, eventKey)) { + if (! this.getDirectionalNext(markAsLastActive, eventKey).classList.contains('active')) { + break; + } + + markAsLastActive = this.getDirectionalNext(markAsLastActive, eventKey); + } + + return [toActiveItem, markAsLastActive]; + } + + /** + * Select All list items + * + * @param list The action list + */ + selectAll(list) { + let allItems = this.getAllItems(list); + let activeItems = this.getActiveItems(list); + this.setActive(allItems.filter(item => ! activeItems.includes(item))); + this.setLastActivatedItemUrl(allItems[allItems.length -1].dataset.icingaDetailFilter); + this.addSelectionCountToFooter(list); + this.loadDetailUrl(list); + } + + /** + * Clear the selection by removing .active class + * + * @param selectedItems The items with class active + */ + clearSelection(selectedItems) { + selectedItems.forEach(item => item.classList.remove('active')); + } + + /** + * Set the last activated item Url + * + * @param url + */ + setLastActivatedItemUrl (url) { + this.lastActivatedItemUrl = url; + } + + /** + * Scroll the given item into view + * + * @param item Item to scroll into view + * @param pressedKey Pressed key (`ArrowUp` or `ArrowDown`) + */ + scrollItemIntoView(item, pressedKey) { + item.scrollIntoView({block: "nearest"}); + let directionalNext = this.getDirectionalNext(item, pressedKey); + + if (directionalNext) { + directionalNext.scrollIntoView({block: "nearest"}); + } + } + + /** + * Load the detail url with selected items + * + * @param list The action list + * @param anchorUrl If any anchor is clicked (e.g. host in service list) + */ + loadDetailUrl(list, anchorUrl = null) { + let url = anchorUrl; + let activeItems = this.getActiveItems(list); + + if (url === null) { + if (activeItems.length > 1) { + url = this.createMultiSelectUrl(activeItems); + } else { + let anchor = activeItems[0].querySelector('[href]'); + url = anchor ? anchor.getAttribute('href') : null; + } + } + + if (url === null) { + return; + } + + const suspendedContainer = this.suspendAutoRefresh(list); + + clearTimeout(this.lastTimeoutId); + this.lastTimeoutId = setTimeout(() => { + const requestNo = this.lastTimeoutId; + this.activeRequests[requestNo] = suspendedContainer; + this.lastTimeoutId = null; + + let req = this.icinga.loader.loadUrl( + url, + this.icinga.loader.getLinkTargetFor($(activeItems[0])) + ); + + req.always((_, __, errorThrown) => { + if (errorThrown !== 'abort') { + this.enableAutoRefresh(this.activeRequests[requestNo]); + } + + delete this.activeRequests[requestNo]; + }); + }, 250); + } + + /** + * Add .active class to given list item + * + * @param toActiveItem The list item(s) + */ + setActive(toActiveItem) { + if (toActiveItem instanceof HTMLElement) { + toActiveItem.classList.add('active'); + } else { + toActiveItem.forEach(item => item.classList.add('active')); + } + } + + /** + * Get the active items from given list + * + * @param list The action list + * + * @return array + */ + getActiveItems(list) + { + let items; + if (list.tagName.toLowerCase() === 'table') { + items = list.querySelectorAll(':scope > tbody > [data-action-item].active'); + } else { + items = list.querySelectorAll(':scope > [data-action-item].active'); + } + + return Array.from(items); + } + + /** + * Get all available items from given list + * + * @param list The action list + * + * @return array + */ + getAllItems(list) + { + let items; + if (list.tagName.toLowerCase() === 'table') { + items = list.querySelectorAll(':scope > tbody > [data-action-item]'); + } else { + items = list.querySelectorAll(':scope > [data-action-item]'); + } + + return Array.from(items); + } + + /** + * Handle the navigation on load-more button + * + * @param loadMoreElement + * @param lastActivatedItem + * @param pressedKey Pressed key (`ArrowUp` or `ArrowDown`) + */ + handleLoadMoreNavigate(loadMoreElement, lastActivatedItem, pressedKey) { + let req = this.loadMore(loadMoreElement.firstChild); + this.isProcessingLoadMore = true; + req.done(() => { + this.isProcessingLoadMore = false; + // list has now new items, so select the lastActivatedItem and then move forward + let toActiveItem = lastActivatedItem.nextElementSibling; + while (toActiveItem) { + if (toActiveItem.hasAttribute('data-action-item')) { + this.clearSelection([lastActivatedItem]); + this.setActive(toActiveItem); + this.setLastActivatedItemUrl(toActiveItem.dataset.icingaDetailFilter); + this.scrollItemIntoView(toActiveItem, pressedKey); + this.addSelectionCountToFooter(toActiveItem.parentElement); + this.loadDetailUrl(toActiveItem.parentElement); + return; + } + + toActiveItem = toActiveItem.nextElementSibling; + } + }); + } + + /** + * Click on load-more button + * + * @param event + * + * @returns {boolean} + */ + onLoadMoreClick(event) { + event.stopPropagation(); + event.preventDefault(); + + event.data.self.loadMore(event.target); + + return false; + } + + onKeyPress(event) { + if (event.key === ' ') { // space + event.data.self.onLoadMoreClick(event); + } + } + + /** + * Load more list items based on the given anchor + * + * @param anchor + * + * @returns {*|{getAllResponseHeaders: function(): *|null, abort: function(*): this, setRequestHeader: function(*, *): this, readyState: number, getResponseHeader: function(*): null|*, overrideMimeType: function(*): this, statusCode: function(*): this}|jQuery|boolean} + */ + loadMore(anchor) { + let showMore = anchor.parentElement; + var progressTimer = this.icinga.timer.register(function () { + var label = anchor.innerText; + + var dots = label.substr(-3); + if (dots.slice(0, 1) !== '.') { + dots = '. '; + } else { + label = label.slice(0, -3); + if (dots === '...') { + dots = '. '; + } else if (dots === '.. ') { + dots = '...'; + } else if (dots === '. ') { + dots = '.. '; + } + } + + anchor.innerText = label + dots; + }, null, 250); + + let url = anchor.getAttribute('href'); + let req = this.icinga.loader.loadUrl( + // Add showCompact, we don't want controls in paged results + this.icinga.utils.addUrlFlag(url, 'showCompact'), + $(showMore.parentElement), + undefined, + undefined, + 'append', + false, + progressTimer + ); + req.addToHistory = false; + req.done(function () { + showMore.remove(); + + // Set data-icinga-url to make it available for Icinga.History.getCurrentState() + req.$target.closest('.container').data('icingaUrl', url); + + this.icinga.history.replaceCurrentState(); + }); + + return req; + } + + /** + * Create the detail url for multi selectable list + * + * @param items List items + * @param withBaseUrl Default to true + * + * @returns {string} The url + */ + createMultiSelectUrl(items, withBaseUrl = true) { + let filters = []; + items.forEach(item => { + filters.push(item.getAttribute('data-icinga-multiselect-filter')); + }); + + let url = '?' + filters.join('|'); + + if (withBaseUrl) { + return items[0].closest('.action-list').getAttribute('data-icinga-multiselect-url') + url; + } + + return url; + } + + onColumnClose(event) { + let _this = event.data.self; + let list = _this.findDetailUrlActionList(document.getElementById('col1')); + if (list && list.matches('[data-icinga-multiselect-url], [data-icinga-detail-url]')) { + _this.clearSelection(_this.getActiveItems(list)); + _this.addSelectionCountToFooter(list); + } + } + + /** + * Find the action list using the detail url + * + * @param {Element} container + * + * @return Element|null + */ + findDetailUrlActionList(container) { + let detailUrl = this.icinga.utils.parseUrl( + this.icinga.history.getCol2State().replace(/^#!/, '') + ); + + let detailItem = container.querySelector( + '[data-icinga-detail-filter="' + + detailUrl.query.replace('?', '') + '"],' + + '[data-icinga-multiselect-filter="' + + detailUrl.query.split('|', 1).toString().replace('?', '') + '"]' + ); + + return detailItem ? detailItem.parentElement : null; + } + + /** + * Triggers when column is moved to left or right + * + * @param event + * @param sourceId The content is moved from + */ + onColumnMoved(event, sourceId) { + let _this = event.data.self; + + if (event.target.id === 'col2' && sourceId === 'col1') { // only for browser-back (col1 shifted to col2) + _this.clearSelection(event.target.querySelectorAll('.action-list .active')); + } else if (event.target.id === 'col1' && sourceId === 'col2') { + for (const requestNo of Object.keys(_this.activeRequests)) { + if (_this.activeRequests[requestNo] === sourceId) { + _this.enableAutoRefresh(_this.activeRequests[requestNo]); + _this.activeRequests[requestNo] = _this.suspendAutoRefresh(event.target); + } + } + } + } + + onRendered(event, isAutoRefresh) { + let _this = event.data.self; + let container = event.target; + let isTopLevelContainer = container.matches('#main > :scope'); + + let list; + if (event.currentTarget !== container || Object.keys(_this.activeRequests).length) { + // Nested containers are not processed multiple times || still processing selection/navigation request + return; + } else if (isTopLevelContainer && container.id !== 'col1') { + if (isAutoRefresh) { + return; + } + + // only for browser back/forward navigation + list = _this.findDetailUrlActionList(document.getElementById('col1')); + } else { + list = _this.findDetailUrlActionList(container); + } + + if (list && list.matches('[data-icinga-multiselect-url], [data-icinga-detail-url]')) { + let detailUrl = _this.icinga.utils.parseUrl( + _this.icinga.history.getCol2State().replace(/^#!/, '') + ); + let toActiveItems = []; + if (list.dataset.icingaMultiselectUrl === detailUrl.path) { + for (const filter of _this.parseSelectionQuery(detailUrl.query.slice(1))) { + let item = list.querySelector( + '[data-icinga-multiselect-filter="' + filter + '"]' + ); + + if (item) { + toActiveItems.push(item); + } + } + } else if (_this.matchesDetailUrl(list.dataset.icingaDetailUrl, detailUrl.path)) { + let item = list.querySelector( + '[data-icinga-detail-filter="' + detailUrl.query.slice(1) + '"]' + ); + + if (item) { + toActiveItems.push(item); + } + } + + _this.clearSelection(_this.getAllItems(list).filter(item => !toActiveItems.includes(item))); + _this.setActive(toActiveItems); + } + + if (isTopLevelContainer) { + let footerList = list ?? container.querySelector('.content > .action-list'); + if (footerList) { + _this.addSelectionCountToFooter(footerList); + } + } + } + + matchesDetailUrl(itemUrl, detailUrl) { + if (itemUrl === detailUrl) { + return true; + } + + // The slash is used to avoid false positives (e.g. icingadb/hostgroup and icingadb/host) + return detailUrl.startsWith(itemUrl + '/'); + } + } + + Icinga.Behaviors.ActionList = ActionList; + +}(Icinga)); diff --git a/public/js/migrate.js b/public/js/migrate.js new file mode 100644 index 0000000..dddbaed --- /dev/null +++ b/public/js/migrate.js @@ -0,0 +1,654 @@ +/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */ + +;(function(Icinga, $) { + + 'use strict'; + + const ANIMATION_LENGTH = 350; + + const POPUP_HTML = '<div class="icinga-module module-icingadb">\n' + + ' <div id="migrate-popup">\n' + + ' <div class="suggestion-area">\n' + + ' <button type="button" class="close">Don\'t show this again</button>\n' + + ' <ul class="search-migration-suggestions"></ul>\n' + + ' <p class="search-migration-hint">Miss some results? Try the link(s) below</p>\n' + + ' <ul class="monitoring-migration-suggestions"></ul>\n' + + ' <p class="monitoring-migration-hint">Preview this in Icinga DB</p>\n' + + ' </div>\n' + + ' <div class="minimizer"><i class="icon-"></i></div>\n' + + ' </div>\n' + + '</div>'; + + const SUGGESTION_HTML = '<li>\n' + + ' <button type="button" value="1"></button>\n' + + ' <button type="button" value="0"><i class="icon-"></i></button>\n' + + '</li>'; + + Icinga.Behaviors = Icinga.Behaviors || {}; + + /** + * Icinga DB Migration behavior. + * + * @param icinga {Icinga} The current Icinga Object + */ + class Migrate extends Icinga.EventListener { + constructor(icinga) { + super(icinga); + + this.knownMigrations = {}; + this.knownBackendSupport = {}; + this.urlMigrationReadyState = null; + this.backendSupportReadyState = null; + this.searchMigrationReadyState = null; + this.backendSupportRelated = {}; + this.$popup = null; + + // Some persistence, we don't want to annoy our users too much + this.storage = Icinga.Storage.BehaviorStorage('icingadb.migrate'); + this.tempStorage = Icinga.Storage.BehaviorStorage('icingadb.migrate'); + this.tempStorage.setBackend(window.sessionStorage); + this.previousMigrations = {}; + + // We don't want to ask the server to migrate non-monitoring urls + this.isMonitoringUrl = new RegExp('^' + icinga.config.baseUrl + '/monitoring/'); + + this.on('rendered', this.onRendered, this); + this.on('close-column', this.onColumnClose, this); + this.on('click', '#migrate-popup button.close', this.onClose, this); + this.on('click', '#migrate-popup li button', this.onDecision, this); + this.on('click', '#migrate-popup .minimizer', this.onHandleClicked, this); + this.storage.onChange('minimized', this.onMinimized, this); + } + + update(data) { + if (data !== 'bogus') { + return; + } + + $.each(this.backendSupportRelated, (id, _) => { + let $container = $('#' + id); + let req = this.icinga.loader.loadUrl($container.data('icingaUrl'), $container); + req.addToHistory = false; + req.scripted = true; + }); + } + + onRendered(event) { + var _this = event.data.self; + var $target = $(event.target); + + if (_this.tempStorage.get('closed') || $('#layout.fullscreen-layout').length) { + // Don't bother in case the user closed the popup or we're in fullscreen + return; + } + + if (!$target.is('#main > .container')) { + if ($target.is('#main .container')) { + var attrUrl = $target.attr('data-icinga-url'); + var dataUrl = $target.data('icingaUrl'); + if (!! attrUrl && attrUrl !== dataUrl) { + // Search urls are redirected, update any migration suggestions + _this.prepareMigration($target); + return; + } + } + + // We are else really only interested in top-level containers + return; + } + + var $dashboard = $target.children('.dashboard'); + if ($dashboard.length) { + // After a page load dashlets have no id as `renderContentToContainer()` didn't ran yet + _this.icinga.ui.assignUniqueContainerIds(); + + $target = $dashboard.children('.container'); + } + + _this.prepareMigration($target); + } + + prepareMigration($target) { + let monitoringUrls = {}; + let searchUrls = {}; + let modules = {} + + $target.each((_, container) => { + let $container = $(container); + let href = decodeURIComponent($container.data('icingaUrl')); + let containerId = $container.attr('id'); + + if (!!href) { + if ( + typeof this.previousMigrations[containerId] !== 'undefined' + && this.previousMigrations[containerId] === href + ) { + delete this.previousMigrations[containerId]; + } else { + if (href.match(this.isMonitoringUrl)) { + monitoringUrls[containerId] = href; + } else if ($container.find('[data-enrichment-type="search-bar"]').length) { + searchUrls[containerId] = href; + } + } + } + + let moduleName = $container.data('icingaModule'); + if (!! moduleName && moduleName !== 'default' && moduleName !== 'monitoring' && moduleName !== 'icingadb') { + modules[containerId] = moduleName; + } + }); + + if (Object.keys(monitoringUrls).length) { + this.setUrlMigrationReadyState(false); + this.migrateUrls(monitoringUrls, 'monitoring'); + } else { + this.setUrlMigrationReadyState(null); + } + + if (Object.keys(searchUrls).length) { + this.setSearchMigrationReadyState(false); + this.migrateUrls(searchUrls, 'search'); + } else { + this.setSearchMigrationReadyState(null); + } + + if (Object.keys(modules).length) { + this.setBackendSupportReadyState(false); + this.prepareBackendCheckboxForm(modules); + } else { + this.setBackendSupportReadyState(null); + } + + if ( + this.urlMigrationReadyState === null + && this.backendSupportReadyState === null + && this.searchMigrationReadyState === null + ) { + this.cleanupPopup(); + } + } + + onColumnClose(event) { + var _this = event.data.self; + _this.Popup().find('.suggestion-area > ul li').each(function () { + var $suggestion = $(this); + var suggestionUrl = $suggestion.data('containerUrl'); + var $container = $('#' + $suggestion.data('containerId')); + + var containerUrl = ''; + if ($container.length) { + containerUrl = decodeURIComponent($container.data('icingaUrl')); + } + + if (suggestionUrl !== containerUrl) { + var $newContainer = $('#main > .container').filter(function () { + return decodeURIComponent($(this).data('icingaUrl')) === suggestionUrl; + }); + if ($newContainer.length) { + // Container moved + $suggestion.attr('id', 'suggest-' + $newContainer.attr('id')); + $suggestion.data('containerId', $newContainer.attr('id')); + } + } + }); + + let backendSupportRelated = { ..._this.backendSupportRelated }; + $.each(backendSupportRelated, (id, module) => { + let $container = $('#' + id); + if (! $container.length || $container.data('icingaModule') !== module) { + let $newContainer = $('#main > .container').filter(function () { + return $(this).data('icingaModule') === module; + }); + if ($newContainer.length) { + _this.backendSupportRelated[$newContainer.attr('id')] = module; + } + + delete _this.backendSupportRelated[id]; + } + }); + + _this.cleanupPopup(); + } + + onClose(event) { + var _this = event.data.self; + _this.tempStorage.set('closed', true); + _this.hidePopup(); + } + + onDecision(event) { + var _this = event.data.self; + var $button = $(event.target).closest('button'); + var $suggestion = $button.parent(); + var $container = $('#' + $suggestion.data('containerId')); + var containerUrl = decodeURIComponent($container.data('icingaUrl')); + + if ($button.attr('value') === '1') { + // Yes + var newHref = _this.knownMigrations[containerUrl]; + _this.icinga.loader.loadUrl(newHref, $container); + + _this.previousMigrations[$suggestion.data('containerId')] = containerUrl; + + if ($container.parent().is('.dashboard')) { + $container.find('h1 a').attr('href', _this.icinga.utils.removeUrlParams(newHref, ['showCompact'])); + } + } else { + // No + _this.knownMigrations[containerUrl] = false; + } + + if (_this.Popup().find('li').length === 1 && ! _this.Popup().find('#setAsBackendForm').length) { + _this.hidePopup(function () { + // Let the transition finish first, looks cleaner + $suggestion.remove(); + }); + } else { + $suggestion.remove(); + } + } + + onHandleClicked(event) { + var _this = event.data.self; + if (_this.togglePopup()) { + _this.storage.set('minimized', true); + } else { + _this.storage.remove('minimized'); + } + } + + onMinimized(isMinimized, oldValue) { + if (isMinimized && isMinimized !== oldValue && this.isShown()) { + this.minimizePopup(); + } + } + + migrateUrls(urls, type) { + var _this = this, + containerIds = [], + containerUrls = []; + + $.each(urls, function (containerId, containerUrl) { + if (typeof _this.knownMigrations[containerUrl] === 'undefined') { + containerUrls.push(containerUrl); + containerIds.push(containerId); + } + }); + + let endpoint, changeCallback; + if (type === 'monitoring') { + endpoint = 'monitoring-url'; + changeCallback = this.changeUrlMigrationReadyState.bind(this); + } else { + endpoint = 'search-url'; + changeCallback = this.changeSearchMigrationReadyState.bind(this); + } + + if (containerUrls.length) { + var req = $.ajax({ + context: this, + type: 'post', + url: this.icinga.config.baseUrl + '/icingadb/migrate/' + endpoint, + headers: {'Accept': 'application/json'}, + contentType: 'application/json', + data: JSON.stringify(containerUrls) + }); + + req.urls = urls; + req.suggestionType = type; + req.urlIndexToContainerId = containerIds; + req.done(this.processUrlMigrationResults); + req.always(() => changeCallback(true)); + } else { + // All urls have already been migrated once, show popup immediately + this.addSuggestions(urls, type); + changeCallback(true); + } + } + + processUrlMigrationResults(data, textStatus, req) { + var _this = this; + var result, containerId; + + if (data.status === 'success') { + result = data.data; + } else { // if (data.status === 'fail') + result = data.data.result; + + $.each(data.data.errors, function (k, error) { + _this.icinga.logger.error('[Migrate] Erroneous url "' + k + '": ' + error[0] + '\n' + error[1]); + }); + } + + $.each(result, function (i, migratedUrl) { + containerId = req.urlIndexToContainerId[i]; + _this.knownMigrations[req.urls[containerId]] = migratedUrl; + }); + + this.addSuggestions(req.urls, req.suggestionType); + } + + prepareBackendCheckboxForm(modules) { + let containerIds = []; + let moduleNames = []; + + $.each(modules, (id, module) => { + if (typeof this.knownBackendSupport[module] === 'undefined') { + containerIds.push(id); + moduleNames.push(module); + } + }); + + if (moduleNames.length) { + let req = $.ajax({ + context : this, + type : 'post', + url : this.icinga.config.baseUrl + '/icingadb/migrate/backend-support', + headers : { 'Accept': 'application/json' }, + contentType : 'application/json', + data : JSON.stringify(moduleNames) + }); + + req.modules = modules; + req.moduleIndexToContainerId = containerIds; + req.done(this.processBackendSupportResults); + req.always(() => this.changeBackendSupportReadyState(true)); + } else { + // All modules have already been checked once, show popup immediately + this.setupBackendCheckboxForm(modules); + this.changeBackendSupportReadyState(true); + } + } + + processBackendSupportResults(data, textStatus, req) { + let result = data.data; + + $.each(result, (i, state) => { + let containerId = req.moduleIndexToContainerId[i]; + this.knownBackendSupport[req.modules[containerId]] = state; + }); + + this.setupBackendCheckboxForm(req.modules); + } + + setupBackendCheckboxForm(modules) { + let supportedModules = {}; + + $.each(modules, (id, module) => { + if (this.knownBackendSupport[module]) { + supportedModules[id] = module; + } + }); + + if (Object.keys(supportedModules).length) { + this.backendSupportRelated = { ...this.backendSupportRelated, ...supportedModules }; + + let req = $.ajax({ + context : this, + type : 'get', + url : this.icinga.config.baseUrl + '/icingadb/migrate/checkbox-state?showCompact' + }); + + req.done(this.setCheckboxState); + } + } + + setCheckboxState(html, textStatus, req) { + let $form = this.Popup().find('.suggestion-area > #setAsBackendForm'); + if (! $form.length) { + $form = $(html); + $form.attr('data-base-target', 'migrate-popup-backend-submit-blackhole'); + $form.append('<div id="migrate-popup-backend-submit-blackhole"></div>'); + + this.Popup().find('.monitoring-migration-suggestions').before($form); + } else { + let $newForm = $(html); + $form.find('[name=backend]').prop('checked', $newForm.find('[name=backend]').is(':checked')); + } + + this.showPopup(); + } + + addSuggestions(urls, type) { + var where; + if (type === 'monitoring') { + where = '.monitoring-migration-suggestions'; + } else { + where = '.search-migration-suggestions'; + } + + var _this = this, + hasSuggestions = false, + $ul = this.Popup().find('.suggestion-area > ul' + where); + $.each(urls, function (containerId, containerUrl) { + // No urls for which the user clicked "No" or an error occurred and only migrated urls please + if (_this.knownMigrations[containerUrl] !== false && _this.knownMigrations[containerUrl] !== containerUrl) { + var $container = $('#' + containerId); + + var $suggestion = $ul.find('li#suggest-' + containerId); + if ($suggestion.length) { + if ($suggestion.data('containerUrl') === containerUrl) { + // There's already a suggestion for this exact container and url + hasSuggestions = true; + return; + } + + $suggestion.data('containerUrl', containerUrl); + } else { + $suggestion = $(SUGGESTION_HTML); + $suggestion.attr('id', 'suggest-' + containerId); + $suggestion.data('containerId', containerId); + $suggestion.data('containerUrl', containerUrl); + $ul.append($suggestion); + } + + hasSuggestions = true; + + var title; + if ($container.data('icingaTitle')) { + title = $container.data('icingaTitle').split(' :: ').slice(0, -1).join(' :: '); + } else if ($container.parent().is('.dashboard')) { + title = $container.find('h1 a').text(); + } else { + title = $container.find('.tabs li.active a').text(); + } + + $suggestion.find('button:first-of-type').text(title); + } + }); + + if (hasSuggestions) { + this.showPopup(); + if (type === 'search') { + this.maximizePopup(); + } + } + } + + cleanupSuggestions() { + var _this = this, + toBeRemoved = []; + this.Popup().find('li').each(function () { + var $suggestion = $(this); + var $container = $('#' + $suggestion.data('containerId')); + var containerUrl = decodeURIComponent($container.data('icingaUrl')); + if ( + // Unknown url, yet + typeof _this.knownMigrations[containerUrl] === 'undefined' + // User doesn't want to migrate + || _this.knownMigrations[containerUrl] === false + // Already migrated or no migration necessary + || containerUrl === _this.knownMigrations[containerUrl] + // The container URL changed + || containerUrl !== $suggestion.data('containerUrl') + ) { + toBeRemoved.push($suggestion); + } + }); + + return toBeRemoved; + } + + cleanupBackendForm() { + let $form = this.Popup().find('#setAsBackendForm'); + if (! $form.length) { + return false; + } + + let stillRelated = {}; + $.each(this.backendSupportRelated, (id, module) => { + let $container = $('#' + id); + if ($container.length && $container.data('icingaModule') === module) { + stillRelated[id] = module; + } + }); + + this.backendSupportRelated = stillRelated; + + if (Object.keys(stillRelated).length) { + return true; + } + + return $form; + } + + cleanupPopup() { + let toBeRemoved = this.cleanupSuggestions(); + let hasBackendForm = this.cleanupBackendForm(); + + if (hasBackendForm !== true && this.Popup().find('li').length === toBeRemoved.length) { + this.hidePopup(() => { + // Let the transition finish first, looks cleaner + $.each(toBeRemoved, function (_, $suggestion) { + $suggestion.remove(); + }); + + if (typeof hasBackendForm === 'object') { + hasBackendForm.remove(); + } + }); + } else { + $.each(toBeRemoved, function (_, $suggestion) { + $suggestion.remove(); + }); + + if (typeof hasBackendForm === 'object') { + hasBackendForm.remove(); + } + + // Let showPopup() handle the automatic minimization in case all search suggestions have been removed + this.showPopup(); + } + } + + showPopup() { + var $popup = this.Popup(); + if (this.storage.get('minimized') && ! this.forceFullyMaximized()) { + if (this.isShown()) { + this.minimizePopup(); + } else { + $popup.addClass('active minimized hidden'); + } + } else { + $popup.addClass('active'); + } + } + + hidePopup(after) { + this.Popup().removeClass('active minimized hidden'); + + if (typeof after === 'function') { + setTimeout(after, ANIMATION_LENGTH); + } + } + + isShown() { + return this.Popup().is('.active'); + } + + minimizePopup() { + var $popup = this.Popup(); + $popup.addClass('minimized'); + setTimeout(function () { + $popup.addClass('hidden'); + }, ANIMATION_LENGTH); + } + + maximizePopup() { + this.Popup().removeClass('minimized hidden'); + } + + forceFullyMaximized() { + return this.Popup().find('.search-migration-suggestions:not(:empty)').length > 0; + } + + togglePopup() { + if (this.Popup().is('.minimized')) { + this.maximizePopup(); + return false; + } else { + this.minimizePopup(); + return true; + } + } + + setUrlMigrationReadyState(state) { + this.urlMigrationReadyState = state; + } + + changeUrlMigrationReadyState(state) { + this.setUrlMigrationReadyState(state); + + if (this.backendSupportReadyState !== false && this.searchMigrationReadyState !== false) { + this.searchMigrationReadyState = null; + this.backendSupportReadyState = null; + this.urlMigrationReadyState = null; + this.cleanupPopup(); + } + } + + setSearchMigrationReadyState(state) { + this.searchMigrationReadyState = state; + } + + changeSearchMigrationReadyState(state) { + this.setSearchMigrationReadyState(state); + + if (this.backendSupportReadyState !== false && this.urlMigrationReadyState !== false) { + this.searchMigrationReadyState = null; + this.backendSupportReadyState = null; + this.urlMigrationReadyState = null; + this.cleanupPopup(); + } + } + + setBackendSupportReadyState(state) { + this.backendSupportReadyState = state; + } + + changeBackendSupportReadyState(state) { + this.setBackendSupportReadyState(state); + + if (this.urlMigrationReadyState !== false && this.searchMigrationReadyState !== false) { + this.searchMigrationReadyState = null; + this.backendSupportReadyState = null; + this.urlMigrationReadyState = null; + this.cleanupPopup(); + } + } + + Popup() { + // Node.contains() is used due to `?renderLayout` + if (this.$popup === null || ! document.body.contains(this.$popup[0])) { + $('#layout').append($(POPUP_HTML)); + this.$popup = $('#migrate-popup'); + } + + return this.$popup; + } + } + + Icinga.Behaviors.Migrate = Migrate; + +})(Icinga, jQuery); diff --git a/public/js/progress-bar.js b/public/js/progress-bar.js new file mode 100644 index 0000000..be24f1c --- /dev/null +++ b/public/js/progress-bar.js @@ -0,0 +1,110 @@ +(function (Icinga) { + + "use strict"; + + class ProgressBar extends Icinga.EventListener { + constructor(icinga) + { + super(icinga); + + /** + * Frame update threshold. If it reaches zero, the view is updated + * + * Currently, only every third frame is updated. + * + * @type {number} + */ + this.frameUpdateThreshold = 3; + + /** + * Threshold at which animations get smoothed out (in milliseconds) + * + * @type {number} + */ + this.smoothUpdateThreshold = 250; + + this.on('rendered', '#main > .container', this.onRendered, this); + } + + onRendered(event) + { + const _this = event.data.self; + const container = event.target; + + container.querySelectorAll('[data-animate-progress]').forEach(progress => { + const frequency = ( + (Number(progress.dataset.endTime) - Number(progress.dataset.startTime) + ) * 1000) / progress.parentElement.offsetWidth; + + _this.updateProgress( + now => _this.animateProgress(progress, now), frequency); + }); + } + + animateProgress(progress, now) + { + if (! progress.isConnected) { + return false; // Exit early if the node is removed from the DOM + } + + const durationScale = 100; + + const startTime = Number(progress.dataset.startTime); + const endTime = Number(progress.dataset.endTime); + const duration = endTime - startTime; + const end = new Date(endTime * 1000.0); + + let leftNow = durationScale * (1 - (end - now) / (duration * 1000.0)); + if (leftNow > durationScale) { + leftNow = durationScale; + } else if (leftNow < 0) { + leftNow = 0; + } + + const switchAfter = Number(progress.dataset.switchAfter); + if (! isNaN(switchAfter)) { + const switchClass = progress.dataset.switchClass; + const switchAt = new Date((startTime * 1000.0) + (switchAfter * 1000.0)); + if (now < switchAt) { + progress.classList.add(switchClass); + } else if (progress.classList.contains(switchClass)) { + progress.classList.remove(switchClass); + } + } + + const bar = progress.querySelector(':scope > .bar'); + bar.style.width = leftNow + '%'; + + return leftNow !== durationScale; + } + + updateProgress(callback, frequency, now = null) + { + if (now === null) { + now = new Date(); + } + + if (! callback(now)) { + return; + } + + if (frequency < this.smoothUpdateThreshold) { + let counter = this.frameUpdateThreshold; + const onNextFrame = timeSinceOrigin => { + if (--counter === 0) { + this.updateProgress(callback, frequency, new Date(performance.timeOrigin + timeSinceOrigin)); + } else { + requestAnimationFrame(onNextFrame); + } + }; + requestAnimationFrame(onNextFrame); + } else { + setTimeout(() => this.updateProgress(callback, frequency), frequency); + } + } + } + + Icinga.Behaviors = Icinga.Behaviors || {}; + + Icinga.Behaviors.ProgressBar = ProgressBar; +})(Icinga); |