This repository has been archived by the owner on Jan 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.coffee
96 lines (74 loc) · 2.02 KB
/
index.coffee
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
_ = require 'lodash'
cssauron = require 'cssauron'
language = cssauron(
tag: 'tagName'
children: 'children'
parent: 'parent'
contents: 'contents'
attr: (node, attr) ->
val = node.attributes?[attr]
if val is undefined
return node[attr]
return val
class: (node) ->
node.className
id: (node) ->
node.id
)
traverse = (vtree, fn) ->
fn vtree
_.map vtree.children, (vtree) ->
traverse vtree, fn
getTextContent = (vtree) ->
if vtree.type is 'VirtualText'
return vtree.text
if _.isEmpty vtree.children
return ''
_.map(vtree.children, getTextContent).join('')
isHook = (hook) ->
hook and _.isFunction(hook.hook) and not hook.hasOwnProperty 'hook'
mapTree = (vtree, parent) ->
if vtree.type is 'VirtualText'
return {
contents: vtree.text
parent: parent
vtree: vtree
}
if vtree.type is 'Thunk'
return mapTree vtree.render(vtree.vnode), parent
# FIXME: A side effect of virtual-hyperscript not being user friendly
if isHook vtree.properties.value
vtree.properties.value = vtree.properties.value.value
node = _.defaults
tagName: vtree.tagName
contents: getTextContent vtree
parent: parent
vtree: vtree
, vtree.properties
node.children = _.map vtree.children, (child) ->
mapTree child, node
return node
capitalizeTags = (selectorString) ->
selectorString.replace /(^|\s)(\w+)/g, (all) ->
all.replace /\w+/g, (tag) ->
tag.toUpperCase()
queryAll = _.curry (tree, selectorString) ->
selector = language capitalizeTags selectorString
node = mapTree(tree)
matched = []
# Traverse each node in the tree and see if it matches our selector
traverse node, (node) ->
result = selector(node)
if result
unless _.isArray result
result = [result]
matched.push.apply matched, result
return
if _.isEmpty matched
return null
matched
queryOne = _.curry (tree, selectorString) ->
_.first queryAll tree, selectorString
_.assign queryOne,
all: queryAll
module.exports = queryOne