]> git.gir.st - VimFx.git/blob - extension/packages/find-link.coffee
Merge branch 'hints-z-index' of git://github.com/lydell/VimFx into lydell-hints-z...
[VimFx.git] / extension / packages / find-link.coffee
1 utils = require 'utils'
2
3 # All the following elements qualify as a link
4 LINK_ELEMENTS = [
5 "a"
6 "area[@href]"
7 "button"
8 ]
9
10 # All elements that have one or more of the following properties
11 # qualify as a link
12 LINK_ELEMENT_PROPERTIES = [
13 "@onclick"
14 "@onmousedown"
15 "@onmouseup"
16 "@oncommand"
17 "@role='link'"
18 "@role='button'"
19 "contains(@class, 'button')"
20 ]
21
22 # Find a link that match with the patterns
23 findLinkMatchPattern = (document, patterns) ->
24 links = getLinkElements(document)
25 candidateLinks = []
26
27 # filter visible links that contain patterns and put in candidateLinks
28 for i in [0...links.snapshotLength] by 1
29 link = links.snapshotItem(i)
30
31 if isVisibleElement(link) and isElementMatchPattern(link, patterns)
32 candidateLinks.push(link)
33
34 return if candidateLinks.length == 0
35
36 for link in candidateLinks
37 link.wordCount = link.textContent.trim().split(/\s+/).length
38
39 # favor shorter links, links near the end of a page
40 candidateLinks = candidateLinks.sort (a, b) ->
41 if a.wordCount == b.wordCount then 1 else a.wordCount - b.wordCount
42
43 # match patterns
44 for pattern in patterns
45 # if the pattern is a word, wrapped it in word boundaries.
46 # thus we won't match words like 'previously' to 'previous'
47 exactWordRegex =
48 if /^\b|\b$/.test(pattern)
49 new RegExp('\\b' + pattern + '\\b', 'i')
50 else
51 new RegExp(pattern, 'i')
52
53 for candidateLink in candidateLinks
54 if exactWordRegex.test(candidateLink.textContent)
55 return candidateLink
56
57
58 # Returns elements that qualify as links
59 getLinkElements = do ->
60 elements = [
61 LINK_ELEMENTS...
62 "*[#{ LINK_ELEMENT_PROPERTIES.join(' or ') }]"
63 ]
64
65 return utils.getDomElements(elements)
66
67
68 # Determine if the link is visible
69 isVisibleElement = (element) ->
70 document = element.ownerDocument
71 window = document.defaultView
72
73 # element that isn't visible on the page
74 computedStyle = window.getComputedStyle(element, null)
75 if computedStyle.getPropertyValue('visibility') != 'visible' or
76 computedStyle.getPropertyValue('display') == 'none' or
77 computedStyle.getPropertyValue('opacity') == '0'
78 return false
79
80 # element that has zero dimension
81 clientRect = element.getBoundingClientRect()
82 if clientRect.width == 0 or clientRect.height == 0
83 return false
84
85 return true
86
87
88 # Determine if the link has a pattern matched
89 isElementMatchPattern = (element, patterns) ->
90 for pattern in patterns
91 if element.textContent.toLowerCase().contains(pattern)
92 return true
93
94 return false
95
96 exports.find = findLinkMatchPattern
Imprint / Impressum