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

View File

@ -54,7 +54,7 @@ class PrivilegeAudit extends BaseHtmlElement
} }
} }
$header = new HtmlElement('div'); $header = new HtmlElement('summary');
if (! empty($refusedBy)) { if (! empty($refusedBy)) {
$header->add([ $header->add([
new Icon('times-circle', ['class' => 'refused']), new Icon('times-circle', ['class' => 'refused']),
@ -171,15 +171,25 @@ class PrivilegeAudit extends BaseHtmlElement
])); ]));
} }
if (empty($rolePaths)) {
return [ return [
empty($refusedBy) ? (empty($grantedBy) ? null : true) : false, empty($refusedBy) ? (empty($grantedBy) ? null : true) : false,
HtmlElement::create('div', [ new HtmlElement(
'class' => [empty($rolePaths) ? null : 'collapsible', 'inheritance-paths'], 'div',
'data-toggle-element' => '.collapsible-control', Attributes::create(['class' => 'inheritance-paths']),
$header->setTag('div')
)
];
}
return [
empty($refusedBy) ? (empty($grantedBy) ? null : true) : false,
HtmlElement::create('details', [
'class' => ['collapsible', 'inheritance-paths'],
'data-no-persistence' => true, '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 $rolePaths
]) ])
]; ];
@ -202,7 +212,7 @@ class PrivilegeAudit extends BaseHtmlElement
} }
} }
$header = new HtmlElement('div'); $header = new HtmlElement('summary');
if (! empty($restrictedBy)) { if (! empty($restrictedBy)) {
$header->add([ $header->add([
new Icon('filter', ['class' => 'restricted']), new Icon('filter', ['class' => 'restricted']),
@ -277,17 +287,27 @@ class PrivilegeAudit extends BaseHtmlElement
]); ]);
} }
if (empty($roles)) {
return [ return [
! empty($restrictedBy), ! empty($restrictedBy),
new HtmlElement( new HtmlElement(
'div', 'div',
Attributes::create(['class' => 'restrictions']),
$header->setTag('div')
)
];
}
return [
! empty($restrictedBy),
new HtmlElement(
'details',
Attributes::create([ Attributes::create([
'class' => [empty($roles) ? null : 'collapsible', 'restrictions'], 'class' => ['collapsible', 'restrictions'],
'data-toggle-element' => '.collapsible-control',
'data-no-persistence' => true, '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) new HtmlElement('ul', null, ...$roles)
) )
]; ];
@ -301,14 +321,18 @@ class PrivilegeAudit extends BaseHtmlElement
$this->addHtml(new HtmlElement( $this->addHtml(new HtmlElement(
'li', 'li',
null,
new HtmlElement(
'details',
Attributes::create([ Attributes::create([
'class' => 'collapsible', 'class' => ['collapsible', 'privilege-section'],
'data-toggle-element' => 'h3', 'open' => ($wildcardState || $unrestrictedState) && getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
'data-visible-height' => 0
]), ]),
new HtmlElement( new HtmlElement(
'h3', 'summary',
null, Attributes::create(['class' => [
'collapsible-control', // Helps JS, improves performance a bit
]]),
new HtmlElement('span', null, Text::create(t('Administrative Privileges'))), new HtmlElement('span', null, Text::create(t('Administrative Privileges'))),
HtmlElement::create( HtmlElement::create(
'span', 'span',
@ -316,7 +340,9 @@ class PrivilegeAudit extends BaseHtmlElement
$wildcardState || $unrestrictedState $wildcardState || $unrestrictedState
? new Icon('check-circle', ['class' => 'granted']) ? new Icon('check-circle', ['class' => 'granted'])
: null : null
) ),
new Icon('angles-down', ['class' => 'collapse-icon']),
new Icon('angles-left', ['class' => 'expand-icon'])
), ),
new HtmlElement( new HtmlElement(
'ol', 'ol',
@ -336,6 +362,7 @@ class PrivilegeAudit extends BaseHtmlElement
$unrestrictedAudit $unrestrictedAudit
) )
) )
)
)); ));
$privilegeSources = array_unique(array_merge(array_keys($permissions), array_keys($restrictions))); $privilegeSources = array_unique(array_merge(array_keys($permissions), array_keys($restrictions)));
@ -420,20 +447,27 @@ class PrivilegeAudit extends BaseHtmlElement
$label = [$source, ' ', HtmlElement::create('em', null, t('Module'))]; $label = [$source, ' ', HtmlElement::create('em', null, t('Module'))];
} }
$this->addHtml(HtmlElement::create('li', [ $this->addHtml(new HtmlElement(
'class' => 'collapsible', 'li',
'data-toggle-element' => 'h3', null,
'data-visible-height' => 0 HtmlElement::create('details', [
'class' => ['collapsible', 'privilege-section'],
'open' => ($anythingGranted || $anythingRefused || $anythingRestricted)
&& getenv('ICINGAWEB_EXPORT_FORMAT') === 'pdf'
], [ ], [
new HtmlElement( new HtmlElement(
'h3', 'summary',
null, Attributes::create(['class' => [
'collapsible-control', // Helps JS, improves performance a bit
]]),
HtmlElement::create('span', null, $label), HtmlElement::create('span', null, $label),
HtmlElement::create('span', ['class' => 'audit-preview'], [ HtmlElement::create('span', ['class' => 'audit-preview'], [
$anythingGranted ? new Icon('check-circle', ['class' => 'granted']) : null, $anythingGranted ? new Icon('check-circle', ['class' => 'granted']) : null,
$anythingRefused ? new Icon('times-circle', ['class' => 'refused']) : null, $anythingRefused ? new Icon('times-circle', ['class' => 'refused']) : null,
$anythingRestricted ? new Icon('filter', ['class' => 'restricted']) : 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 : [ $permissionList->isEmpty() ? null : [
HtmlElement::create('h4', null, t('Permissions')), HtmlElement::create('h4', null, t('Permissions')),
@ -443,7 +477,8 @@ class PrivilegeAudit extends BaseHtmlElement
HtmlElement::create('h4', null, t('Restrictions')), HtmlElement::create('h4', null, t('Restrictions')),
$restrictionList $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) { :nth-child(1) {
display: none; display: none;
} }

View File

@ -19,16 +19,17 @@
list-style-type: none; list-style-type: none;
} }
h3 { .privilege-section > summary {
font-weight: @font-weight-bold;
border-bottom: 1px solid @gray-light; border-bottom: 1px solid @gray-light;
} }
h3 em, .privilege-section > summary em,
.previews em, .previews em,
.privilege-label em { .privilege-label em {
color: @text-color-light; color: @text-color-light;
} }
h3 em { .privilege-section > summary em {
font-weight: normal; font-weight: normal;
} }
.privilege-label em { .privilege-label em {
@ -144,10 +145,6 @@
padding: 0; padding: 0;
} }
> li:not(.collapsed) {
margin-bottom: 2em;
}
.flex-overflow, .flex-overflow,
.privilege-list > li, .privilege-list > li,
.inheritance-paths > ol { .inheritance-paths > ol {
@ -165,15 +162,30 @@
// https://codepen.io/unthinkingly/pen/XMwJLG // https://codepen.io/unthinkingly/pen/XMwJLG
overflow: hidden; 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; display: flex;
align-items: baseline;
font-size: 1.167em;
margin: 0.556em 0 0.333em;
> :first-child { > :first-child {
flex: 3 1 auto; flex: 3 1 auto;
min-width: 20em; 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 { .audit-preview {
@ -181,7 +193,7 @@
.icon:before { .icon:before {
width: 1.25em; 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 { .restrictions {
flex: 1 1 auto; flex: 1 1 auto;
> div { > summary {
line-height: 1; line-height: 1;
overflow: hidden; overflow: hidden;
@ -325,7 +337,7 @@
#layout.minimal-layout, #layout.minimal-layout,
#layout.poor-layout { #layout.poor-layout {
.privilege-audit { .privilege-audit {
h3 > :first-child { .privilege-section > summary > :first-child {
flex-grow: 99; flex-grow: 99;
} }
@ -346,27 +358,6 @@
.privilege-audit .collapsible { .privilege-audit .collapsible {
.collapsible-control { .collapsible-control {
cursor: pointer; cursor: pointer;
-webkit-touch-callout: none; .user-select(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

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

View File

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

View File

@ -255,10 +255,30 @@ form.role-form {
display: inline-block; 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 { > :first-child {
display: inline-block; 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 { .privilege-preview .icon {
@ -276,12 +296,8 @@ form.role-form {
} }
} }
fieldset.collapsible { .collapsible {
border: none; summary em {
padding: 0;
margin: 0;
h3 em {
font-size: .857em; font-size: .857em;
font-weight: normal; font-weight: normal;
color: @text-color-light; 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,22 +1,31 @@
/*! Icinga Web 2 | (c) 2019 Icinga GmbH | GPLv2+ */ /*! Icinga Web 2 | (c) 2019 Icinga GmbH | GPLv2+ */
;(function(Icinga, $) { ;(function(Icinga) {
'use strict'; 'use strict';
Icinga.Behaviors = Icinga.Behaviors || {}; 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. * Behavior for collapsible containers.
* *
* @param icinga Icinga The current Icinga Object * @param icinga Icinga The current Icinga Object
*/ */
var Collapsible = function(icinga) { class Collapsible extends Icinga.EventListener {
Icinga.EventListener.call(this, icinga); constructor(icinga) {
super(icinga);
this.on('layout-change', this.onLayoutChange, this); this.on('layout-change', this.onLayoutChange, this);
this.on('rendered', '#main > .container, #modal-content', this.onRendered, this); this.on('rendered', '#main > .container, #modal-content', this.onRendered, this);
this.on('click', '.collapsible + .collapsible-control, .collapsible > .collapsible-control', this.on('click', '.collapsible + .collapsible-control, .collapsible .collapsible-control',
this.onControlClicked, this); this.onControlClicked, this);
this.icinga = icinga; this.icinga = icinga;
@ -29,52 +38,68 @@
) )
.on('add', this.onExpand, this) .on('add', this.onExpand, this)
.on('delete', this.onCollapse, this); .on('delete', this.onCollapse, this);
}; }
Collapsible.prototype = new Icinga.EventListener();
/** /**
* Initializes all collapsibles. Triggered on rendering of a container. * Initializes all collapsibles. Triggered on rendering of a container.
* *
* @param event Event The `onRender` event triggered by the rendered container * @param event Event The `onRender` event triggered by the rendered container
*/ */
Collapsible.prototype.onRendered = function(event) { onRendered(event) {
var _this = event.data.self; let _this = event.data.self,
var toCollapse = []; toCollapse = [],
toExpand = [];
$.each(event.target.querySelectorAll('.collapsible:not(.can-collapse)'), function (_, collapsible) { event.target.querySelectorAll('.collapsible').forEach(collapsible => {
// Assumes that any newly rendered elements are expanded // Assumes that any newly rendered elements are expanded
if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) { if (! ('canCollapse' in collapsible.dataset) && _this.canCollapse(collapsible)) {
if (_this.setupCollapsible(collapsible)) {
toCollapse.push([collapsible, _this.calculateCollapsedHeight(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);
}
} }
}); });
// Elements are all collapsed in a row now, after height calculations are done. // 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 // This avoids reflows since instantly collapsing an element will cause one if
// the height of the next element is being calculated. // the height of the next element is being calculated.
for (var i = 0; i < toCollapse.length; i++) { for (const collapseInfo of toCollapse) {
_this.collapse(toCollapse[i][0], toCollapse[i][1]); _this.collapse(collapseInfo[0], collapseInfo[1]);
}
for (const collapsible of toExpand) {
_this.expand(collapsible);
}
} }
};
/** /**
* Updates all collapsibles. * Updates all collapsibles.
* *
* @param event Event The `layout-change` event triggered by window resizing or column changes * @param event Event The `layout-change` event triggered by window resizing or column changes
*/ */
Collapsible.prototype.onLayoutChange = function(event) { onLayoutChange(event) {
var _this = event.data.self; let _this = event.data.self;
var toCollapse = []; let toCollapse = [];
$.each(document.querySelectorAll('.collapsible'), function (_, collapsible) { document.querySelectorAll('.collapsible').forEach(collapsible => {
if (collapsible.matches('.can-collapse')) { if ('canCollapse' in collapsible.dataset) {
if (! _this.canCollapse(collapsible)) { if (! _this.canCollapse(collapsible)) {
var toggleSelector = collapsible.dataset.toggleElement; let toggleSelector = collapsible.dataset.toggleElement;
if (! this.isDetails(collapsible)) {
if (! toggleSelector) { if (! toggleSelector) {
$(collapsible).next('.collapsible-control').remove(); collapsible.nextElementSibling.remove();
} else {
let toggle = document.getElementById(toggleSelector);
if (toggle) {
toggle.classList.remove('collapsed');
delete toggle.dataset.canCollapse;
}
}
} }
collapsible.classList.remove('can-collapse'); delete collapsible.dataset.canCollapse;
_this.expand(collapsible); _this.expand(collapsible);
} }
} else if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) { } else if (_this.canCollapse(collapsible) && _this.setupCollapsible(collapsible)) {
@ -84,72 +109,101 @@
}); });
setTimeout(function () { setTimeout(function () {
for (var i = 0; i < toCollapse.length; i++) { for (const collapseInfo of toCollapse) {
_this.collapse(toCollapse[i][0], toCollapse[i][1]); _this.collapse(collapseInfo[0], collapseInfo[1]);
} }
}, 0); }, 0);
}; }
/** /**
* A collapsible got expanded in another window, try to apply this here as well * A collapsible got expanded in another window, try to apply this here as well
* *
* @param {string} collapsiblePath * @param {string} collapsiblePath
*/ */
Collapsible.prototype.onExpand = function(collapsiblePath) { onExpand(collapsiblePath) {
var collapsible = $(collapsiblePath)[0]; let collapsible = document.querySelector(collapsiblePath);
if (collapsible && collapsible.matches('.can-collapse')) { if (collapsible && 'canCollapse' in collapsible.dataset) {
if ('stateCollapses' in collapsible.dataset) {
this.collapse(collapsible, this.calculateCollapsedHeight(collapsible));
} else {
this.expand(collapsible); this.expand(collapsible);
} }
}; }
}
/** /**
* A collapsible got collapsed in another window, try to apply this here as well * A collapsible got collapsed in another window, try to apply this here as well
* *
* @param {string} collapsiblePath * @param {string} collapsiblePath
*/ */
Collapsible.prototype.onCollapse = function(collapsiblePath) { onCollapse(collapsiblePath) {
var collapsible = $(collapsiblePath)[0]; let collapsible = document.querySelector(collapsiblePath);
if (collapsible && this.canCollapse(collapsible)) { if (collapsible && this.canCollapse(collapsible)) {
if ('stateCollapses' in collapsible.dataset) {
this.expand(collapsible);
} else {
this.collapse(collapsible, this.calculateCollapsedHeight(collapsible)); this.collapse(collapsible, this.calculateCollapsedHeight(collapsible));
} }
}; }
}
/** /**
* Event handler for toggling collapsibles. Switches the collapsed state of the respective container. * 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 * @param event Event The `onClick` event triggered by the clicked collapsible-control element
*/ */
Collapsible.prototype.onControlClicked = function(event) { onControlClicked(event) {
var _this = event.data.self; let _this = event.data.self,
var $target = $(event.currentTarget); target = event.currentTarget;
var collapsible = $target.prev('.collapsible')[0]; let collapsible = target.previousElementSibling;
if (! collapsible) { if ('collapsibleAt' in target.dataset) {
collapsible = $target.parent('.collapsible')[0]; collapsible = document.querySelector(target.dataset.collapsibleAt);
} else if (! collapsible) {
collapsible = target.closest('.collapsible');
} }
if (! collapsible) { if (! collapsible) {
_this.icinga.logger.error( _this.icinga.logger.error(
'[Collapsible] Collapsible control has no associated .collapsible: ', $target[0]); '[Collapsible] Collapsible control has no associated .collapsible: ', target);
} else if (typeof collapsible.dataset.noPersistence !== 'undefined') {
if (collapsible.matches('.collapsed')) { return;
} else if ('noPersistence' in collapsible.dataset) {
if (collapsible.classList.contains('collapsed')) {
_this.expand(collapsible); _this.expand(collapsible);
} else { } else {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible)); _this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
} }
} else { } else {
var collapsiblePath = _this.icinga.utils.getCSSPath(collapsible); let collapsiblePath = _this.icinga.utils.getCSSPath(collapsible),
stateCollapses = 'stateCollapses' in collapsible.dataset;
if (_this.state.has(collapsiblePath)) { if (_this.state.has(collapsiblePath)) {
_this.state.delete(collapsiblePath); _this.state.delete(collapsiblePath);
if (stateCollapses) {
_this.expand(collapsible);
} else {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible)); _this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
}
} else { } else {
_this.state.set(collapsiblePath); _this.state.set(collapsiblePath);
if (stateCollapses) {
_this.collapse(collapsible, _this.calculateCollapsedHeight(collapsible));
} else {
_this.expand(collapsible); _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 * Setup the given collapsible
@ -158,23 +212,59 @@
* *
* @returns {boolean} Whether it needs to collapse or not * @returns {boolean} Whether it needs to collapse or not
*/ */
Collapsible.prototype.setupCollapsible = function (collapsible) { setupCollapsible(collapsible) {
var toggleSelector = collapsible.dataset.toggleElement; if (this.isDetails(collapsible)) {
if (!! toggleSelector) { let summary = collapsible.querySelector(':scope > summary');
var toggle = $(collapsible).children(toggleSelector)[0]; if (! summary.classList.contains('collapsible-control')) {
if (! toggle && $(collapsible.nextSibling).is(toggleSelector)) { summary.classList.add('collapsible-control');
toggle = collapsible.nextSibling; }
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 (! toggle) {
if (externalToggle) {
this.icinga.logger.error(
'[Collapsible] External control with id `'
+ toggleSelector
+ '` not found for .collapsible',
collapsible
);
} else {
this.icinga.logger.error( this.icinga.logger.error(
'[Collapsible] Control `' + toggleSelector + '` not found in .collapsible', collapsible); '[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')) { } else if (! toggle.classList.contains('collapsible-control')) {
toggle.classList.add('collapsible-control'); toggle.classList.add('collapsible-control');
} }
} else { } else {
setTimeout(function () { setTimeout(function () {
var collapsibleControl = document let collapsibleControl = document
.getElementById('collapsible-control-ghost') .getElementById('collapsible-control-ghost')
.cloneNode(true); .cloneNode(true);
collapsibleControl.removeAttribute('id'); collapsibleControl.removeAttribute('id');
@ -182,11 +272,18 @@
}, 0); }, 0);
} }
collapsible.classList.add('can-collapse'); collapsible.dataset.canCollapse = '';
return typeof collapsible.dataset.noPersistence !== 'undefined' if ('noPersistence' in collapsible.dataset) {
|| ! this.state.has(this.icinga.utils.getCSSPath(collapsible)); 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 * Return an appropriate row element selector
@ -195,19 +292,19 @@
* *
* @returns {string} * @returns {string}
*/ */
Collapsible.prototype.getRowSelector = function(collapsible) { getRowSelector(collapsible) {
if (!! collapsible.dataset.visibleHeight) { if (!! collapsible.dataset.visibleHeight) {
return ''; return '';
} }
if (collapsible.matches('table')) { if (collapsible.tagName === 'TABLE') {
return '> tbody > tr'; return '> tbody > tr';
} else if (collapsible.matches('ul, ol')) { } else if (collapsible.tagName === 'UL' || collapsible.tagName === 'OL') {
return '> li:not(.collapsible-control)'; return '> li:not(.collapsible-control)';
} }
return ''; return '';
}; }
/** /**
* Check whether the given collapsible needs to collapse * Check whether the given collapsible needs to collapse
@ -216,56 +313,68 @@
* *
* @returns {boolean} * @returns {boolean}
*/ */
Collapsible.prototype.canCollapse = function(collapsible) { canCollapse(collapsible) {
var rowSelector = this.getRowSelector(collapsible); if (this.isDetails(collapsible)) {
if (!! rowSelector) { return collapsible.querySelector(':scope > summary') !== null;
var visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows;
} }
return $(rowSelector, collapsible).length > visibleRows * 2; 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 { } else {
var actualHeight = collapsible.scrollHeight - parseFloat( 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') window.getComputedStyle(collapsible).getPropertyValue('padding-top')
); );
var maxHeight = Number(collapsible.dataset.visibleHeight);
if (isNaN(maxHeight)) {
maxHeight = this.defaultVisibleHeight;
}
return actualHeight >= maxHeight * 2; return actualHeight >= maxHeight * 2;
} }
}; }
/** /**
* Calculate the height the given collapsible should have when collapsed * Calculate the height the given collapsible should have when collapsed
* *
* @param collapsible * @param collapsible
*/ */
Collapsible.prototype.calculateCollapsedHeight = function (collapsible) { calculateCollapsedHeight(collapsible) {
var height; let height;
var rowSelector = this.getRowSelector(collapsible); if (this.isDetails(collapsible)) {
return -1;
}
let rowSelector = this.getRowSelector(collapsible);
if (!! rowSelector) { if (!! rowSelector) {
height = collapsible.scrollHeight; height = collapsible.scrollHeight;
height -= parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-bottom')); height -= parseFloat(window.getComputedStyle(collapsible).getPropertyValue('padding-bottom'));
var visibleRows = Number(collapsible.dataset.visibleRows); let visibleRows = Number(collapsible.dataset.visibleRows);
if (isNaN(visibleRows)) { if (isNaN(visibleRows)) {
visibleRows = this.defaultVisibleRows; visibleRows = this.defaultVisibleRows;
} }
var $rows = $(rowSelector, collapsible).slice(visibleRows); let rows = Array.from(collapsible.querySelectorAll(rowSelector)).slice(visibleRows);
for (var i = 0; i < $rows.length; i++) { for (let i = 0; i < rows.length; i++) {
var row = $rows[i]; let row = rows[i];
if (row.previousElementSibling === null) { // very first element if (row.previousElementSibling === null) { // very first element
height -= row.offsetHeight; height -= row.offsetHeight;
height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top')); height -= parseFloat(window.getComputedStyle(row).getPropertyValue('margin-top'));
} else if (i < $rows.length - 1) { // every element but the last one } else if (i < rows.length - 1) { // every element but the last one
var prevBottomBorderAt = row.previousElementSibling.offsetTop; let prevBottomBorderAt = row.previousElementSibling.offsetTop;
prevBottomBorderAt += row.previousElementSibling.offsetHeight; prevBottomBorderAt += row.previousElementSibling.offsetHeight;
height -= row.offsetTop - prevBottomBorderAt + row.offsetHeight; height -= row.offsetTop - prevBottomBorderAt + row.offsetHeight;
} else { // the last element } else { // the last element
@ -284,9 +393,11 @@
if ( if (
!! collapsible.dataset.toggleElement !! collapsible.dataset.toggleElement
&& ! $(collapsible.nextSibling).is(collapsible.dataset.toggleElement) && ! ('hasExternalToggle' in collapsible.dataset)
&& (! collapsible.nextElementSibling
|| ! collapsible.nextElementSibling.matches(collapsible.dataset.toggleElement))
) { ) {
var toggle = $(collapsible).children(collapsible.dataset.toggleElement)[0]; let toggle = collapsible.querySelector(collapsible.dataset.toggleElement);
height += toggle.offsetHeight; // TODO: Very expensive at times. (50ms+) Check why! 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-top'));
height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-bottom')); height += parseFloat(window.getComputedStyle(toggle).getPropertyValue('margin-bottom'));
@ -294,7 +405,7 @@
} }
return height; return height;
}; }
/** /**
* Collapse the given collapsible * Collapse the given collapsible
@ -302,21 +413,51 @@
* @param collapsible The given collapsible container element * @param collapsible The given collapsible container element
* @param toHeight {int} The height in pixels to collapse to * @param toHeight {int} The height in pixels to collapse to
*/ */
Collapsible.prototype.collapse = function(collapsible, toHeight) { collapse(collapsible, toHeight) {
if (this.isDetails(collapsible)) {
collapsible.open = false;
} else {
collapsible.style.cssText = 'display: block; height: ' + toHeight + 'px; padding-bottom: 0'; collapsible.style.cssText = 'display: block; height: ' + toHeight + 'px; padding-bottom: 0';
if ('hasExternalToggle' in collapsible.dataset) {
document.getElementById(collapsible.dataset.toggleElement).classList.add('collapsed');
}
}
collapsible.classList.add('collapsed'); collapsible.classList.add('collapsed');
}; }
/** /**
* Expand the given collapsible * Expand the given collapsible
* *
* @param collapsible The given collapsible container element * @param collapsible The given collapsible container element
*/ */
Collapsible.prototype.expand = function(collapsible) { expand(collapsible) {
collapsible.classList.remove('collapsed'); collapsible.classList.remove('collapsed');
if (this.isDetails(collapsible)) {
collapsible.open = true;
} else {
collapsible.style.cssText = ''; collapsible.style.cssText = '';
};
if ('hasExternalToggle' in collapsible.dataset) {
document.getElementById(collapsible.dataset.toggleElement).classList.remove('collapsed');
}
}
}
/**
* Get whether the given collapsible is a <details> element
*
* @param collapsible
*
* @return {Boolean}
*/
isDetails(collapsible) {
return collapsible.tagName === 'DETAILS';
}
}
Icinga.Behaviors.Collapsible = Collapsible; Icinga.Behaviors.Collapsible = Collapsible;
})(Icinga, jQuery); })(Icinga);

View File

@ -371,16 +371,20 @@
var path = []; var path = [];
while (true) { 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");
}
if (!! id) {
// Only use ids if they're truly unique // Only use ids if they're truly unique
// TODO: The check used to use document.querySelectorAll, but this resulted in many issues with ids let results = document.querySelectorAll('* #' + this.escapeCSSSelector(id));
// that start with a decimal. jQuery seems to escape those correctly, so this is the only reason if (results.length === 1) {
// why it's still.. jQuery.
if (!! id && $('* #' + id).length === 1) {
path.push('#' + id); path.push('#' + id);
break; break;
} }
}
var tagName = element.tagName; var tagName = element.tagName;
var parent = element.parentElement; var parent = element.parentElement;
@ -409,6 +413,20 @@
return path.reverse().join(' > '); 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 * Climbs up the given dom path and returns the element
* *