summaryrefslogtreecommitdiffstats
path: root/afb-client/bower_components/tether/coffee/tether.coffee
blob: 3df246fe2e4d2cba7ee0ecf901e253702ba27afc (plain)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
if not @Tether?
  throw new Error "You must include the utils.js file before tether.js"

Tether = @Tether

{getScrollParent, getSize, getOuterSize, getBounds, getOffsetParent, extend, addClass, removeClass, updateClasses, defer, flush, getScrollBarSize} = Tether.Utils

within = (a, b, diff=1) ->
  a + diff >= b >= a - diff

transformKey = do ->
  el = document.createElement 'div'

  for key in ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']
    if el.style[key] isnt undefined
      return key

tethers = []

position = ->
  for tether in tethers
    tether.position(false)

  flush()

now = ->
  performance?.now?() ? +new Date

do ->
  lastCall = null
  lastDuration = null
  pendingTimeout = null

  tick = ->
    if lastDuration? and lastDuration > 16
      # We voluntarily throttle ourselves if we can't manage 60fps
      lastDuration = Math.min(lastDuration - 16, 250)

      # Just in case this is the last event, remember to position just once more
      pendingTimeout = setTimeout tick, 250
      return

    if lastCall? and (now() - lastCall) < 10
      # Some browsers call events a little too frequently, refuse to run more than is reasonable
      return

    if pendingTimeout?
      clearTimeout pendingTimeout
      pendingTimeout = null

    lastCall = now()

    position()

    lastDuration = now() - lastCall

  for event in ['resize', 'scroll', 'touchmove']
    window.addEventListener event, tick

MIRROR_LR =
  center: 'center'
  left: 'right'
  right: 'left'

MIRROR_TB =
  middle: 'middle'
  top: 'bottom'
  bottom: 'top'

OFFSET_MAP =
  top: 0
  left: 0
  middle: '50%'
  center: '50%'
  bottom: '100%'
  right: '100%'

autoToFixedAttachment = (attachment, relativeToAttachment) ->
  {left, top} = attachment

  if left is 'auto'
    left = MIRROR_LR[relativeToAttachment.left]

  if top is 'auto'
    top = MIRROR_TB[relativeToAttachment.top]

  {left, top}

attachmentToOffset = (attachment) ->
  return {
    left: OFFSET_MAP[attachment.left] ? attachment.left
    top: OFFSET_MAP[attachment.top] ? attachment.top
  }

addOffset = (offsets...) ->
  out = {top: 0, left: 0}

  for {top, left} in offsets
    if typeof top is 'string'
      top = parseFloat(top, 10)
    if typeof left is 'string'
      left = parseFloat(left, 10)

    out.top += top
    out.left += left

  out

offsetToPx = (offset, size) ->
  if typeof offset.left is 'string' and offset.left.indexOf('%') isnt -1
    offset.left = parseFloat(offset.left, 10) / 100 * size.width
  if typeof offset.top is 'string' and offset.top.indexOf('%') isnt -1
    offset.top = parseFloat(offset.top, 10) / 100 * size.height

  offset

parseAttachment = parseOffset = (value) ->
  [top, left] = value.split(' ')

  {top, left}

