Merge pull request #4884 from Icinga/enhance-collapsible-js

Enhance collapsible js
This commit is contained in:
Johannes Meyer 2022-10-17 11:29:59 +02:00 committed by GitHub
commit 69929b799b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 612 additions and 426 deletions

View File

@ -272,7 +272,7 @@ class RoleForm extends RepositoryForm
$moduleName . '_header',
[
'decorators' => ['ViewHelper'],
'value' => '<h3>'
'value' => '<summary class="collapsible-control">'
. '<span>' . ($moduleName !== 'application'
? sprintf('%s <em>%s</em>', $moduleName, $this->translate('Module'))
: 'Icinga Web 2'
@ -285,18 +285,20 @@ class RoleForm extends RepositoryForm
: ''
)
. '</span>'
. '</h3>'
. new Icon('angles-down', ['class' => 'collapse-icon'])
. new Icon('angles-left', ['class' => 'expand-icon'])
. '</summary>'
]
);
$this->addDisplayGroup($elements, $moduleName . '_elements', [
'decorators' => [
'FormElements',
['Fieldset', [
'class' => 'collapsible',
'data-toggle-element' => 'h3',
'data-visible-height' => 0
]]
['HtmlTag', [
'tag' => 'details',
'class' => 'collapsible'
]],
['Fieldset']
]
]);
}

View File

