Skip to content

Commit

Permalink
utils.js: Optimize performance of getCSSPath()
Browse files Browse the repository at this point in the history
  • Loading branch information
nilmerg committed Jul 26, 2022
1 parent 0198900 commit 382b270
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions public/js/icinga/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,15 +371,19 @@
var path = [];

while (true) {
var 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;
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
let results = document.querySelectorAll('* #' + this.escapeCSSSelector(id));
if (results.length === 1) {
path.push('#' + id);
break;
}
}

var tagName = element.tagName;
Expand Down Expand Up @@ -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
*
Expand Down

0 comments on commit 382b270

Please sign in to comment.