|
| 1 | +/* eslint-disable import/prefer-default-export */ |
| 2 | + |
| 3 | +//import {print as inspect} from 'q-i'; |
| 4 | +import {PROP_CONTENT, PROP_TAG} from './element.es'; |
| 5 | +import {isArray} from '../util/isArray.es'; |
| 6 | + |
| 7 | + |
| 8 | +export function domPath(element, path) { |
| 9 | + //inspect({domPath: {element, path}}); |
| 10 | + //inspect({path}); |
| 11 | + if (!element[PROP_CONTENT]) { return null; } |
| 12 | + |
| 13 | + const contentArr = isArray(element[PROP_CONTENT]) ? |
| 14 | + element[PROP_CONTENT] : [element[PROP_CONTENT]]; |
| 15 | + |
| 16 | + const pathObj = {}; |
| 17 | + for (let i = 0; i < contentArr.length; i += 1) { |
| 18 | + const item = contentArr[i]; |
| 19 | + const childTag = item[PROP_TAG]; |
| 20 | + if (isArray(pathObj[childTag])) { |
| 21 | + pathObj[childTag].push(item); // reference |
| 22 | + } else if (pathObj[childTag]) { |
| 23 | + pathObj[childTag] = [pathObj[childTag], item]; // reference |
| 24 | + } else { |
| 25 | + pathObj[childTag] = item; // reference |
| 26 | + } |
| 27 | + } // for |
| 28 | + //inspect({pathObj}); |
| 29 | + |
| 30 | + const parts = path.split('.'); |
| 31 | + const currentPart = parts.shift(); //inspect({currentPart}); |
| 32 | + const brackets = currentPart.split('['); //inspect({brackets}); |
| 33 | + let child; |
| 34 | + if (brackets.length > 1) { |
| 35 | + //child = eval(`pathObj.${currentPart}`); // NOTE eval can be harmful, so this avoids it: |
| 36 | + const a = brackets[0]; //inspect({a}); |
| 37 | + const b = brackets[1].substring(0, brackets[1].length - 1); //inspect({b}); |
| 38 | + child = pathObj[a][b]; |
| 39 | + } else { |
| 40 | + child = pathObj[currentPart]; |
| 41 | + } |
| 42 | + //inspect({child}); |
| 43 | + if (!child) { return null; } |
| 44 | + if (!parts.length) { return child; } // reference |
| 45 | + return domPath(child, parts.join('.')); // recurse |
| 46 | +} // export function domPath |
0 commit comments