1 utils = require 'utils'
3 # All the following elements qualify as a link
10 # All elements that have one or more of the following properties
12 LINK_ELEMENT_PROPERTIES = [
19 "contains(@class, 'button')"
22 # Find a link that match with the patterns
23 findLinkMatchPattern = (document, patterns) ->
24 links = getLinkElements(document)
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)
31 if isVisibleElement(link) and isElementMatchPattern(link, patterns)
32 candidateLinks.push(link)
34 return if candidateLinks.length == 0
36 for link in candidateLinks
37 link.wordCount = link.textContent.trim().split(/\s+/).length
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
45 # match patterns. Sort them to match shorter patterns first.
46 # The latter is to prevent matching first links that contain
47 # longer words like `next`, `more`, etc.
48 for pattern in patterns.sort((a, b) -> a.length > b.length)
50 # if the pattern is a word, wrapped it in word boundaries.
51 # thus we won't match words like 'previously' to 'previous'
53 if /^\b|\b$/.test(pattern)
54 new RegExp('\\b' + pattern + '\\b', 'i')
56 new RegExp(pattern, 'i')
58 for candidateLink in candidateLinks
59 if exactWordRegex.test(candidateLink.textContent)
60 results.push(candidateLink)
65 # Returns elements that qualify as links
66 getLinkElements = do ->
69 "*[#{ LINK_ELEMENT_PROPERTIES.join(' or ') }]"
72 return utils.getDomElements(elements)
75 # Determine if the link is visible
76 isVisibleElement = (element) ->
77 document = element.ownerDocument
78 window = document.defaultView
80 # element that isn't visible on the page
81 computedStyle = window.getComputedStyle(element, null)
82 if computedStyle.getPropertyValue('visibility') != 'visible' or
83 computedStyle.getPropertyValue('display') == 'none' or
84 computedStyle.getPropertyValue('opacity') == '0'
87 # element that has zero dimension
88 clientRect = element.getBoundingClientRect()
89 if clientRect.width == 0 or clientRect.height == 0
95 # Determine if the link has a pattern matched
96 isElementMatchPattern = (element, patterns) ->
97 for pattern in patterns
98 if element.textContent.toLowerCase().contains(pattern)
103 exports.find = findLinkMatchPattern