-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathsmart-underline.coffee
449 lines (325 loc) · 14.2 KB
/
smart-underline.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
window.SmartUnderline =
init: ->
destroy: ->
return unless window['getComputedStyle'] and document.documentElement.getAttribute
PHI = 1.618034
selectionColor = '#b4d5fe'
linkColorAttrName = 'data-smart-underline-link-color'
linkSmallAttrName = 'data-smart-underline-link-small'
linkLargeAttrName = 'data-smart-underline-link-large'
linkAlwysAttrName = 'data-smart-underline-link-always'
linkBgPosAttrName = 'data-smart-underline-link-background-position'
linkHoverAttrName = 'data-smart-underline-link-hover'
containerIdAttrName = 'data-smart-underline-container-id'
performanceTimes = []
time = -> + new Date
linkContainers = {}
uniqueLinkContainerID = do ->
id = 0
return -> id += 1
clearCanvas = (canvas, context) ->
context.clearRect 0, 0, canvas.width, canvas.height
calculateTextHighestY = (text, canvas, context) ->
clearCanvas canvas, context
context.fillStyle = 'red'
textWidth = context.measureText(text).width
context.fillText text, 0, 0
highestY = undefined
for x in [0..textWidth]
for y in [0..canvas.height]
pixelData = context.getImageData x, y, x + 1, y + 1
r = pixelData.data[0]
alpha = pixelData.data[3]
if r is 255 and alpha > 50 # TODO - tune this alpha?
highestY = y if not highestY
highestY = y if y > highestY
clearCanvas canvas, context
highestY
calculateTypeMetrics = (computedStyle) ->
canvas = document.createElement 'canvas'
context = canvas.getContext '2d'
# Ensure that the canvas size is large enough to
# render the glyphs. 2 * fontSize is sufficient.
canvas.height = canvas.width = 2 * parseInt computedStyle.fontSize, 10
context.textBaseline = 'top'
context.textAlign = 'start'
context.fontStretch = 1
context.angle = 0
# We’d love to use `computedStyle.font` here,
# but Firefox has issues... (TODO: file bug report)
context.font = "#{ computedStyle.fontVariant } #{ computedStyle.fontStyle } #{ computedStyle.fontWeight } #{ computedStyle.fontSize }/#{ computedStyle.lineHeight } #{ computedStyle.fontFamily }"
baselineY = calculateTextHighestY 'I', canvas, context
gLowestPixel = calculateTextHighestY 'g', canvas, context
descenderHeight = gLowestPixel - baselineY
{ baselineY, descenderHeight }
calculateBaselineYRatio = (node) ->
# Roughly taken from underline.js
# http://git.io/A113
test = document.createElement 'div'
test.style.display = 'block'
test.style.position = 'absolute'
test.style.bottom = 0
test.style.right = 0
test.style.width = 0
test.style.height = 0
test.style.margin = 0
test.style.padding = 0
test.style.visibility = 'hidden'
test.style.overflow = 'hidden'
test.style.wordWrap = 'normal'
test.style.whiteSpace = 'nowrap'
small = document.createElement 'span'
large = document.createElement 'span'
small.style.display = 'inline'
large.style.display = 'inline'
# Large numbers help improve accuracy.
small.style.fontSize = '0px'
large.style.fontSize = '2000px'
small.innerHTML = 'X'
large.innerHTML = 'X'
test.appendChild small
test.appendChild large
node.appendChild test
smallRect = small.getBoundingClientRect()
largeRect = large.getBoundingClientRect()
node.removeChild test
# Calculate where the baseline was, percentage-wise.
baselinePositionY = smallRect.top - largeRect.top
height = largeRect.height
baselineYRatio = Math.abs baselinePositionY / height
backgroundPositionYCache = {}
getFirstAvailableFont = (fontFamily) ->
fonts = fontFamily.split ','
for font in fonts
if fontAvailable font
return font
return false
fontAvailable = (font) ->
canvas = document.createElement 'canvas'
context = canvas.getContext '2d'
text = 'abcdefghijklmnopqrstuvwxyz0123456789'
context.font = '72px monospace'
baselineSize = context.measureText(text).width
context.font = "72px #{ font }, monospace"
newSize = context.measureText(text).width
return false if newSize is baselineSize
return true
getUnderlineBackgroundPositionY = (node) ->
computedStyle = getComputedStyle node
firstAvailableFont = getFirstAvailableFont computedStyle.fontFamily
if not firstAvailableFont
cacheKey = "#{ Math.random() }" # AKA, don’t cache
else
cacheKey = "font:#{ firstAvailableFont }size:#{ computedStyle.fontSize }weight:#{ computedStyle.fontWeight }"
cache = backgroundPositionYCache[cacheKey]
return cache if cache
{ baselineY, descenderHeight } = calculateTypeMetrics computedStyle
clientRects = node.getClientRects()
return unless clientRects?.length
adjustment = 1
textHeight = clientRects[0].height - adjustment
# Detect baseline using canvas in all but FF due to
# https://bugzilla.mozilla.org/show_bug.cgi?id=737852
# so we use a DOM technique to approximate it
if -1 < navigator.userAgent.toLowerCase().indexOf 'firefox'
adjustment = .98
baselineYRatio = calculateBaselineYRatio node
baselineY = baselineYRatio * textHeight * adjustment
descenderY = baselineY + descenderHeight
fontSizeInt = parseInt computedStyle.fontSize, 10
minimumCloseness = 3
backgroundPositionY = baselineY + Math.max minimumCloseness, descenderHeight / PHI
if descenderHeight is 4
backgroundPositionY = descenderY - 1
if descenderHeight is 3
backgroundPositionY = descenderY
backgroundPositionYPercent = Math.round 100 * backgroundPositionY / textHeight
if descenderHeight > 2 and fontSizeInt > 10 and backgroundPositionYPercent <= 100
backgroundPositionYCache[cacheKey] = backgroundPositionYPercent
return backgroundPositionYPercent
return
isTransparent = (color) ->
return true if color in ['transparent', 'rgba(0, 0, 0, 0)']
rgbaAlphaMatch = color.match /^rgba\(.*,(.+)\)/i
if rgbaAlphaMatch?.length is 2
alpha = parseFloat rgbaAlphaMatch[1]
if alpha < .0001
return true
return false
getBackgroundColorNode = (node) ->
computedStyle = getComputedStyle node
backgroundColor = computedStyle.backgroundColor
parentNode = node.parentNode
reachedRootNode = not parentNode or parentNode is document.documentElement or parentNode is node
if computedStyle.backgroundImage isnt 'none'
return null
if isTransparent backgroundColor
if reachedRootNode
return node.parentNode or node
else
return getBackgroundColorNode parentNode
else
return node
hasValidLinkContent = (node) ->
# For performance, check for invalid child elements before
# using getComputedStyle to check for display block elements
containsInvalidElements(node) or containsAnyNonInlineElements(node)
containsInvalidElements = (node) ->
for child in node.children
if child.tagName?.toLowerCase() in ['img', 'video', 'canvas', 'embed', 'object', 'iframe']
return true
return containsInvalidElements child
return false
containsAnyNonInlineElements = (node) ->
for child in node.children
style = getComputedStyle child
if style.display isnt 'inline'
return true
return containsAnyNonInlineElements child
return false
getBackgroundColor = (node) ->
backgroundColor = getComputedStyle(node).backgroundColor
if node is document.documentElement and isTransparent backgroundColor
return 'rgb(255, 255, 255)'
else
return backgroundColor
getLinkColor = (node) ->
getComputedStyle(node).color
styleNode = document.createElement 'style'
countParentContainers = (node, count = 0) ->
parentNode = node.parentNode
reachedRootNode = not parentNode or parentNode is document or parentNode is node
if reachedRootNode
return count
else
if parentNode.hasAttribute containerIdAttrName
count += 1
return count + countParentContainers parentNode
sortContainersForCSSPrecendence = (containers) ->
sorted = []
for id, container of containers
container.depth = countParentContainers container.container
sorted.push container
sorted.sort (a, b) ->
return -1 if a.depth < b.depth
return 1 if a.depth > b.depth
return 0
return sorted
isUnderlined = (style) ->
for property in ['textDecorationLine', 'textDecoration']
return true if style[property]?.match /\bunderline\b/
return false
initLink = (link) ->
style = getComputedStyle link
fontSize = parseFloat style.fontSize
if isUnderlined(style) and style.display is 'inline' and fontSize >= 10 and not hasValidLinkContent link
container = getBackgroundColorNode link
if container
backgroundPositionY = getUnderlineBackgroundPositionY link
if backgroundPositionY
link.setAttribute linkColorAttrName, getLinkColor link
link.setAttribute linkBgPosAttrName, backgroundPositionY
id = container.getAttribute containerIdAttrName
if id
linkContainers[id].links.push link
else
id = uniqueLinkContainerID()
container.setAttribute containerIdAttrName, id
linkContainers[id] =
id: id
container: container
links: [link]
return true
return false
renderStyles = ->
styles = ''
containersWithPrecedence = sortContainersForCSSPrecendence linkContainers
linkBackgroundPositionYs = {}
for container in containersWithPrecedence
linkColors = {}
for link in container.links
linkColors[getLinkColor link] = true
linkBackgroundPositionYs[getUnderlineBackgroundPositionY link] = true
backgroundColor = getBackgroundColor container.container
for color of linkColors
linkSelector = (modifier = '') -> """
[#{ containerIdAttrName }="#{ container.id }"] a[#{ linkColorAttrName }="#{ color }"][#{ linkAlwysAttrName }]#{ modifier },
[#{ containerIdAttrName }="#{ container.id }"] a[#{ linkColorAttrName }="#{ color }"][#{ linkHoverAttrName }]#{ modifier }:hover
"""
styles += """
#{ linkSelector() }, #{ linkSelector ':visited' } {
color: #{ color };
text-decoration: none !important;
text-shadow: 0.03em 0 #{ backgroundColor }, -0.03em 0 #{ backgroundColor }, 0 0.03em #{ backgroundColor }, 0 -0.03em #{ backgroundColor }, 0.06em 0 #{ backgroundColor }, -0.06em 0 #{ backgroundColor }, 0.09em 0 #{ backgroundColor }, -0.09em 0 #{ backgroundColor }, 0.12em 0 #{ backgroundColor }, -0.12em 0 #{ backgroundColor }, 0.15em 0 #{ backgroundColor }, -0.15em 0 #{ backgroundColor };
background-color: transparent;
background-image: -webkit-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -webkit-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -webkit-linear-gradient(#{ color }, #{ color });
background-image: -moz-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -moz-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -moz-linear-gradient(#{ color }, #{ color });
background-image: -o-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -o-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -o-linear-gradient(#{ color }, #{ color });
background-image: -ms-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -ms-linear-gradient(#{ backgroundColor }, #{ backgroundColor }), -ms-linear-gradient(#{ color }, #{ color });
background-image: linear-gradient(#{ backgroundColor }, #{ backgroundColor }), linear-gradient(#{ backgroundColor }, #{ backgroundColor }), linear-gradient(#{ color }, #{ color });
-webkit-background-size: 0.05em 1px, 0.05em 1px, 1px 1px;
-moz-background-size: 0.05em 1px, 0.05em 1px, 1px 1px;
background-size: 0.05em 1px, 0.05em 1px, 1px 1px;
background-repeat: no-repeat, no-repeat, repeat-x;
}
#{ linkSelector '::selection' } {
text-shadow: 0.03em 0 #{ selectionColor }, -0.03em 0 #{ selectionColor }, 0 0.03em #{ selectionColor }, 0 -0.03em #{ selectionColor }, 0.06em 0 #{ selectionColor }, -0.06em 0 #{ selectionColor }, 0.09em 0 #{ selectionColor }, -0.09em 0 #{ selectionColor }, 0.12em 0 #{ selectionColor }, -0.12em 0 #{ selectionColor }, 0.15em 0 #{ selectionColor }, -0.15em 0 #{ selectionColor };
background: #{ selectionColor };
}
#{ linkSelector '::-moz-selection' } {
text-shadow: 0.03em 0 #{ selectionColor }, -0.03em 0 #{ selectionColor }, 0 0.03em #{ selectionColor }, 0 -0.03em #{ selectionColor }, 0.06em 0 #{ selectionColor }, -0.06em 0 #{ selectionColor }, 0.09em 0 #{ selectionColor }, -0.09em 0 #{ selectionColor }, 0.12em 0 #{ selectionColor }, -0.12em 0 #{ selectionColor }, 0.15em 0 #{ selectionColor }, -0.15em 0 #{ selectionColor };
background: #{ selectionColor };
}
"""
for backgroundPositionY of linkBackgroundPositionYs
styles += """
a[#{ linkBgPosAttrName }="#{ backgroundPositionY }"] {
background-position: 0% #{ backgroundPositionY }%, 100% #{ backgroundPositionY }%, 0% #{ backgroundPositionY }%;
}
"""
styleNode.innerHTML = styles
initLinkOnHover = ->
link = @
alreadyMadeSmart = link.hasAttribute linkHoverAttrName
unless alreadyMadeSmart
madeSmart = initLink link
if madeSmart
link.setAttribute linkHoverAttrName, ''
renderStyles()
init = (options) ->
startTime = time()
links = document.querySelectorAll "#{ if options.location then options.location + ' ' else '' }a"
return unless links.length
linkContainers = {}
for link in links
madeSmart = initLink link
if madeSmart
link.setAttribute linkAlwysAttrName, ''
else
link.removeEventListener 'mouseover', initLinkOnHover
link.addEventListener 'mouseover', initLinkOnHover
renderStyles()
document.body.appendChild styleNode
performanceTimes.push time() - startTime
destroy = ->
styleNode.parentNode?.removeChild styleNode
Array::forEach.call document.querySelectorAll("[#{ linkHoverAttrName }]"), (node) ->
node.removeEventListener initLinkOnHover
for attribute in [linkColorAttrName, linkSmallAttrName, linkLargeAttrName, linkAlwysAttrName, linkHoverAttrName, containerIdAttrName]
Array::forEach.call document.querySelectorAll("[#{ attribute }]"), (node) ->
node.removeAttribute attribute
window.SmartUnderline =
init: (options = {}) ->
if document.readyState is 'loading'
window.addEventListener 'DOMContentLoaded', ->
init options
window.addEventListener 'load', ->
destroy()
init options
else
destroy()
init options
destroy: ->
destroy()
performanceTimes: ->
performanceTimes