/
util.coffee
2135 lines (1817 loc) · 54.2 KB
/
util.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
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###**
Utility functions
=================
Unpoly comes with a number of utility functions
that might save you from loading something like [Lodash](https://lodash.com/).
@class up.util
###
up.util = (($) ->
###**
A function that does nothing.
@function up.util.noop
@experimental
###
noop = (->)
###**
A function that returns a resolved promise.
@function up.util.asyncNoop
@internal
###
asyncNoop = -> Promise.resolve()
###**
Ensures that the given function can only be called a single time.
Subsequent calls will return the return value of the first call.
Note that this is a simple implementation that
doesn't distinguish between argument lists.
@function up.util.memoize
@internal
###
memoize = (func) ->
cachedValue = undefined
cached = false
(args...) ->
if cached
cachedValue
else
cached = true
cachedValue = func(args...)
###**
Returns if the given port is the default port for the given protocol.
@function up.util.isStandardPort
@internal
###
isStandardPort = (protocol, port) ->
port = port.toString()
((port == "" || port == "80") && protocol == 'http:') || (port == "443" && protocol == 'https:')
###**
Normalizes relative paths and absolute paths to a full URL
that can be checked for equality with other normalized URLs.
By default hashes are ignored, search queries are included.
@function up.util.normalizeUrl
@param {boolean} [options.hash=false]
Whether to include an `#hash` anchor in the normalized URL
@param {boolean} [options.search=true]
Whether to include a `?query` string in the normalized URL
@param {boolean} [options.stripTrailingSlash=false]
Whether to strip a trailing slash from the pathname
@internal
###
normalizeUrl = (urlOrAnchor, options) ->
parts = parseUrl(urlOrAnchor)
normalized = parts.protocol + "//" + parts.hostname
normalized += ":#{parts.port}" unless isStandardPort(parts.protocol, parts.port)
pathname = parts.pathname
# Some IEs don't include a leading slash in the #pathname property.
# We have seen this in IE11 and W3Schools claims it happens in IE9 or earlier
# http://www.w3schools.com/jsref/prop_anchor_pathname.asp
pathname = "/#{pathname}" unless pathname[0] == '/'
pathname = pathname.replace(/\/$/, '') if options?.stripTrailingSlash == true
normalized += pathname
normalized += parts.search unless options?.search == false
normalized += parts.hash if options?.hash == true
normalized
isCrossDomain = (targetUrl) ->
currentUrl = parseUrl(location.href)
targetUrl = parseUrl(targetUrl)
currentUrl.protocol != targetUrl.protocol || currentUrl.host != targetUrl.host
###**
Parses the given URL into components such as hostname and path.
If the given URL is not fully qualified, it is assumed to be relative
to the current page.
@function up.util.parseUrl
@return {Object}
The parsed URL as an object with
`protocol`, `hostname`, `port`, `pathname`, `search` and `hash`
properties.
@experimental
###
parseUrl = (urlOrAnchor) ->
# In case someone passed us a $link, unwrap it
if isJQuery(urlOrAnchor)
urlOrAnchor = getElement(urlOrAnchor)
# If we are handed a parsed URL, just return it
if urlOrAnchor.pathname
return urlOrAnchor
anchor = $('<a>').attr(href: urlOrAnchor).get(0)
# In IE11 the #hostname and #port properties of such a link are empty
# strings. However, we can fix this by assigning the anchor its own
# href because computer:
# https://gist.github.com/jlong/2428561#comment-1461205
anchor.href = anchor.href if isBlank(anchor.hostname)
anchor
###**
@function up.util.normalizeMethod
@internal
###
normalizeMethod = (method) ->
if method
method.toUpperCase()
else
'GET'
###**
@function up.util.methodAllowsPayload
@internal
###
methodAllowsPayload = (method) ->
method != 'GET' && method != 'HEAD'
###**
@function $createElementFromSelector
@internal
###
$createElementFromSelector = (selector) ->
path = selector.split(/[ >]/)
$root = null
for depthSelector, iteration in path
conjunction = depthSelector.match(/(^|\.|\#)[A-Za-z0-9\-_]+/g)
tag = "div"
classes = []
id = null
for expression in conjunction
switch expression[0]
when "."
classes.push expression.substr(1)
when "#"
id = expression.substr(1)
else
tag = expression
html = "<" + tag
html += " class=\"" + classes.join(" ") + "\"" if classes.length
html += " id=\"" + id + "\"" if id
html += ">"
$element = $(html)
$element.appendTo($parent) if $parent
$root = $element if iteration == 0
$parent = $element
$root
###**
@function $createPlaceHolder
@internal
###
$createPlaceholder = (selector, container = document.body) ->
$placeholder = $createElementFromSelector(selector)
$placeholder.addClass('up-placeholder')
$placeholder.appendTo(container)
$placeholder
###**
Returns a CSS selector that matches the given element as good as possible.
This uses, in decreasing order of priority:
- The element's `up-id` attribute
- The element's ID
- The element's name
- The element's classes
- The element's tag names
@function up.util.selectorForElement
@param {string|Element|jQuery}
The element for which to create a selector.
@experimental
###
selectorForElement = (element) ->
$element = $(element)
selector = undefined
tagName = $element.prop('tagName').toLowerCase()
if upId = presence($element.attr("up-id"))
selector = attributeSelector('up-id', upId)
else if id = presence($element.attr("id"))
if id.match(/^[a-z0-9\-_]+$/i)
selector = "##{id}"
else
selector = attributeSelector('id', id)
else if name = presence($element.attr("name"))
selector = tagName + attributeSelector('name', name)
else if classes = presence(nonUpClasses($element))
selector = ''
for klass in classes
selector += ".#{klass}"
else if ariaLabel = presence($element.attr("aria-label"))
selector = attributeSelector('aria-label', ariaLabel)
else
selector = tagName
selector
attributeSelector = (attribute, value) ->
value = value.replace(/"/g, '\\"')
"[#{attribute}=\"#{value}\"]"
nonUpClasses = ($element) ->
classString = $element.attr('class') || ''
classes = classString.split(' ')
select classes, (klass) -> isPresent(klass) && !klass.match(/^up-/)
# jQuery's implementation of $(...) cannot create elements that have
# an <html> or <body> tag. So we're using native elements.
# Also IE9 cannot set innerHTML on a <html> or <head> element.
createElementFromHtml = (html) ->
parser = new DOMParser()
parser.parseFromString(html, 'text/html')
assignPolyfill = (target, sources...) ->
for source in sources
for own key, value of source
target[key] = value
target
###**
Merge the own properties of one or more `sources` into the `target` object.
@function up.util.assign
@param {Object} target
@param {Array<Object>} sources...
@stable
###
assign = Object.assign || assignPolyfill
###**
Returns a new string with whitespace removed from the beginning
and end of the given string.
@param {string}
A string that might have whitespace at the beginning and end.
@return {string}
The trimmed string.
@stable
###
trim = $.trim
listBlock = (block) ->
if isString(block)
(item) -> item[block]
else
block
###**
Translate all items in an array to new array of items.
@function up.util.map
@param {Array<T>} array
@param {Function(T, number): any|String} block
A function that will be called with each element and (optional) iteration index.
You can also pass a property name as a String,
which will be collected from each item in the array.
@return {Array}
A new array containing the result of each function call.
@stable
###
map = (array, block) ->
return [] if array.length == 0
block = listBlock(block)
for item, index in array
block(item, index)
###**
Calls the given function for each element (and, optional, index)
of the given array.
@function up.util.each
@param {Array<T>} array
@param {Function(T, number)} block
A function that will be called with each element and (optional) iteration index.
@stable
###
each = map
###**
Calls the given function for the given number of times.
@function up.util.times
@param {number} count
@param {Function} block
@stable
###
times = (count, block) ->
block(iteration) for iteration in [0..(count - 1)]
###**
Returns whether the given argument is `null`.
@function up.util.isNull
@param object
@return {boolean}
@stable
###
isNull = (object) ->
object == null
###**
Returns whether the given argument is `undefined`.
@function up.util.isUndefined
@param object
@return {boolean}
@stable
###
isUndefined = (object) ->
object == undefined
###**
Returns whether the given argument is not `undefined`.
@function up.util.isDefined
@param object
@return {boolean}
@stable
###
isDefined = (object) ->
!isUndefined(object)
###**
Returns whether the given argument is either `undefined` or `null`.
Note that empty strings or zero are *not* considered to be "missing".
For the opposite of `up.util.isMissing()` see [`up.util.isGiven()`](/up.util.isGiven).
@function up.util.isMissing
@param object
@return {boolean}
@stable
###
isMissing = (object) ->
isUndefined(object) || isNull(object)
###**
Returns whether the given argument is neither `undefined` nor `null`.
Note that empty strings or zero *are* considered to be "given".
For the opposite of `up.util.isGiven()` see [`up.util.isMissing()`](/up.util.isMissing).
@function up.util.isGiven
@param object
@return {boolean}
@stable
###
isGiven = (object) ->
!isMissing(object)
# isNan = (object) ->
# isNumber(value) && value != +value
###**
Return whether the given argument is considered to be blank.
This returns `true` for:
- `undefined`
- `null`
- Empty strings
- Empty arrays
- An object without own enumerable properties
All other arguments return `false`.
@function up.util.isBlank
@param object
@return {boolean}
@stable
###
isBlank = (object) ->
return true if isMissing(object)
return false if isFunction(object)
return true if isObject(object) && Object.keys(object).length == 0 # object
return true if object.length == 0 # string, array, jQuery
return false
###**
Returns the given argument if the argument is [present](/up.util.isPresent),
otherwise returns `undefined`.
@function up.util.presence
@param object
@param {Function(T): boolean} [tester=up.util.isPresent]
The function that will be used to test whether the argument is present.
@return {T|undefined}
@stable
###
presence = (object, tester = isPresent) ->
if tester(object) then object else undefined
###**
Returns whether the given argument is not [blank](/up.util.isBlank).
@function up.util.isPresent
@param object
@return {boolean}
@stable
###
isPresent = (object) ->
!isBlank(object)
###**
Returns whether the given argument is a function.
@function up.util.isFunction
@param object
@return {boolean}
@stable
###
isFunction = (object) ->
typeof(object) == 'function'
###**
Returns whether the given argument is a string.
@function up.util.isString
@param object
@return {boolean}
@stable
###
isString = (object) ->
typeof(object) == 'string' || object instanceof String
###**
Returns whether the given argument is a number.
Note that this will check the argument's *type*.
It will return `false` for a string like `"123"`.
@function up.util.isNumber
@param object
@return {boolean}
@stable
###
isNumber = (object) ->
typeof(object) == 'number' || object instanceof Number
###**
Returns whether the given argument is an options hash,
Differently from [`up.util.isObject()`], this returns false for
functions, jQuery collections, promises, `FormData` instances and arrays.
@function up.util.isOptions
@param object
@return {boolean}
@internal
###
isOptions = (object) ->
typeof(object) == 'object' && !isNull(object) && !isJQuery(object) && !isPromise(object) && !isFormData(object) && !isArray(object)
###**
Returns whether the given argument is an object.
This also returns `true` for functions, which may behave like objects in JavaScript.
@function up.util.isObject
@param object
@return {boolean}
@stable
###
isObject = (object) ->
typeOfResult = typeof(object)
(typeOfResult == 'object' && !isNull(object)) || typeOfResult == 'function'
###**
Returns whether the given argument is a DOM element.
@function up.util.isElement
@param object
@return {boolean}
@stable
###
isElement = (object) ->
!!(object && object.nodeType == 1)
###**
Returns whether the given argument is a jQuery collection.
@function up.util.isJQuery
@param object
@return {boolean}
@stable
###
isJQuery = (object) ->
object instanceof jQuery
###**
Returns whether the given argument is an object with a `then` method.
@function up.util.isPromise
@param object
@return {boolean}
@stable
###
isPromise = (object) ->
isObject(object) && isFunction(object.then)
###**
Returns whether the given argument is an array.
@function up.util.isArray
@param object
@return {boolean}
@stable
###
# https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isArray = Array.isArray
###**
Returns whether the given argument is a `FormData` instance.
Always returns `false` in browsers that don't support `FormData`.
@function up.util.isFormData
@param object
@return {boolean}
@internal
###
isFormData = (object) ->
object instanceof FormData
###**
Converts the given array-like argument into an array.
Returns the array.
@function up.util.toArray
@param object
@return {Array}
@stable
###
toArray = (object) ->
Array.prototype.slice.call(object)
###**
Returns a shallow copy of the given array or object.
@function up.util.copy
@param {Object|Array} object
@return {Object|Array}
@stable
###
copy = (object) ->
if isArray(object)
object = object.slice()
else if isObject(object) && !isFunction(object)
object = assign({}, object)
else
up.fail('Cannot copy %o', object)
object
###**
If given a jQuery collection, returns the first native DOM element in the collection.
If given a string, returns the first element matching that string.
If given any other argument, returns the argument unchanged.
@function up.util.element
@param {jQuery|Element|String} object
@return {Element}
@internal
###
getElement = (object) ->
if isJQuery(object)
object.get(0)
else if isString(object)
$(object).get(0)
else
object
###**
Creates a new object by merging together the properties from the given objects.
@function up.util.merge
@param {Array<Object>} sources...
@return Object
@stable
###
merge = (sources...) ->
assign({}, sources...)
###**
Creates an options hash from the given argument and some defaults.
The semantics of this function are confusing.
We want to get rid of this in the future.
@function up.util.options
@param {Object} object
@param {Object} [defaults]
@return {Object}
@internal
###
options = (object, defaults) ->
merged = if object then copy(object) else {}
if defaults
for key, defaultValue of defaults
value = merged[key]
if isMissing(value)
value = defaultValue
merged[key] = value
merged
###**
Returns the first argument that is considered [given](/up.util.isGiven).
This function is useful when you have multiple option sources and the value can be boolean.
In that case you cannot change the sources with a `||` operator
(since that doesn't short-circuit at `false`).
@function up.util.option
@param {Array} args...
@internal
###
option = (args...) ->
detect(args, isGiven)
###**
Passes each element in the given array to the given function.
Returns the first element for which the function returns a truthy value.
If no object matches, returns `undefined`.
@function up.util.detect
@param {Array<T>} array
@param {Function(T): boolean} tester
@return {T|undefined}
@stable
###
detect = (array, tester) ->
match = undefined
for element in array
if tester(element)
match = element
break
match
###**
Returns whether the given function returns a truthy value
for any element in the given array.
@function up.util.any
@param {Array<T>} array
@param {Function(T, number): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
###
any = (array, tester) ->
tester = listBlock(tester)
match = false
for element, index in array
if tester(element, index)
match = true
break
match
###**
Returns whether the given function returns a truthy value
for all elements in the given array.
@function up.util.all
@param {Array<T>} array
@param {Function(T, number): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
###
all = (array, tester) ->
tester = listBlock(tester)
match = true
for element, index in array
unless tester(element, index)
match = false
break
match
###**
Returns all elements from the given array that are
neither `null` or `undefined`.
@function up.util.compact
@param {Array<T>} array
@return {Array<T>}
@stable
###
compact = (array) ->
select array, isGiven
###**
Returns the given array without duplicates.
@function up.util.uniq
@param {Array<T>} array
@return {Array<T>}
@stable
###
uniq = (array) ->
return array if array.length < 2
setToArray(arrayToSet(array))
###*
This function is like [`uniq`](/up.util.uniq), accept that
the given function is invoked for each element to generate the value
for which uniquness is computed.
@function up.util.uniqBy
@param {Array<T>} array
@param {Function<T>: any} array
@return {Array<T>}
@experimental
###
uniqBy = (array, mapper) ->
return array if array.length < 2
mapper = listBlock(mapper)
set = new Set()
select array, (elem, index) ->
mapped = mapper(elem, index)
if set.has(mapped)
false
else
set.add(mapped)
true
###*
@function up.util.setToArray
@internal
###
setToArray = (set) ->
array = []
set.forEach (elem) -> array.push(elem)
array
###*
@function up.util.arrayToSet
@internal
###
arrayToSet = (array) ->
set = new Set()
array.forEach (elem) -> set.add(elem)
set
###**
Returns all elements from the given array that return
a truthy value when passed to the given function.
@function up.util.select
@param {Array<T>} array
@param {Function(T, number): boolean} tester
@return {Array<T>}
@stable
###
select = (array, tester) ->
tester = listBlock(tester)
matches = []
each array, (element, index) ->
if tester(element, index)
matches.push(element)
matches
###**
Returns all elements from the given array that do not return
a truthy value when passed to the given function.
@function up.util.reject
@param {Array<T>} array
@param {Function(T, number): boolean} tester
@return {Array<T>}
@stable
###
reject = (array, tester) ->
tester = listBlock(tester)
select(array, (element, index) -> !tester(element, index))
###**
Returns the intersection of the given two arrays.
Implementation is not optimized. Don't use it for large arrays.
@function up.util.intersect
@internal
###
intersect = (array1, array2) ->
select array1, (element) ->
contains(array2, element)
addClass = (element, klassOrKlasses) ->
changeClassList(element, klassOrKlasses, 'add')
removeClass = (element, klassOrKlasses) ->
changeClassList(element, klassOrKlasses, 'remove')
changeClassList = (element, klassOrKlasses, fnName) ->
classList = getElement(element).classList
if isArray(klassOrKlasses)
each klassOrKlasses, (klass) ->
classList[fnName](klass)
else
classList[fnName](klassOrKlasses)
addTemporaryClass = (element, klassOrKlasses) ->
addClass(element, klassOrKlasses)
-> removeClass(element, klassOrKlasses)
hasClass = (element, klass) ->
classList = getElement(element).classList
classList.contains(klass)
###**
Returns the first [present](/up.util.isPresent) element attribute
among the given list of attribute names.
@function up.util.presentAttr
@internal
###
presentAttr = ($element, attrNames...) ->
values = ($element.attr(attrName) for attrName in attrNames)
detect(values, isPresent)
###**
Waits for the given number of milliseconds, the runs the given callback.
Instead of `up.util.setTimer(0, fn)` you can also use [`up.util.nextFrame(fn)`](/up.util.nextFrame).
@function up.util.setTimer
@param {number} millis
@param {Function} callback
@stable
###
setTimer = (millis, callback) ->
setTimeout(callback, millis)
###**
Schedules the given function to be called in the
next JavaScript execution frame.
@function up.util.nextFrame
@param {Function} block
@stable
###
nextFrame = (block) ->
setTimeout(block, 0)
###**
Queue a function to be executed in the next microtask.
@function up.util.queueMicrotask
@param {Function} task
@internal
###
microtask = (task) ->
Promise.resolve().then(task)
###**
Returns the last element of the given array.
@function up.util.last
@param {Array<T>} array
@return {T}
###
last = (array) ->
array[array.length - 1]
###**
Measures the drawable area of the document.
@function up.util.clientSize
@internal
###
clientSize = ->
element = document.documentElement
width: element.clientWidth
height: element.clientHeight
###**
Returns the width of a scrollbar.
This only runs once per page load.
@function up.util.scrollbarWidth
@internal
###
scrollbarWidth = memoize ->
# This is how Bootstrap does it also:
# https://github.com/twbs/bootstrap/blob/c591227602996c542b9fd0cb65cff3cc9519bdd5/dist/js/bootstrap.js#L1187
$outer = $('<div>')
outer = $outer.get(0)
$outer.attr('up-viewport', '')
writeInlineStyle outer,
position: 'absolute'
top: '0'
left: '0'
width: '100px'
height: '100px' # Firefox needs at least 100px to show a scrollbar
overflowY: 'scroll'
$outer.appendTo(document.body)
width = outer.offsetWidth - outer.clientWidth
$outer.remove()
width
###**
Returns whether the given element is currently showing a vertical scrollbar.
@function up.util.documentHasVerticalScrollbar
@internal
###
documentHasVerticalScrollbar = ->
body = document.body
$body = $(body)
html = document.documentElement
bodyOverflow = readComputedStyle($body, 'overflowY')
forcedScroll = (bodyOverflow == 'scroll')
forcedHidden = (bodyOverflow == 'hidden')
forcedScroll || (!forcedHidden && html.scrollHeight > html.clientHeight)
###**
Temporarily sets the CSS for the given element.
@function up.util.writeTemporaryStyle
@param {jQuery} $element
@param {Object} css
@param {Function} [block]
If given, the CSS is set, the block is called and
the old CSS is restored.
@return {Function}
A function that restores the original CSS when called.
@internal
###
writeTemporaryStyle = (elementOrSelector, newCss, block) ->
$element = $(elementOrSelector)
oldStyles = readInlineStyle($element, Object.keys(newCss))
restoreOldStyles = -> writeInlineStyle($element, oldStyles)
writeInlineStyle($element, newCss)
if block
# If a block was passed, we run the block and restore old styles.
block()
restoreOldStyles()
else
# If no block was passed, we return the restoration function.
restoreOldStyles
###**
Forces a repaint of the given element.
@function up.util.forceRepaint
@internal
###
forceRepaint = (element) ->
element = getElement(element)
element.offsetHeight
###*
@function up.util.finishTransition
@internal
###
concludeCssTransition = (element) ->
undo = writeTemporaryStyle(element, transition: 'none')
# Browsers need to paint at least one frame without a transition to stop the
# animation. In theory we could just wait until the next paint, but in case
# someone will set another transition after us, let's force a repaint here.
forceRepaint(element)
return undo
###**
@internal
###
margins = (selectorOrElement) ->