vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
89 lines (88 loc) • 2.9 kB
JavaScript
;
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var elmExp = /^[a-z]+/;
var nameExp = /[a-z][\w\d-]*/i;
var nameExpStr = nameExp.source;
var idExp = new RegExp("#" + nameExpStr, 'i');
var classExp = new RegExp("\\." + nameExpStr, 'ig');
var attrExp = new RegExp("\\[(" + nameExpStr + ")(?:=([^\\]]+))?]", 'g');
var addAttribute = function (att, val, attributes) {
if (val == null) {
return;
}
var isId = att === 'id';
// ID Attributes are only added once
if (isId && attributes[att]) {
return;
}
if (!attributes[att]) {
attributes[att] = new Set();
}
// Clean class and ID values
if (att === 'class' || isId) {
val = val.replace(/[#.]/g, '');
}
attributes[att].add(val);
};
var parseAttribute = function (selector, attributes) {
// This function detects the attribute from the selector,
// and then removes it to avoid having to parse it again
var replaceFn = function (_, att, val) {
val = (val || '').replace(/^["']|["']$/g, '');
addAttribute(att, val, attributes);
return '';
};
return selector.includes('[')
? selector.replace(attrExp, replaceFn)
: selector;
};
/**
* Parses a selector string into a structured object
*
* @param selector - The CSS selector to parse
* @return The attribute parsing mapping
*/
function parseSelector(selector) {
var mapping = {};
// Tag name
var tagNameMatch = selector.match(elmExp);
var tagName = (tagNameMatch || ['div'])[0];
// Attribute expressions
selector = parseAttribute(selector, mapping);
// ID
var idMatch = selector.includes('#') && selector.match(idExp);
if (idMatch) {
delete mapping.id;
addAttribute('id', idMatch[0].substr(1), mapping);
}
// Class names
var cnMatch = selector.includes('.') && selector.match(classExp);
if (cnMatch) {
cnMatch.forEach(function (cn) { return addAttribute('class', cn.substr(1), mapping); });
}
// Transform array attributes into space separated strings
var attributes = Object.entries(mapping)
.reduce(function (atts, _a) {
var _b = __read(_a, 2), name = _b[0], val = _b[1];
atts[name] = Array.from(val).join(' ');
return atts;
}, {});
return { tagName: tagName, attributes: attributes };
}
exports.default = parseSelector;