UNPKG

simmerjs

Version:

A pure Javascript reverse CSS selector engine which calculates a DOM element's unique CSS selector on the current page.

56 lines (47 loc) 2.81 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /** * Inspect the elements' IDs and add them to the CSS Selector * @param {array} hierarchy. The hierarchy of elements * @param {object} state. The current selector state (has the stack and specificity sum) */ exports.default = function (hierarchy, state, validateSelector, config, query) { return hierarchy.reduce(function (selectorState, currentElem, index) { if (!selectorState.verified) { var _filter$filter$map = [currentElem.el.getAttribute('id')].filter(function (id) { return (0, _validationHelpers.attr)(id); } // make sure the ID is unique ).filter(function (id) { return (0, _queryEngine.isUniqueElementID)(query, id); }).map(function (validId) { selectorState.stack[index].push('[id=\'' + validId + '\']'); selectorState.specificity += 100; if (selectorState.specificity >= config.specificityThreshold) { // we have reached the minimum specificity, lets try verifying now, as this will save us having to add more IDs to the selector if (validateSelector(selectorState)) { // The ID worked like a charm - mark this state as verified and move on! selectorState.verified = true; } } if (!selectorState.verified && index === 0) { // if the index is 0 then this is the ID of the actual element! Which means we have found our selector! // The ID wasn't enough, this means the page, this should never happen as we tested for the ID's uniquness, but just incase // we will pop it from the stack as it only adds noise selectorState.stack[index].pop(); selectorState.specificity -= 100; } return selectorState; }), _filter$filter$map2 = _slicedToArray(_filter$filter$map, 1), validatedState = _filter$filter$map2[0]; return validatedState || selectorState; } return selectorState; }, state); }; var _queryEngine = require('../queryEngine'); var _validationHelpers = require('./validationHelpers');