* 解析查询串
(selector)
| 237 | * 解析查询串 |
| 238 | */ |
| 239 | parse(selector) { |
| 240 | const segment = [{tag: '*'}] |
| 241 | const regexp = this.regexp |
| 242 | |
| 243 | const onProcess = (all, idAll, id, tagAll, classAll, className, pseudoAll, pseudoName, pseudoParam, attrAll, attrName, attrOpr, attrVal, kinshipAll, kinship) => { |
| 244 | if (idAll) { |
| 245 | // id 选择器 |
| 246 | segment[segment.length - 1].id = id |
| 247 | } else if (tagAll) { |
| 248 | // 标签选择器 |
| 249 | segment[segment.length - 1].tag = tagAll.toLowerCase() |
| 250 | } else if (classAll) { |
| 251 | // 类选择器 |
| 252 | const currentRule = segment[segment.length - 1] |
| 253 | currentRule.class = currentRule.class || [] |
| 254 | |
| 255 | currentRule.class.push(className) |
| 256 | } else if (pseudoAll) { |
| 257 | // 伪类选择器 |
| 258 | const currentRule = segment[segment.length - 1] |
| 259 | currentRule.pseudo = currentRule.pseudo || [] |
| 260 | pseudoName = pseudoName.toLowerCase() |
| 261 | |
| 262 | const pseudo = {name: pseudoName} |
| 263 | |
| 264 | if (pseudoParam) pseudoParam = pseudoParam.trim() |
| 265 | if (pseudoName === 'nth-child' || pseudoName === 'nth-of-type') { |
| 266 | // 处理 nth-child 伪类,参数统一处理成 an + b 的格式 |
| 267 | pseudoParam = pseudoParam.replace(/\s+/g, '') |
| 268 | |
| 269 | if (pseudoParam === 'even') { |
| 270 | // 偶数个 |
| 271 | pseudoParam = {a: 2, b: 2} |
| 272 | } else if (pseudoParam === 'odd') { |
| 273 | // 奇数个 |
| 274 | pseudoParam = {a: 2, b: 1} |
| 275 | } else if (pseudoParam) { |
| 276 | // 其他表达式 |
| 277 | const nthParsed = pseudoParam.match(/^(?:(\d+)|(\d*)?n([+-]\d+)?)$/) |
| 278 | |
| 279 | if (!nthParsed) { |
| 280 | // 解析失败 |
| 281 | pseudoParam = {a: 0, b: 1} |
| 282 | } else if (nthParsed[1]) { |
| 283 | // 纯数字 |
| 284 | pseudoParam = {a: 0, b: +nthParsed[1]} |
| 285 | } else { |
| 286 | // 表达式 |
| 287 | pseudoParam = { |
| 288 | a: nthParsed[2] ? +nthParsed[2] : 1, |
| 289 | b: nthParsed[3] ? +nthParsed[3] : 0, |
| 290 | } |
| 291 | } |
| 292 | } else { |
| 293 | // 默认取第一个 |
| 294 | pseudoParam = {a: 0, b: 1} |
| 295 | } |
| 296 | } |