]> git.gir.st - VimFx.git/blob - extension/packages/find-link.coffee
DRY getDomElements in utils
[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 match 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 # and ignore those that are more than one word longer than the shortest link
41 candidateLinks =
42 candidateLinks.sort((a, b) ->
43 if a.wordCount == b.wordCount then 1 else a.wordCount - b.wordCount
44 ).filter((a) -> a.wordCount <= candidateLinks[0].wordCount + 1)
45
46 # match patterns
47 for pattern in patterns
48 exactWordRegex =
49 if /\b/.test(pattern[0]) or /\b/.test(pattern[pattern.length - 1])
50 new RegExp '\\b' + pattern + '\\b', 'i'
51 else
52 new RegExp pattern, 'i'
53
54 for candidateLink in candidateLinks
55 if exactWordRegex.test(candidateLink.textContent)
56 return candidateLink
57
58 return null
59
60 # Returns elements that qualify as links
61 getLinkElements = do ->
62 elements = [
63 LINK_ELEMENTS...
64 "*[#{ LINK_ELEMENT_PROPERTIES.join(' or ') }]"
65 ]
66
67 utils.getDomElements(elements)
68
69
70 # Determine if the link is visible
71 isVisibleElement = (element) ->
72 document = element.ownerDocument
73 window = document.defaultView
74
75 # element that isn't visible on the page
76 computedStyle = window.getComputedStyle(element, null)
77 if computedStyle.getPropertyValue('visibility') != 'visible' or
78 computedStyle.getPropertyValue('display') == 'none' or
79 computedStyle.getPropertyValue('opacity') == '0'
80 return false
81
82 # element that has zero dimension
83 clientRect = element.getBoundingClientRect()
84 if clientRect.width == 0 or clientRect.height == 0
85 return false
86
87 return true
88
89 # Determine if the link has a pattern matched
90 isElementMatchPattern = (element, patterns) ->
91 for pattern in patterns
92 if element.textContent.toLowerCase().indexOf(pattern) != -1
93 return true
94
95 return false
96
97 exports.find = findLinkMatchPattern
Imprint / Impressum