Skip to content

Commit 8f32607

Browse files
committed
WIP
1 parent e55bf30 commit 8f32607

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

es6/xray.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
const findSpecimens = () => {
2+
const startComments = getComments(document.body)
3+
.filter(node => node.textContent.indexOf('XRAY START') !== -1)
4+
5+
return startComments.reduce((specimens, comment) => {
6+
const [_, id, path] = comment.data.match(/^XRAY START (\d+) (.*)$/)
7+
const contents = []
8+
let el = comment.nextSibling
9+
10+
while (el.nodeType !== 8 && el.textContent !== 'XRAY END ' + id) {
11+
if (el.nodeType === 1 && el.tagName !== 'script')
12+
contents.push(el)
13+
el = el.nextSibling
14+
}
15+
16+
if (contents.length > 0) {
17+
specimens.push(new Specimen(path, contents))
18+
}
19+
20+
return specimens
21+
}, [])
22+
}
23+
24+
class Specimen {
25+
constructor(path, contents) {
26+
this.path = path
27+
this.contents = contents
28+
}
29+
30+
getBox() {
31+
if (this.contents.length === 0) {
32+
return { width: 0, height: 0, top: 0, left: 0 }
33+
}
34+
35+
const widths = this.contents.map(node => node.offsetWidth || 0)
36+
const heights = this.contents.map(node => node.offsetHeight || 0)
37+
const lefts = this.contents.map(node => node.offsetLeft || 0)
38+
const tops = this.contents.map(node => node.offsetTop || 0)
39+
40+
return {
41+
width: Math.max(...widths),
42+
height: Math.max(...heights),
43+
left: Math.min(...lefts),
44+
top: Math.min(...tops)
45+
}
46+
}
47+
}
48+
49+
// There is no CSS selector for finding comment nodes.
50+
function getComments(context) {
51+
var foundComments = []
52+
var stack = [context]
53+
54+
while (stack.length > 0) {
55+
var el = stack.pop()
56+
for (var i = 0; i < el.childNodes.length; i++) {
57+
var node = el.childNodes[i]
58+
if (node.nodeType === Node.COMMENT_NODE) {
59+
foundComments.push(node)
60+
} else {
61+
stack.push(node)
62+
}
63+
}
64+
}
65+
return foundComments
66+
}
67+
68+
document.addEventListener('DOMContentLoaded', function() {
69+
console.log(findSpecimens().map(x => x.getBox()))
70+
})

0 commit comments

Comments
 (0)