@ -54,7 +54,7 @@ class PrivilegeAudit extends BaseHtmlElement
}
}
$header = new HtmlElement('div');
$header = new HtmlElement('summary');
if (! empty($refusedBy)) {
$header->add([
new Icon('times-circle', ['class' => 'refused']),
@ -171,15 +171,25 @@ class PrivilegeAudit extends BaseHtmlElement
]));
}
if (empty($rolePaths)) {
return [
empty($refusedBy) ? (empty($grantedBy) ? null : true) : false,
new HtmlElement(
'div',
Attributes::create(['class' => 'inheritance-paths']),
$header->setTag('div')
)
];
}
return [
empty($refusedBy) ? (empty($grantedBy) ? null : true) : false,
HtmlElement::create('div', [
'class' => [empty($rolePaths) ? null : 'collapsible', 'inheritance-paths'],
'data-toggle-element' => '.collapsible-control',
HtmlElement::create('details', [
'class' => ['collapsible', 'inheritance-paths'],
'data-no-persistence' => true,
'data-visible-height' => 0
'open' => getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
], [
empty($rolePaths) ? $header : $header->addAttributes(['class' => 'collapsible-control']),
$header->addAttributes(['class' => 'collapsible-control']),
$rolePaths
])
];
@ -202,7 +212,7 @@ class PrivilegeAudit extends BaseHtmlElement
}
}
$header = new HtmlElement('div');
$header = new HtmlElement('summary');
if (! empty($restrictedBy)) {
$header->add([
new Icon('filter', ['class' => 'restricted']),
@ -277,17 +287,27 @@ class PrivilegeAudit extends BaseHtmlElement
]);
}
if (empty($roles)) {
return [
! empty($restrictedBy),
new HtmlElement(
'div',
Attributes::create(['class' => 'restrictions']),
$header->setTag('div')
)
];
}
return [
! empty($restrictedBy),
new HtmlElement(
'div',
'details',
Attributes::create([
'class' => [empty($roles) ? null : 'collapsible', 'restrictions'],
'data-toggle-element' => '.collapsible-control',
'class' => ['collapsible', 'restrictions'],
'data-no-persistence' => true,
'data-visible-height' => 0
'open' => getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
]),
empty($roles) ? $header : $header->addAttributes(['class' => 'collapsible-control']),
$header->addAttributes(['class' => 'collapsible-control']),
new HtmlElement('ul', null, ...$roles)
)
];
@ -301,39 +321,46 @@ class PrivilegeAudit extends BaseHtmlElement
$this->addHtml(new HtmlElement(
'li',
Attributes::create([
'class' => 'collapsible',
'data-toggle-element' => 'h3',
'data-visible-height' => 0
]),
null,
new HtmlElement(
'h3',
null,
new HtmlElement('span', null, Text::create(t('Administrative Privileges'))),
HtmlElement::create(
'span',
['class' => 'audit-preview'],
$wildcardState || $unrestrictedState
? new Icon('check-circle', ['class' => 'granted'])
: null
)
),
new HtmlElement(
'ol',
Attributes::create(['class' => 'privilege-list']),
'details',
Attributes::create([
'class' => ['collapsible', 'privilege-section'],
'open' => ($wildcardState || $unrestrictedState) && getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
]),
new HtmlElement(
'li',
null,
HtmlElement::create('p', ['class' => 'privilege-label'], t('Administrative Access')),
HtmlElement::create('div', ['class' => 'spacer']),
$wildcardAudit
'summary',
Attributes::create(['class' => [
'collapsible-control', // Helps JS, improves performance a bit
]]),
new HtmlElement('span', null, Text::create(t('Administrative Privileges'))),
HtmlElement::create(
'span',
['class' => 'audit-preview'],
$wildcardState || $unrestrictedState
? new Icon('check-circle', ['class' => 'granted'])
: null
),
new Icon('angles-down', ['class' => 'collapse-icon']),
new Icon('angles-left', ['class' => 'expand-icon'])
),
new HtmlElement(
'li',
null,
HtmlElement::create('p', ['class' => 'privilege-label'], t('Unrestricted Access')),
HtmlElement::create('div', ['class' => 'spacer']),
$unrestrictedAudit
'ol',
Attributes::create(['class' => 'privilege-list']),
new HtmlElement(
'li',
null,
HtmlElement::create('p', ['class' => 'privilege-label'], t('Administrative Access')),
HtmlElement::create('div', ['class' => 'spacer']),
$wildcardAudit
),
new HtmlElement(
'li',
null,
HtmlElement::create('p', ['class' => 'privilege-label'], t('Unrestricted Access')),
HtmlElement::create('div', ['class' => 'spacer']),
$unrestrictedAudit
)
)
)
));
@ -420,30 +447,38 @@ class PrivilegeAudit extends BaseHtmlElement
$label = [$source, ' ', HtmlElement::create('em', null, t('Module'))];
}
$this->addHtml(HtmlElement::create('li', [
'class' => 'collapsible',
'data-toggle-element' => 'h3',
'data-visible-height' => 0
], [
new HtmlElement(
'h3',
null,
HtmlElement::create('span', null, $label),
HtmlElement::create('span', ['class' => 'audit-preview'], [
$anythingGranted ? new Icon('check-circle', ['class' => 'granted']) : null,
$anythingRefused ? new Icon('times-circle', ['class' => 'refused']) : null,
$anythingRestricted ? new Icon('filter', ['class' => 'restricted']) : null
])
),
$permissionList->isEmpty() ? null : [
HtmlElement::create('h4', null, t('Permissions')),
$permissionList
],
$restrictionList->isEmpty() ? null : [
HtmlElement::create('h4', null, t('Restrictions')),
$restrictionList
]
]));
$this->addHtml(new HtmlElement(
'li',
null,
HtmlElement::create('details', [
'class' => ['collapsible', 'privilege-section'],
'open' => ($anythingGranted || $anythingRefused || $anythingRestricted)
&& getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
], [
new HtmlElement(
'summary',
Attributes::create(['class' => [
'collapsible-control', // Helps JS, improves performance a bit
]]),
HtmlElement::create('span', null, $label),
HtmlElement::create('span', ['class' => 'audit-preview'], [
$anythingGranted ? new Icon('check-circle', ['class' => 'granted']) : null,
$anythingRefused ? new Icon('times-circle', ['class' => 'refused']) : null,
$anythingRestricted ? new Icon('filter', ['class' => 'restricted']) : null
]),
new Icon('angles-down', ['class' => 'collapse-icon']),
new Icon('angles-left', ['class' => 'expand-icon'])
),
$permissionList->isEmpty() ? null : [
HtmlElement::create('h4', null, t('Permissions')),
$permissionList
],
$restrictionList->isEmpty() ? null : [
HtmlElement::create('h4', null, t('Restrictions')),
$restrictionList
]
])
));
}
}

View File

