forked from gajus/surgeon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosestSubroutine.js
64 lines (48 loc) · 1.47 KB
/
closestSubroutine.js
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
// @flow
import cheerio from 'cheerio';
import {
SurgeonError,
} from '../errors';
import type {
SubroutineType,
} from '../types';
import Logger from '../Logger';
const log = Logger.child({
namespace: 'subroutine:closest',
});
// eslint-disable-next-line flowtype/no-weak-types
const closestSubroutine: SubroutineType = (subject: any, [cssSelector], {evaluator}) => {
log.debug('selecting "%s"', cssSelector);
if (!evaluator.isElement(subject)) {
throw new SurgeonError('Unexpected value. Value must be an element.');
}
let parentElement = subject;
while (true) {
if (parentElement.filter(cssSelector).length) {
return parentElement;
}
const previousNodes = parentElement
.prevAll()
.toArray()
.map((previousNode) => {
return cheerio(previousNode);
});
for (const previousNode of previousNodes) {
const directMatch = previousNode.filter(cssSelector);
if (directMatch.length) {
return directMatch.last();
}
const deepMatches = previousNode.find(cssSelector);
if (deepMatches.length) {
return deepMatches.last();
}
}
const maybeNextParentElement = parentElement.parent();
if (!maybeNextParentElement || maybeNextParentElement[0] === parentElement[0]) {
break;
}
parentElement = maybeNextParentElement;
}
throw new SurgeonError('Cannot find a preceding node matching the provided CSS selector.');
};
export default closestSubroutine;