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
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'
48 if /^\b|\b$/.test(pattern)
49 new RegExp('\\b' + pattern + '\\b', 'i')
51 new RegExp(pattern, 'i')
53 for candidateLink in candidateLinks
54 if exactWordRegex.test(candidateLink.textContent)
58 # Returns elements that qualify as links
59 getLinkElements = do ->
62 "*[#{ LINK_ELEMENT_PROPERTIES.join(' or ') }]"
65 return utils.getDomElements(elements)
68 # Determine if the link is visible
69 isVisibleElement = (element) ->
70 document = element.ownerDocument
71 window = document.defaultView
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'
80 # element that has zero dimension
81 clientRect = element.getBoundingClientRect()
82 if clientRect.width == 0 or clientRect.height == 0
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)
96 exports.find = findLinkMatchPattern