class _Tether
  @modules: []

  constructor: (options) ->
    tethers.push @

    @history = []

    @setOptions options, false

    for module in Tether.modules
      module.initialize?.call(@)

    @position()

  getClass: (key) ->
    if @options.classes?[key]
      @options.classes[key]
    else if @options.classes?[key] isnt false
      if @options.classPrefix
        "#{ @options.classPrefix }-#{ key }"
      else
        key
    else
      ''

  setOptions: (@options, position=true) ->
    defaults =
      offset: '0 0'
      targetOffset: '0 0'
      targetAttachment: 'auto auto'
      classPrefix: 'tether'

    @options = extend defaults, @options

    {@element, @target, @targetModifier} = @options

    if @target is 'viewport'
      @target = document.body
      @targetModifier = 'visible'
    else if @target is 'scroll-handle'
      @target = document.body
      @targetModifier = 'scroll-handle'

    for key in ['element', 'target']
      if not @[key]?
        throw new Error "Tether Error: Both element and target must be defined"

      if @[key].jquery?
        @[key] = @[key][0]
      else if typeof @[key] is 'string'
        @[key] = document.querySelector @[key]

    addClass @element, @getClass 'element'
    addClass @target, @getClass 'target'

    if not @options.attachment
      throw new Error "Tether Error: You must provide an attachment"

    @targetAttachment = parseAttachment @options.targetAttachment
    @attachment = parseAttachment @options.attachment
    @offset = parseOffset @options.offset
    @targetOffset = parseOffset @options.targetOffset

    if @scrollParent?
      @disable()

    if @targetModifier is 'scroll-handle'
      @scrollParent = @target
    else
      @scrollParent = getScrollParent @target

    unless @options.enabled is false
      @enable(position)

  getTargetBounds: ->
    if @targetModifier?
      switch @targetModifier
        when 'visible'
          if @target is document.body
            {top: pageYOffset, left: pageXOffset, height: innerHeight, width: innerWidth}
          else
            bounds = getBounds @target

            out =
              height: bounds.height
              width: bounds.width
              top: bounds.top
              left: bounds.left

            out.height = Math.min(out.height, bounds.height - (pageYOffset - bounds.top))
            out.height = Math.min(out.height, bounds.height - ((bounds.top + bounds.height) - (pageYOffset + innerHeight)))
            out.height = Math.min(innerHeight, out.height)
            out.height -= 2

            out.width = Math.min(out.width, bounds.width - (pageXOffset - bounds.left))
            out.width = Math.min(out.width, bounds.width - ((bounds.left + bounds.width) - (pageXOffset + innerWidth)))
            out.width = Math.min(innerWidth, out.width)
            out.width -= 2

            if out.top < pageYOffset
              out.top = pageYOffset
            if out.left < pageXOffset
              out.left = pageXOffset

            out

        when 'scroll-handle'
          target = @target
          if target is document.body
            target = document.documentElement

            bounds =
              left: pageXOffset
              top: pageYOffset
              height: innerHeight
              width: innerWidth
          else
            bounds = getBounds target

          style = getComputedStyle target

          hasBottomScroll = target.scrollWidth > target.clientWidth or 'scroll' is [style.overflow, style.overflowX] or @target isnt document.body

          scrollBottom = 0
          if hasBottomScroll
            scrollBottom = 15

          height = bounds.height - parseFloat(style.borderTopWidth) - parseFloat(style.borderBottomWidth) - scrollBottom

          out =
            width: 15
            height: height * 0.975 * (height / target.scrollHeight)
            left: bounds.left + bounds.width - parseFloat(style.borderLeftWidth) - 15

          fitAdj = 0
          if height < 408 and @target is document.body
            fitAdj = -0.00011 * Math.pow(height, 2) - 0.00727 * height + 22.58

          if @target isnt document.body
            out.height = Math.max out.height, 24

          scrollPercentage = @target.scrollTop / (target.scrollHeight - height)
          out.top = scrollPercentage * (height - out.height - fitAdj) + bounds.top + parseFloat(style.borderTopWidth)

          if @target is document.body
            out.height = Math.max out.height, 24

          out
    else
      getBounds @target

  clearCache: ->
    @_cache = {}

  cache: (k, getter) ->
    # More than one module will often need the same DOM info, so
    # we keep a cache which is cleared on each position call
    @_cache ?= {}

    if not @_cache[k]?
      @_cache[k] = getter.call(@)

    @_cache[k]

  enable: (position=true) ->
    addClass @target, @getClass 'enabled'
    addClass @element, @getClass 'enabled'
    @enabled = true

    if @scrollParent isnt document
      @scrollParent.addEventListener 'scroll', @position

    if position
      @position()

  disable: ->
    removeClass @target, @getClass 'enabled'
    removeClass @element, @getClass 'enabled'
    @enabled = false

    if @scrollParent?
      @scrollParent.removeEventListener 'scroll', @position

  destroy: ->
    @disable()

    for tether, i in tethers
      if tether is @
        tethers.splice i, 1
        break

  updateAttachClasses: (elementAttach=@attachment, targetAttach=@targetAttachment) ->
    sides = ['left', 'top', 'bottom', 'right', 'middle', 'center']

    if @_addAttachClasses?.length
        # updateAttachClasses can be called more than once in a position call, so
        # we need to clean up after ourselves such that when the last defer gets
        # ran it doesn't add any extra classes from previous calls.
        @_addAttachClasses.splice 0, @_addAttachClasses.length

    add = @_addAttachClasses ?= []
    add.push "#{ @getClass('element-attached') }-#{ elementAttach.top }" if elementAttach.top
    add.push "#{ @getClass('element-attached') }-#{ elementAttach.left }" if elementAttach.left
    add.push "#{ @getClass('target-attached') }-#{ targetAttach.top }" if targetAttach.top
    add.push "#{ @getClass('target-attached') }-#{ targetAttach.left }" if targetAttach.left

    all = []
    all.push "#{ @getClass('element-attached') }-#{ side }" for side in sides
    all.push "#{ @getClass('target-attached') }-#{ side }" for side in sides

    defer =>
      return unless @_addAttachClasses?

      updateClasses @element, @_addAttachClasses, all
      updateClasses @target, @_addAttachClasses, all

      @_addAttachClasses = undefined

  position: (flushChanges=true) =>
    # flushChanges commits the changes immediately, leave true unless you are positioning multiple
    # tethers (in which case call Tether.Utils.flush yourself when you're done)

    return unless @enabled

    @clearCache()

    # Turn 'auto' attachments into the appropriate corner or edge
    targetAttachment = autoToFixedAttachment(@targetAttachment, @attachment)

    @updateAttachClasses @attachment, targetAttachment

    elementPos = @cache 'element-bounds', => getBounds @element
    {width, height} = elementPos

    if width is 0 and height is 0 and @lastSize?
      # We cache the height and width to make it possible to position elements that are
      # getting hidden.
      {width, height} = @lastSize
    else
      @lastSize = {width, height}

    targetSize = targetPos = @cache 'target-bounds', => @getTargetBounds()

    # Get an actual px offset from the attachment
    offset = offsetToPx attachmentToOffset(@attachment), {width, height}
    targetOffset = offsetToPx attachmentToOffset(targetAttachment), targetSize

    manualOffset = offsetToPx(@offset, {width, height})
    manualTargetOffset = offsetToPx(@targetOffset, targetSize)

    # Add the manually provided offset
    offset = addOffset offset, manualOffset
    targetOffset = addOffset targetOffset, manualTargetOffset

    # It's now our goal to make (element position + offset) == (target position + target offset)
    left = targetPos.left + targetOffset.left - offset.left
    top = targetPos.top + targetOffset.top - offset.top

    for module in Tether.modules
      ret = module.position.call(@, {left, top, targetAttachment, targetPos, @attachment, elementPos, offset, targetOffset, manualOffset, manualTargetOffset, scrollbarSize})

      if not ret? or typeof ret isnt 'object'
        continue
      else if ret is false
        return false
      else
        {top, left} = ret

    # We describe the position three different ways to give the optimizer
    # a chance to decide the best possible way to position the element
    # with the fewest repaints.
    next = {
      # It's position relative to the page (absolute positioning when
      # the element is a child of the body)
      page:
        top: top
        left: left

      # It's position relative to the viewport (fixed positioning)
      viewport:
        top: top - pageYOffset
        bottom: pageYOffset - top - height + innerHeight
        left: left - pageXOffset
        right: pageXOffset - left - width + innerWidth
    }

    if document.body.scrollWidth > window.innerWidth
      scrollbarSize = @cache 'scrollbar-size', getScrollBarSize
      next.viewport.bottom -= scrollbarSize.height

    if document.body.scrollHeight > window.innerHeight
      scrollbarSize = @cache 'scrollbar-size', getScrollBarSize
      next.viewport.right -= scrollbarSize.width

    if document.body.style.position not in ['', 'static'] or document.body.parentElement.style.position not in ['', 'static']
      # Absolute positioning in the body will be relative to the page, not the 'initial containing block'
      next.page.bottom = document.body.scrollHeight - top - height
      next.page.right = document.body.scrollWidth - left - width

    if @options.optimizations?.moveElement isnt false and not @targetModifier?
      offsetParent = @cache 'target-offsetparent', => getOffsetParent @target
      offsetPosition = @cache 'target-offsetparent-bounds', -> getBounds offsetParent
      offsetParentStyle = getComputedStyle offsetParent
      elementStyle = getComputedStyle @element
      offsetParentSize = offsetPosition

      offsetBorder = {}
      for side in ['Top', 'Left', 'Bottom', 'Right']
        offsetBorder[side.toLowerCase()] = parseFloat offsetParentStyle["border#{ side }Width"]

      offsetPosition.right = document.body.scrollWidth - offsetPosition.left - offsetParentSize.width + offsetBorder.right
      offsetPosition.bottom = document.body.scrollHeight - offsetPosition.top - offsetParentSize.height + offsetBorder.bottom

      if next.page.top >= (offsetPosition.top + offsetBorder.top) and next.page.bottom >= offsetPosition.bottom
        if next.page.left >= (offsetPosition.left + offsetBorder.left) and next.page.right >= offsetPosition.right
          # We're within the visible part of the target's scroll parent

          scrollTop = offsetParent.scrollTop
          scrollLeft = offsetParent.scrollLeft

          # It's position relative to the target's offset parent (absolute positioning when
          # the element is moved to be a child of the target's offset parent).
          next.offset =
            top: next.page.top - offsetPosition.top + scrollTop - offsetBorder.top
            left: next.page.left - offsetPosition.left + scrollLeft - offsetBorder.left


    # We could also travel up the DOM and try each containing context, rather than only
    # looking at the body, but we're gonna get diminishing returns.

    @move next

    @history.unshift next

    if @history.length > 3
      @history.pop()

    if flushChanges
      flush()

    true

  move: (position) ->
    return if not @element.parentNode?

    same = {}

    for type of position
      same[type] = {}

      for key of position[type]
        found = false

        for point in @history
          unless within(point[type]?[key], position[type][key])
            found = true
            break

        if not found
          same[type][key] = true

    css = {top: '', left: '', right: '', bottom: ''}

    transcribe = (same, pos) =>
      if @options.optimizations?.gpu isnt false
        if same.top
          css.top = 0
          yPos = pos.top
        else
          css.bottom = 0
          yPos = -pos.bottom

        if same.left
          css.left = 0
          xPos = pos.left
        else
          css.right = 0
          xPos = -pos.right


        css[transformKey] = "translateX(#{ Math.round xPos }px) translateY(#{ Math.round yPos }px)"

        if transformKey isnt 'msTransform'
          # The Z transform will keep this in the GPU (faster, and prevents artifacts),
          # but IE9 doesn't support 3d transforms and will choke.
          css[transformKey] += " translateZ(0)"

      else
        if same.top
          css.top = "#{ pos.top }px"
        else
          css.bottom = "#{ pos.bottom }px"

        if same.left
          css.left = "#{ pos.left }px"
        else
          css.right = "#{ pos.right }px"

    moved = false
    if (same.page.top or same.page.bottom) and (same.page.left or same.page.right)
      css.position = 'absolute'
      transcribe same.page, position.page

    else if (same.viewport.top or same.viewport.bottom) and (same.viewport.left or same.viewport.right)
      css.position = 'fixed'

      transcribe same.viewport, position.viewport

    else if same.offset? and same.offset.top and same.offset.left
      css.position = 'absolute'

      offsetParent = @cache 'target-offsetparent', => getOffsetParent @target

      if getOffsetParent(@element) isnt offsetParent
        defer =>
          @element.parentNode.removeChild @element
          offsetParent.appendChild @element

      transcribe same.offset, position.offset

      moved = true

    else
      css.position = 'absolute'
      transcribe {top: true, left: true}, position.page

    if not moved and @element.parentNode.tagName isnt 'BODY'
      @element.parentNode.removeChild @element
      document.body.appendChild @element

    # Any css change will trigger a repaint, so let's avoid one if nothing changed
    writeCSS = {}
    write = false
    for key, val of css
      elVal = @element.style[key]

      if elVal isnt '' and val isnt '' and key in ['top', 'left', 'bottom', 'right']
        elVal = parseFloat elVal
        val = parseFloat val

      if elVal isnt val
        write = true
        writeCSS[key] = css[key]

    if write
      defer =>
        extend @element.style, writeCSS

Tether.position = position

@Tether = extend _Tether, Tether