@ -760,7 +760,7 @@ form.instance-features span.description, form.object-features span.description {
}
}
&.can-collapse thead th > span {
&[data-can-collapse] thead th > span {
:nth-child(1) {
display: none;
}

View File

@ -19,16 +19,17 @@
list-style-type: none;
}
h3 {
.privilege-section > summary {
font-weight: @font-weight-bold;
border-bottom: 1px solid @gray-light;
}
h3 em,
.privilege-section > summary em,
.previews em,
.privilege-label em {
color: @text-color-light;
}
h3 em {
.privilege-section > summary em {
font-weight: normal;
}
.privilege-label em {
@ -144,10 +145,6 @@
padding: 0;
}
> li:not(.collapsed) {
margin-bottom: 2em;
}
.flex-overflow,
.privilege-list > li,
.inheritance-paths > ol {
@ -165,15 +162,30 @@
// https://codepen.io/unthinkingly/pen/XMwJLG
overflow: hidden;
}
> details:last-child {
// The overflow above cuts off the outline of the summary otherwise
margin: -4px;
padding: 4px;
}
}
h3 {
.privilege-section {
&:not(.collapsed) {
margin-bottom: 2em;
}
}
.privilege-section > summary {
display: flex;
align-items: baseline;
font-size: 1.167em;
margin: 0.556em 0 0.333em;
> :first-child {
flex: 3 1 auto;
min-width: 20em;
max-width: 40em / 1.167em; // privilege label width + spacer width / h3 font-size
max-width: 40em / 1.167em; // privilege label width + spacer width / summary font-size
}
.audit-preview {
@ -181,7 +193,7 @@
.icon:before {
width: 1.25em;
font-size: 1.25em / 1.167em; // privilege state icon font-size / h3 font-size
font-size: 1.25em / 1.167em; // privilege state icon font-size / summary font-size
}
}
@ -213,7 +225,7 @@
.restrictions {
flex: 1 1 auto;
> div {
> summary {
line-height: 1;
overflow: hidden;
@ -325,7 +337,7 @@
#layout.minimal-layout,
#layout.poor-layout {
.privilege-audit {
h3 > :first-child {
.privilege-section > summary > :first-child {
flex-grow: 99;
}
@ -346,27 +358,6 @@
.privilege-audit .collapsible {
.collapsible-control {
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.collapsible-control:after {
content: "\f103";
display: inline-block;
font-family: 'ifont';
font-weight: normal;
padding: 0 .25em;
margin-right: .25em;
width: 1em;
opacity: .6;
float: right;
}
&.collapsed .collapsible-control:after {
content: "\e87a";
.user-select(none);
}
}

View File

@ -194,6 +194,10 @@
html {
box-sizing: border-box;
}
details > * {
// children somehow default to content-box no matter the inheritance
box-sizing: border-box;
}
*,
*:before,
*:after {

View File

@ -303,7 +303,7 @@ a:hover > .icon-cancel {
display: none;
}
.collapsible-control {
.collapsible + .collapsible-control {
position: relative;
z-index: 1;
@ -334,33 +334,39 @@ a:hover > .icon-cancel {
}
}
.collapsible.can-collapse:not(.collapsed) + .collapsible-control button {
> i.expand-icon {
.collapsible[data-can-collapse]:not(.collapsed) + .collapsible-control button,
.collapsible[data-can-collapse]:not(.collapsed) > .collapsible-control,
details.collapsible[open] + .collapsible-control button,
details.collapsible[open] > .collapsible-control {
i.expand-icon {
display: none;
}
> i.collapse-icon {
display: unset;
i.collapse-icon {
display: inline;
}
}
.collapsible.collapsed + .collapsible-control button {
> i.expand-icon {
display: unset;
.collapsible.collapsed + .collapsible-control button,
.collapsible.collapsed > .collapsible-control,
details.collapsible:not([open]) + .collapsible-control button,
details.collapsible:not([open]) > .collapsible-control {
i.expand-icon {
display: inline;
}
> i.collapse-icon {
i.collapse-icon {
display: none;
}
}
// Collapsibles
.collapsible.collapsed {
.collapsible.collapsed:not(details) {
overflow: hidden;
}
.collapsible.collapsed:not([data-toggle-element]) {
.collapsible.collapsed:not([data-toggle-element], details) {
position: relative;
&:after {

View File

@ -255,10 +255,30 @@ form.role-form {
display: inline-block;
}
h3 {
summary {
border-bottom: 1px solid @gray-light;
.user-select(none);
cursor: pointer;
font-weight: @font-weight-bold;
margin: 0.556em 0 0.333em;
font-size: 1.167em;
display: flex;
align-items: baseline;
.privilege-preview {
flex: 1 1 auto;
}
> :first-child {
display: inline-block;
width: 20em / 1.167em; // element label width / h3 font-size
width: 20em / 1.167em; // element label width / summary font-size
}
> :nth-last-child(1),
> :nth-last-child(2) {
font-size: .75em;
opacity: .6;
}
.privilege-preview .icon {
@ -276,12 +296,8 @@ form.role-form {
}
}
fieldset.collapsible {
border: none;
padding: 0;
margin: 0;
h3 em {
.collapsible {
summary em {
font-size: .857em;
font-weight: normal;
color: @text-color-light;
@ -309,33 +325,6 @@ form.role-form {
}
}
}
.collapsible-control {
border-bottom: 1px solid @gray-light;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.collapsible-control:after {
content: "\f103";
display: inline-block;
font-family: 'ifont';
font-weight: normal;
padding: 0 .25em;
margin-right: .25em;
width: 1em;
opacity: .6;
float: right;
}
&.collapsed .collapsible-control:after {
content: "\e87a";
}
}
}

View File

@ -1,322 +1,463 @@
/*! Icinga Web 2 | (c) 2019 Icinga GmbH | GPLv2+ */
;(function(Icinga, $) {
;(function(Icinga) {
'use strict';
Icinga.Behaviors = Icinga.Behaviors || {};
let $ = window.$;
try {
$ = require('icinga/icinga-php-library/notjQuery');
} catch (e) {
console.warn('[Collapsible] notjQuery unavailable. Using jQuery for now');
}
/**
* Behavior for collapsible containers.
*
* @param icinga Icinga The current Icinga Object
*/
var Collapsible = function(icinga) {
Icinga.EventListener.call(this, icinga);
class Collapsible extends Icinga.EventListener {
constructor(icinga) {
super(icinga);
this.on('layout-change', this.onLayoutChange, this);
this.on('rendered', '#main > .container, #modal-content', this.onRendered, this);
this.on('click', '.collapsible + .collapsible-control, .collapsible > .collapsible-control',
this.onControlClicked, this);
this.on('layout-change', this.onLayoutChange, this);
this.on('rendered', '#main > .container, #modal-content', this.onRendered, this);
this.on('click', '.collapsible + .collapsible-control, .collapsible .collapsible-control',
this.onControlClicked, this);
this.icinga = icinga;
this.defaultVisibleRows = 2;
this.defaultVisibleHeight = 36;
this.icinga = icinga;
this.defaultVisibleRows = 2;
this.defaultVisibleHeight = 36;
this.state = new Icinga.Storage.StorageAwareMap.withStorage(
Icinga.Storage.BehaviorStorage('collapsible'),
'expanded'
)
.on('add', this.onExpand, this)
.on('delete', this.onCollapse, this);
};
Collapsible.prototype = new Icinga.EventListener();
/**
* Initializes all collapsibles. Triggered on rendering of a container.
*
* @param event Event The `onRender` event triggered by the rendered container
*/
Collapsible.prototype.onRendered = function(event) {
var _this = event.data.self;
var toCollapse = [];
$.each(event.target.querySelectorAll('.collapsible:not(.can-collapse)'), function (_, collapsible) {
// Assumes that any newly rendered elements are expanded
if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) {
toCollapse.push([collapsible, _this.calculateCollapsedHeight(collapsible)]);
}
});
// Elements are all collapsed in a row now, after height calculations are done.
// This avoids reflows since instantly collapsing an element will cause one if
// the height of the next element is being calculated.
for (var i = 0; i < toCollapse.length; i++) {
_this.collapse(toCollapse[i][0], toCollapse[i][1]);
this.state = new Icinga.Storage.StorageAwareMap.withStorage(
Icinga.Storage.BehaviorStorage('collapsible'),
'expanded'
)
.on('add', this.onExpand, this)
.on('delete', this.onCollapse, this);
}
};
/**
* Updates all collapsibles.
*
* @param event Event The `layout-change` event triggered by window resizing or column changes
*/
Collapsible.prototype.onLayoutChange = function(event) {
var _this = event.data.self;
var toCollapse = [];
/**
* Initializes all collapsibles. Triggered on rendering of a container.
*
* @param event Event The `onRender` event triggered by the rendered container
*/
onRendered(event) {
let _this = event.data.self,
toCollapse = [],
toExpand = [];
$.each(document.querySelectorAll('.collapsible'), function (_, collapsible) {
if (collapsible.matches('.can-collapse')) {
if (! _this.canCollapse(collapsible)) {
var toggleSelector = collapsible.dataset.toggleElement;
if (! toggleSelector) {
$(collapsible).next('.collapsible-control').remove();
event.target.querySelectorAll('.collapsible').forEach(collapsible => {
// Assumes that any newly rendered elements are expanded
if (! ('canCollapse' in collapsible.dataset) && _this.canCollapse(collapsible)) {
if (_this.setupCollapsible(collapsible)) {
toCollapse.push([collapsible, _this.calculateCollapsedHeight(collapsible)]);
} else if (_this.isDetails(collapsible)) {
// Except if it's a <details> element, which may not be expanded by default
toExpand.push(collapsible);
}
collapsible.classList.remove('can-collapse');
_this.expand(collapsible);
}
} else if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) {
// It's expanded but shouldn't
toCollapse.push([collapsible, _this.calculateCollapsedHeight(collapsible)]);
});
// Elements are all collapsed in a row now, after height calculations are done.
// This avoids reflows since instantly collapsing an element will cause one if
// the height of the next element is being calculated.
for (const collapseInfo of toCollapse) {
_this.collapse(collapseInfo[0], collapseInfo[1]);
}
});
setTimeout(function () {
for (var i = 0; i < toCollapse.length; i++) {
_this.collapse(toCollapse[i][0], toCollapse[i][1]);
}
}, 0);
};
/**
* A collapsible got expanded in another window, try to apply this here as well
*
* @param {string} collapsiblePath
*/
Collapsible.prototype.onExpand = function(collapsiblePath) {
var collapsible = $(collapsiblePath)[0];
if (collapsible && collapsible.matches('.can-collapse')) {
this.expand(collapsible);
}
};
/**
* A collapsible got collapsed in another window, try to apply this here as well
*
* @param {string} collapsiblePath
*/
Collapsible.prototype.onCollapse = function(collapsiblePath) {
var collapsible = $(collapsiblePath)[0];
if (collapsible && this.canCollapse(collapsible)) {
this.collapse(collapsible, this.calculateCollapsedHeight(collapsible));
}
};
/**
* Event handler for toggling collapsibles. Switches the collapsed state of the respective container.
*
* @param event Event The `onClick` event triggered by the clicked collapsible-control element
*/
Collapsible.prototype.onControlClicked = function(event) {
var _this = event.data.self;
var $target = $(event.currentTarget);
var collapsible = $target.prev('.collapsible')[0];
if (! collapsible) {
collapsible = $target.parent('.collapsible')[0];
}
if (! collapsible) {
_this.icinga.logger.error(
'[Collapsible] Collapsible control has no associated .collapsible: ', $target[0]);
} else if (typeof collapsible.dataset.noPersistence !== 'undefined') {
if (collapsible.matches('.collapsed')) {
_this.expand(collapsible);
} else {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
}
} else {
var collapsiblePath = _this.icinga.utils.getCSSPath(collapsible);
if (_this.state.has(collapsiblePath)) {
_this.state.delete(collapsiblePath);
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
} else {
_this.state.set(collapsiblePath);
for (const collapsible of toExpand) {
_this.expand(collapsible);
}
}
};
/**
* Setup the given collapsible
*
* @param collapsible The given collapsible container element
*
* @returns {boolean} Whether it needs to collapse or not
*/
Collapsible.prototype.setupCollapsible = function (collapsible) {
var toggleSelector = collapsible.dataset.toggleElement;
if (!! toggleSelector) {
var toggle = $(collapsible).children(toggleSelector)[0];
if (! toggle && $(collapsible.nextSibling).is(toggleSelector)) {
toggle = collapsible.nextSibling;
}
/**
* Updates all collapsibles.
*
* @param event Event The `layout-change` event triggered by window resizing or column changes
*/
onLayoutChange(event) {
let _this = event.data.self;
let toCollapse = [];
document.querySelectorAll('.collapsible').forEach(collapsible => {
if ('canCollapse' in collapsible.dataset) {
if (! _this.canCollapse(collapsible)) {
let toggleSelector = collapsible.dataset.toggleElement;
if (! this.isDetails(collapsible)) {
if (! toggleSelector) {
collapsible.nextElementSibling.remove();
} else {
let toggle = document.getElementById(toggleSelector);
if (toggle) {
toggle.classList.remove('collapsed');
delete toggle.dataset.canCollapse;
}
}
}
delete collapsible.dataset.canCollapse;
_this.expand(collapsible);
}
} else if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) {
// It's expanded but shouldn't
toCollapse.push([collapsible, _this.calculateCollapsedHeight(collapsible)]);
}
});
if (! toggle) {
this.icinga.logger.error(
'[Collapsible] Control `' + toggleSelector + '` not found in .collapsible', collapsible);
} else if (! toggle.classList.contains('collapsible-control')) {
toggle.classList.add('collapsible-control');
}
} else {
setTimeout(function () {
var collapsibleControl = document
.getElementById('collapsible-control-ghost')
.cloneNode(true);
collapsibleControl.removeAttribute('id');
collapsible.parentNode.insertBefore(collapsibleControl, collapsible.nextElementSibling);
for (const collapseInfo of toCollapse) {
_this.collapse(collapseInfo[0], collapseInfo[1]);
}
}, 0);
}
collapsible.classList.add('can-collapse');
/**
* A collapsible got expanded in another window, try to apply this here as well
*
* @param {string} collapsiblePath
*/
onExpand(collapsiblePath) {
let collapsible = document.querySelector(collapsiblePath);
return typeof collapsible.dataset.noPersistence !== 'undefined'
|| ! this.state.has(this.icinga.utils.getCSSPath(collapsible));
};
if (collapsible && 'canCollapse' in collapsible.dataset) {
if ('stateCollapses' in collapsible.dataset) {
this.collapse(collapsible, this.calculateCollapsedHeight(collapsible));
} else {
this.expand(collapsible);
}
}
}
/**
* A collapsible got collapsed in another window, try to apply this here as well
*
* @param {string} collapsiblePath
*/
onCollapse(collapsiblePath) {
let collapsible = document.querySelector(collapsiblePath);
if (collapsible && this.canCollapse(collapsible)) {
if ('stateCollapses' in collapsible.dataset) {
this.expand(collapsible);
} else {
this.collapse(collapsible, this.calculateCollapsedHeight(collapsible));
}
}
}
/**
* Event handler for toggling collapsibles. Switches the collapsed state of the respective container.
*
* @param event Event The `onClick` event triggered by the clicked collapsible-control element
*/
onControlClicked(event) {
let _this = event.data.self,
target = event.currentTarget;
let collapsible = target.previousElementSibling;
if ('collapsibleAt' in target.dataset) {
collapsible = document.querySelector(target.dataset.collapsibleAt);
} else if (! collapsible) {
collapsible = target.closest('.collapsible');
}
if (! collapsible) {
_this.icinga.logger.error(
'[Collapsible] Collapsible control has no associated .collapsible: ', target);
return;
} else if ('noPersistence' in collapsible.dataset) {
if (collapsible.classList.contains('collapsed')) {
_this.expand(collapsible);
} else {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
}
} else {
let collapsiblePath = _this.icinga.utils.getCSSPath(collapsible),
stateCollapses = 'stateCollapses' in collapsible.dataset;
if (_this.state.has(collapsiblePath)) {
_this.state.delete(collapsiblePath);
if (stateCollapses) {
_this.expand(collapsible);
} else {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
}
} else {
_this.state.set(collapsiblePath);
if (stateCollapses) {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
} else {
_this.expand(collapsible);
}
}
}
if (_this.isDetails(collapsible)) {
// The browser handles these clicks as well, and would toggle the state again
event.preventDefault();
}
}
/**
* Setup the given collapsible
*
* @param collapsible The given collapsible container element
*
* @returns {boolean} Whether it needs to collapse or not
*/
setupCollapsible(collapsible) {
if (this.isDetails(collapsible)) {
let summary = collapsible.querySelector(':scope > summary');
if (! summary.classList.contains('collapsible-control')) {
summary.classList.add('collapsible-control');
}
if (collapsible.open) {
collapsible.dataset.stateCollapses = '';
}
} else if (!! collapsible.dataset.toggleElement) {
let toggleSelector = collapsible.dataset.toggleElement,
toggle = collapsible.querySelector(toggleSelector),
externalToggle = false;
if (! toggle) {
if (collapsible.nextElementSibling && collapsible.nextElementSibling.matches(toggleSelector)) {
toggle = collapsible.nextElementSibling;
} else {
externalToggle = true;
toggle = document.getElementById(toggleSelector);
}
}
if (! toggle) {
if (externalToggle) {
this.icinga.logger.error(
'[Collapsible] External control with id `'
+ toggleSelector
+ '` not found for .collapsible',
collapsible
);
} else {
this.icinga.logger.error(
'[Collapsible] Control `' + toggleSelector + '` not found in .collapsible', collapsible);
}
return false;
} else if (externalToggle) {
collapsible.dataset.hasExternalToggle = '';
toggle.dataset.canCollapse = '';
toggle.dataset.collapsibleAt = this.icinga.utils.getCSSPath(collapsible);
$(toggle).on('click', e => {
// Only required as onControlClicked() is compatible with Icinga.EventListener
e.data = { self: this };
this.onControlClicked(e);
});
} else if (! toggle.classList.contains('collapsible-control')) {
toggle.classList.add('collapsible-control');
}
} else {
setTimeout(function () {
let collapsibleControl = document
.getElementById('collapsible-control-ghost')
.cloneNode(true);
collapsibleControl.removeAttribute('id');
collapsible.parentNode.insertBefore(collapsibleControl, collapsible.nextElementSibling);
}, 0);
}
collapsible.dataset.canCollapse = '';
if ('noPersistence' in collapsible.dataset) {
return ! ('stateCollapses' in collapsible.dataset);
}
if ('stateCollapses' in collapsible.dataset) {
return this.state.has(this.icinga.utils.getCSSPath(collapsible));
} else {
return ! this.state.has(this.icinga.utils.getCSSPath(collapsible));
}
}
/**
* Return an appropriate row element selector
*
* @param collapsible The given collapsible container element
*
* @returns {string}
*/
getRowSelector(collapsible) {
if (!! collapsible.dataset.visibleHeight) {
return '';
}
if (collapsible.tagName === 'TABLE') {
return '> tbody > tr';
} else if (collapsible.tagName === 'UL' || collapsible.tagName === 'OL') {
return '> li:not(.collapsible-control)';
}
/**
* Return an appropriate row element selector
*
* @param collapsible The given collapsible container element
*
* @returns {string}
*/
Collapsible.prototype.getRowSelector = function(collapsible) {
if (!! collapsible.dataset.visibleHeight) {
return '';
}
if (collapsible.matches('table')) {
return '> tbody > tr';
} else if (collapsible.matches('ul, ol')) {
return '> li:not(.collapsible-control)';
/**
* Check whether the given collapsible needs to collapse
*
* @param collapsible The given collapsible container element
*
* @returns {boolean}
*/
canCollapse(collapsible) {
if (this.isDetails(collapsible)) {
return collapsible.querySelector(':scope > summary') !== null;
}
let rowSelector = this.getRowSelector(collapsible);
if (!! rowSelector) {
let visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows;
} else if (visibleRows === 0) {
return true;
}
return collapsible.querySelectorAll(rowSelector).length > visibleRows * 2;
} else {
let maxHeight = Number(collapsible.dataset.visibleHeight);
if (isNaN(maxHeight)) {
maxHeight = this.defaultVisibleHeight;
} else if (maxHeight === 0) {
return true;
}
let actualHeight = collapsible.scrollHeight - parseFloat(
window.getComputedStyle(collapsible).getPropertyValue('padding-top')
);
return actualHeight >= maxHeight * 2;
}
}
return '';
};
/**
* Calculate the height the given collapsible should have when collapsed
*
* @param collapsible
*/
calculateCollapsedHeight(collapsible) {
let height;
/**
* Check whether the given collapsible needs to collapse
*
* @param collapsible The given collapsible container element
*
* @returns {boolean}
*/
Collapsible.prototype.canCollapse = function(collapsible) {
var rowSelector = this.getRowSelector(collapsible);
if (!! rowSelector) {
var visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows;
if (this.isDetails(collapsible)) {
return -1;
}
return $(rowSelector, collapsible).length > visibleRows * 2;
} else {
var actualHeight = collapsible.scrollHeight - parseFloat(
window.getComputedStyle(collapsible).getPropertyValue('padding-top')
);
let rowSelector = this.getRowSelector(collapsible);
if (!! rowSelector) {
height = collapsible.scrollHeight;
height -= parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-bottom'));
var maxHeight = Number(collapsible.dataset.visibleHeight);
if (isNaN(maxHeight)) {
maxHeight = this.defaultVisibleHeight;
}
let visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows;
}
return actualHeight >= maxHeight * 2;
}
};
let rows = Array.from(collapsible.querySelectorAll(rowSelector)).slice(visibleRows);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
/**
* Calculate the height the given collapsible should have when collapsed
*
* @param collapsible
*/
Collapsible.prototype.calculateCollapsedHeight = function (collapsible) {
var height;
if (row.previousElementSibling === null) { // very first element
height -= row.offsetHeight;
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top'));
} else if (i < rows.length - 1) { // every element but the last one
let prevBottomBorderAt = row.previousElementSibling.offsetTop;
prevBottomBorderAt += row.previousElementSibling.offsetHeight;
height -= row.offsetTop - prevBottomBorderAt + row.offsetHeight;
} else { // the last element
height -= row.offsetHeight;
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top'));
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-bottom'));
}
}
} else {
height = Number(collapsible.dataset.visibleHeight);
if (isNaN(height)) {
height = this.defaultVisibleHeight;
}
var rowSelector = this.getRowSelector(collapsible);
if (!! rowSelector) {
height = collapsible.scrollHeight;
height -= parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-bottom'));
height += parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-top'));
var visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows;
}
var $rows = $(rowSelector, collapsible).slice(visibleRows);
for (var i = 0; i < $rows.length; i++) {
var row = $rows[i];
if (row.previousElementSibling === null) { // very first element
height -= row.offsetHeight;
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top'));
} else if (i < $rows.length - 1) { // every element but the last one
var prevBottomBorderAt = row.previousElementSibling.offsetTop;
prevBottomBorderAt += row.previousElementSibling.offsetHeight;
height -= row.offsetTop - prevBottomBorderAt + row.offsetHeight;
} else { // the last element
height -= row.offsetHeight;
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top'));
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-bottom'));
if (
!! collapsible.dataset.toggleElement
&& ! ('hasExternalToggle' in collapsible.dataset)
&& (! collapsible.nextElementSibling
|| ! collapsible.nextElementSibling.matches(collapsible.dataset.toggleElement))
) {
let toggle = collapsible.querySelector(collapsible.dataset.toggleElement);
height += toggle.offsetHeight; // TODO: Very expensive at times. (50ms+) Check why!
height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-top'));
height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-bottom'));
}
}
} else {
height = Number(collapsible.dataset.visibleHeight);
if (isNaN(height)) {
height = this.defaultVisibleHeight;
return height;
}
/**
* Collapse the given collapsible
*
* @param collapsible The given collapsible container element
* @param toHeight {int} The height in pixels to collapse to
*/
collapse(collapsible, toHeight) {
if (this.isDetails(collapsible)) {
collapsible.open = false;
} else {
collapsible.style.cssText = 'display: block; height: ' + toHeight + 'px; padding-bottom: 0';
if ('hasExternalToggle' in collapsible.dataset) {
document.getElementById(collapsible.dataset.toggleElement).classList.add('collapsed');
}
}
height += parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-top'));
collapsible.classList.add('collapsed');
}
if (
!! collapsible.dataset.toggleElement
&& ! $(collapsible.nextSibling).is(collapsible.dataset.toggleElement)
) {
var toggle = $(collapsible).children(collapsible.dataset.toggleElement)[0];
height += toggle.offsetHeight; // TODO: Very expensive at times. (50ms+) Check why!
height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-top'));
height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-bottom'));
/**
* Expand the given collapsible
*
* @param collapsible The given collapsible container element
*/
expand(collapsible) {
collapsible.classList.remove('collapsed');
if (this.isDetails(collapsible)) {
collapsible.open = true;
} else {
collapsible.style.cssText = '';
if ('hasExternalToggle' in collapsible.dataset) {
document.getElementById(collapsible.dataset.toggleElement).classList.remove('collapsed');
}
}
}
return height;
};
/**
* Collapse the given collapsible
*
* @param collapsible The given collapsible container element
* @param toHeight {int} The height in pixels to collapse to
*/
Collapsible.prototype.collapse = function(collapsible, toHeight) {
collapsible.style.cssText = 'display: block; height: ' + toHeight + 'px; padding-bottom: 0';
collapsible.classList.add('collapsed');
};
/**
* Expand the given collapsible
*
* @param collapsible The given collapsible container element
*/
Collapsible.prototype.expand = function(collapsible) {
collapsible.classList.remove('collapsed');
collapsible.style.cssText = '';
};
/**
* Get whether the given collapsible is a <details> element
*
* @param collapsible
*
* @return {Boolean}
*/
isDetails(collapsible) {
return collapsible.tagName === 'DETAILS';
}
}
Icinga.Behaviors.Collapsible = Collapsible;
})(Icinga, jQuery);
})(Icinga);

View File

@ -371,15 +371,19 @@
var path = [];
while (true) {
var id = element.getAttribute("id");
let id = element.id;
if (typeof id !== 'undefined' && typeof id !== 'string') {
// Sometimes there may be a form element with the name "id"
id = element.getAttribute("id");
}
// Only use ids if they're truly unique
// TODO: The check used to use document.querySelectorAll, but this resulted in many issues with ids
// that start with a decimal. jQuery seems to escape those correctly, so this is the only reason
// why it's still.. jQuery.
if (!! id && $('* #' + id).length === 1) {
path.push('#' + id);
break;
if (!! id) {
// Only use ids if they're truly unique
let results = document.querySelectorAll('* #' + this.escapeCSSSelector(id));
if (results.length === 1) {
path.push('#' + id);
break;
}
}
var tagName = element.tagName;
@ -409,6 +413,20 @@
return path.reverse().join(' > ');
},
/**
* Escape the given string to be used in a CSS selector
*
* @param {string} selector
* @returns {string}
*/
escapeCSSSelector: function (selector) {
if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
return CSS.escape(selector);
}
return selector.replaceAll(/^(\d)/, '\\\\3$1 ');
},
/**
* Climbs up the given dom path and returns the element
*