All files / gogocode-core/src/html-core core.js

85.15% Statements 109/128
69.3% Branches 70/101
94.11% Functions 16/17
85.15% Lines 109/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 31337x 37x 37x 37x 37x                     133x 131x   133x 133x 133x 135x         135x         135x     133x 133x 135x               135x                         232x 227x 227x 227x       133x               199x 199x 324x 324x   199x               286x 286x 286x 286x 286x 265x   21x 21x 5x 16x 16x                           286x                   286x     4x 2x         2x 2x                       59x 28x   59x                   59x 59x 45x 45x 45x     45x 29x 29x 87x 46x 46x 46x   46x   51x 51x 20x 20x       31x 25x 6x 6x   51x   51x     31x               31x       51x       46x         41x 41x 41x         29x   16x           45x     45x 45x   45x   3x 3x     3x     3x 42x 6x 36x   36x 36x                         42x     42x 42x 42x         8x 1x   7x           1x           6x             6x   16x 16x 16x       1x 1x           1x         37x  
const getSelector = require('./get-selector');
const { find } = require('./find');
const parse = require('./parse');
const generate = require('./serialize-node');
const core = {
    // 通过选择器获取,返回ast片段
    getAstsBySelector(
        ast,
        selector,
        { strictSequence, deep, parseOptions, expando = 'g123o456g789o' } = {}
    ) {
        //strictSequence作用:
        // 有的时候数组不要求顺序,如{a:$_$}匹配{b:1, a:2}
        // 有的时候需要,如function($_$, $_$)匹配function(a, b) {}
 
        if (!Array.isArray(selector)) {
            selector = [selector];
        }
        let nodePathList = [];
        let matchWildCardList = [];
        const selectorAst = selector.map((item) => {
            const sel = getSelector(
                item,
                this.parseOptions || parseOptions,
                expando
            );
            Iif (!sel.nodeType) {
                throw new Error(
                    '语句类型缺失,请在 https://github.com/thx/gogocode/issues 上提供您的代码样例'
                );
            }
            return sel;
        });
        // const posStrList = [];
        const reachedNodeList = [];
        selectorAst.forEach((item) => {
            const res = find.call(
                ast,
                item.nodeType,
                item.structure,
                strictSequence,
                deep,
                expando
            );
            res.nodePathList.forEach((p, i) => {
                // let posStr = '';
                // if (p.node.content.openStart) {
                //     posStr = `${p.node.content.openStart.startPosition},${p.node.content.openEnd.endPosition}`;
                // } else if (p.node.content.value) {
                //     posStr = `${p.node.content.value.startPosition},${p.node.content.value.endPosition}`;
                // }
                // if (posStrList.indexOf(posStr) == -1) {
                //     // 去重
                //     nodePathList.push(p);
                //     matchWildCardList.push(res.matchWildCardList[i]);
                //     posStrList.push(posStr);
                // }
                if (reachedNodeList.indexOf(p.node.content) == -1) {
                    nodePathList.push(p);
                    matchWildCardList.push(res.matchWildCardList[i]);
                    reachedNodeList.push(p.node.content)
                }
            });
        });
        return {
            nodePathList,
            matchWildCardList,
            pathList: nodePathList,
            extraDataList: matchWildCardList
        };
    },
    getParentListByAst(path) {
        const list = [];
        while (path && path.parentPath) {
            list.push(path.parentPath);
            path = path.parentPath;
        }
        return list;
    },
 
    buildAstByAstStr(
        str,
        astPatialMap = {},
        { isProgram = false, parseOptions } = {}
    ) {
        try {
            const ast = parse(str, parseOptions);
            const program = core.replaceStrByAst(ast, astPatialMap);
            if (program) {
                if (isProgram) {
                    return program;
                } else {
                    Eif (program.content.children && program.content.children[0]) {
                        if (program.content.children.length > 1) {
                            return program.content.children
                        } else if (program.content.children.length == 1) {
                            return program.content.children[0];
                        } else E{
                            return null
                        }
                    }
                }
            } else E{
                return null;
            }
        } catch (e) {
            console.log('buildAstByAstStr failed:' + e);
        }
    },
    replaceStrByAst(ast, astPatialMap = {}) {
        for (let key in astPatialMap) {
            const valueAst = astPatialMap[key];
            const { nodePathList } = core.getAstsBySelector(
                ast,
                `'$_$${key}$_$'`
            );
            if (nodePathList.length > 0) {
                nodePathList[0].replace(valueAst);
            }
        }
        return ast;
    },
    replaceAstByAst(oldAst, newAst, _index) {
        if (oldAst.parent && oldAst.parent.node && oldAst.parent.node.content) {
            oldAst.parent.node.content.children.splice(
                _index,
                1,
                newAst
            );
        } else Eif (oldAst.node.nodeType == 'document') {
            oldAst.node.content.children = [newAst];
        }
    },
    replaceSelBySel(
        ast,
        selector,
        replacer,
        strictSequence,
        parseOptions,
        expando = 'g123o456g789o'
    ) {
        // 用于结构不一致的,整体替换
        if (ast.node) {
            ast = ast.node;
        }
        const { nodePathList, matchWildCardList } = core.getAstsBySelector(
            ast,
            selector,
            {
                strictSequence,
                deep: 'nn',
                parseOptions: this.parseOptions || parseOptions,
                expando
            }
        );
        const originReplacer = replacer;
        nodePathList.forEach((path, i) => {
            const extra = matchWildCardList[i];
            replacer = originReplacer;
            Iif (typeof replacer == 'function') {
                replacer = replacer(extra, path);
            }
            if (Object.keys(extra).length > 0 && typeof replacer == 'string') {
                let newReplacer = replacer;
                for (let key in extra) {
                    if (key.match(/\$\$\$/)) {
                        let key$$$ = key.replace(/\$\$\$/, '');
                        key$$$ == '$' && (key$$$ = '');
                        let join = '\n';
 
                        let wildCardCode = extra[key]
                            .map((item) => {
                                let codeStr = '';
                                if (item.key) {
                                    if (item.value) {
                                        codeStr = `${item.key.content}="${item.value.content}"`;
                                    } else E{
                                        codeStr = item.key.content;
                                    }
                                } else if (item.nodeType == 'text') {
                                    codeStr = item.content.value.content;
                                } else Eif (item.nodeType == 'tag') {
                                    codeStr = generate(item);
                                }
                                try {
                                    // 嵌套replace
                                    const childAst = core.buildAstByAstStr(
                                        generate(item), {}, { isProgram: true }
                                    );
                                    core.replaceSelBySel(
                                        childAst,
                                        selector,
                                        replacer,
                                        strictSequence,
                                        parseOptions,
                                        expando
                                    );
                                    codeStr = generate(childAst);
                                } catch (e) {
                                    //
                                }
                                return codeStr;
                            })
                            .join(join);
                        // 不能都用,连接,还是需要找到$_$
                        newReplacer = newReplacer.replace(
                            '$$$' + key$$$,
                            wildCardCode
                        );
                    } else {
                        let wildCardCode = extra[key][0].value;
                        key == '0' && (key = '');
                        newReplacer = newReplacer
                            .replace(new RegExp(`\\$_\\$${key}`, 'g'), wildCardCode);
                        // 通过选择器替换ast,返回完整ast
                    }
                }
                core.replace(path, newReplacer)
            } else {
                core.replace(path, replacer)
            }
        });
    },
    replace(oldPath, newReplacer) {
        let parentContent, index, isDoc, newNodes;
        Iif (oldPath.node.nodeType == 'document') {
            isDoc = true;
        } else {
            parentContent = oldPath.parent.node.content.children || [];
            index = parentContent.indexOf(oldPath.node);
        }
        if (!newReplacer) {
            // 删除节点
            Eif (index > -1) {
                Iif (isDoc) {
                    oldPath.node.content.children = []
                } else {
                    parentContent.splice(index, 1);
                }
            }
            return;
        } else if (newReplacer.nodeType == 'document') {
            newNodes = newReplacer.content.children || []
        } else if (typeof newReplacer == 'string') {
            // 通过字符串解析为node
            Eif (index > -1) {
                newNodes = core.buildAstByAstStr(
                    newReplacer,
                    {},
                    { isProgram: true }
                ).content.children;
            }
        } else Eif (newReplacer[0] && newReplacer[0].nodePath) {
            // AST实例
            newNodes = [newReplacer.node]
        } else if (newReplacer.type) {
            // AST node
            newNodes = [newReplacer]
        }
        Iif (isDoc) {
            oldPath.node.content.children = newNodes
        } else {
            newNodes.forEach(newNode => {
                newNode.parentRef = oldPath.parent.node;
                parentContent.splice(index, 1, newNode);
            })
        }
    },
    removeAst(ast, selector, { strictSequence, parseOptions, expando } = {}) {
        if (!ast || typeof ast !== 'object') {
            throw new Error('remove failed! first argument mast be object');
        }
        if (
            !selector ||
            (typeof selector !== 'object' &&
                typeof selector !== 'string' &&
                !Array.isArray(selector))
        ) {
            throw new Error(
                'remove failed! first argument mast be object、string or string array'
            );
        }
        // const selectorAst = getSelector(selector, this.parseOptions);
        // console.log(selectorAst)
        const { nodePathList } = core.getAstsBySelector(ast, selector, {
            strictSequence,
            parseOptions,
            expando
        });
        // const { nodePathList } = find.call(ast, selectorAst.nodeType, selectorAst.structure, true, 'nn');
        // console.log(nodePathList)
        nodePathList.forEach((path) => {
            // 多条语句逗号分割的话,只删除一个;一条语句的话,删除父节点
            const parentChildList = path.parent.node.content.children;
            const index = parentChildList.indexOf(path.node);
            parentChildList.splice(index, 1);
        });
    },
    remove(ast) {
        try {
            ast.node.parentRef.content.children.forEach((item, index) => {
                if (item == ast.node) {
                    ast.node.parentRef.content.children.splice(index, 1);
                }
            });
        } catch (e) {
            throw `remove failed! ${e}`;
        }
    }
};
 
module.exports = core;