-
Notifications
You must be signed in to change notification settings - Fork 477
/
Utils.coffee
1450 lines (1105 loc) · 39.5 KB
/
Utils.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
{_} = require "./Underscore"
{Screen} = require "./Screen"
{Matrix} = require "./Matrix"
WebFont = require('webfontloader')
Utils = {}
Utils.reset = ->
Framer.CurrentContext.reset()
Utils.getValue = (value) ->
return value() if _.isFunction value
return value
Utils.getValueForKeyPath = (obj, key) ->
result = obj
return obj[key] if not "." in key
for key in key.split(".")
result = result[key]
result
Utils.setValueForKeyPath = (obj, path, val) ->
fields = path.split(".")
result = obj
i = 0
n = fields.length
while i < n and result isnt undefined
field = fields[i]
if i is n - 1
currentValue = result[field]
if _.isObject(currentValue) and _.isObject(val) and Object.getPrototypeOf(currentValue) is Object.prototype and Object.getPrototypeOf(val) is Object.prototype
_.extend(currentValue, val)
else
result[field] = val
else
if typeof result[field] is "undefined" or not _.isObject(result[field])
result[field] = {}
result = result[field]
i++
return
Utils.valueOrDefault = (value, defaultValue) ->
if value in [undefined, null]
value = defaultValue
return value
Utils.arrayNext = (arr, item) ->
arr[arr.indexOf(item) + 1] or _.head arr
Utils.arrayPrev = (arr, item) ->
arr[arr.indexOf(item) - 1] or _.last arr
Utils.webkitPerspectiveForValue = (value) ->
if value in ["none", null, 0]
return "none"
else if _.isNumber(value)
return value
else
return null
######################################################
# MATH
Utils.sum = (arr) -> _.reduce arr, (a, b) -> a + b
Utils.average = (arr) -> Utils.sum(arr) / arr.length
Utils.mean = Utils.average
Utils.median = (x) ->
return null if x.length is 0
sorted = x.slice().sort (a, b) ->
a - b
if sorted.length % 2 is 1
sorted[(sorted.length - 1) / 2]
else
(sorted[(sorted.length / 2) - 1] + sorted[sorted.length / 2]) / 2
Utils.nearestIncrement = (x, increment) ->
return x unless increment
return Math.round(x * (1 / increment)) / (1 / increment)
######################################################
# ANIMATION
# This is a little hacky, but I want to avoid wrapping the function
# in another one as it gets called at 60 fps. So we make it a global.
window.requestAnimationFrame ?= window.webkitRequestAnimationFrame
window.requestAnimationFrame ?= (f) -> Utils.delay 1/60, f
######################################################
# TIME FUNCTIONS
# Note: in Framer 3 we try to keep all times in seconds
# Used by animation engine, needs to be very performant
if window.performance
Utils.getTime = -> window.performance.now() / 1000
else
Utils.getTime = -> Date.now() / 1000
Utils.delay = (time, f) ->
timer = setTimeout(f, time * 1000)
Framer.CurrentContext.addTimer(timer)
return timer
Utils.interval = (time, f) ->
timer = setInterval(f, time * 1000)
Framer.CurrentContext.addInterval(timer)
return timer
Utils.debounce = (threshold=0.1, fn, immediate) ->
timeout = null
threshold *= 1000
(args...) ->
obj = this
delayed = ->
fn.apply(obj, args) unless immediate
timeout = null
if timeout
clearTimeout(timeout)
else if (immediate)
fn.apply(obj, args)
timeout = setTimeout delayed, threshold
Utils.throttle = (delay, fn) ->
return fn if delay is 0
delay *= 1000
timer = false
return ->
return if timer
timer = true
setTimeout (-> timer = false), delay unless delay is -1
fn arguments...
# Taken from http://addyosmani.com/blog/faster-javascript-memoization/
Utils.memoize = (fn) -> ->
args = Array::slice.call(arguments)
hash = ""
i = args.length
currentArg = null
while i--
currentArg = args[i]
hash += (if (currentArg is Object(currentArg)) then JSON.stringify(currentArg) else currentArg)
fn.memoize or (fn.memoize = {})
(if (hash of fn.memoize) then fn.memoize[hash] else fn.memoize[hash] = fn.apply(this, args))
######################################################
# HANDY FUNCTIONS
Utils.randomColor = (alpha = 1.0) ->
return Color.random(alpha)
Utils.randomChoice = (arr) ->
arr[Math.floor(Math.random() * arr.length)]
Utils.randomNumber = (a=0, b=1) ->
# Return a random number between a and b
Utils.mapRange Math.random(), 0, 1, a, b
Utils.randomImage = (layer) ->
if _.isNumber(layer)
layer = {id: layer}
photos = ["1417733403748-83bbc7c05140", "1423841265803-dfac59ebf718", "1433689056001-018e493576bc", "1430812411929-de4cf1d1fe73", "1457269449834-928af64c684d", "1443616839562-036bb2afd9a2", "1461535676131-2de1f7054d3f", "1462393582935-1ac76b85dcf1", "1414589530802-cb54ce0575d9", "1422908132590-117a051fc5cd", "1438522014717-d7ce32b9bab9", "1462058164249-2dcdcda67ce7", "1456757014009-0614a080ff7f", "1434238255348-4fb0d9caa0a4", "1448071792026-7064a01897e7", "1458681842652-019f4eeda5e5", "1460919920543-d8c45f4bd621", "1447767961238-038617b84a2b", "1449089299624-89ce41e8306c", "1414777410116-81e404502b52", "1433994349623-0a18966ee9c0", "1452567772283-91d67178f409", "1458245229726-a8ba04cb5969", "1422246719650-cb30d19825e3", "1417392639864-2c88dd07f460", "1442328166075-47fe7153c128", "1448467258552-6b3982373a13", "1447023362548-250f3a7b80ed", "1451486242265-24b0c0ef9a51", "1414339372428-797ec111646d"]
photo = Utils.randomChoice(photos)
photo = photos[(layer.id) % photos.length] if layer?.id
increment = 100
size = 1024
if layer
size = Math.max(layer.width, layer.height)
size = Math.ceil(size / increment) * increment
size = increment if size < increment
size = Utils.devicePixelRatio() * size
size = parseInt(size)
# width = Utils.round(layer.width, 0, 100, 100)
# height = Utils.round(layer.height, 0, 100, 100)
return "https://images.unsplash.com/photo-#{photo}?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=#{size}&h=#{size}&fit=max"
Utils.defineEnum = (names = [], offset = 0, geometric = 0) ->
# TODO: What is this doing here?
Enum = {}
for name, i in names
j = i
j = if not offset then j else j + offset
j = if not geometric then j else Math.pow geometric, j
Enum[Enum[name] = j] = name
return Enum
Utils.labelLayer = (layer, text, style={}) ->
return unless text
return if text is ""
return unless typeof(text) is "string"
fontSize = Math.max(Math.min(48, parseInt(layer.height / 3.2)), 14)
style = _.extend({
font: "#{fontSize}px/1em #{Utils.deviceFont()}"
lineHeight: "#{layer.height}px"
textAlign: "center"
color: "#fff"
}, style)
layer.style = style
layer.html = text
Utils.stringify = (obj) ->
try
return JSON.stringify obj if _.isObject obj
catch
""
return "null" if obj is null
return "undefined" if obj is undefined
return obj.toString() if obj.toString
return obj
Utils.inspectObjectType = (item) ->
# This is a hacky way to get nice object names, it tries to
# parse them from the .toString methods for objects.
if item.constructor?.name? and item.constructor?.name isnt "Object"
return item.constructor.name
extract = (str) ->
return null unless str
regex = /\[object (\w+)\]/
match = regex.exec(str)
return match[1] if match
return null
if item.toString
className = extract(item.toString())
return className if className
if item.constructor?.toString
className = extract(item.constructor?.toString())
return className.replace("Constructor", "") if className
return "Object"
Utils.inspect = (item, max=5, l=0) ->
return "null" if item is null
return "undefined" if item is undefined
if _.isFunction(item.toInspect)
return item.toInspect()
if _.isString(item)
return "\"#{item}\""
if _.isNumber(item)
return "#{item}"
if _.isFunction(item)
code = item.toString()["function ".length..].replace(/\n/g, "").replace(/\s+/g, " ")
# We limit the size of a function body if it's in a strucutre
limit = 50
code = "#{_.trimEnd(code[..limit])}… }" if code.length > limit and l > 0
return "<Function #{code}>"
if _.isArray(item)
return "[...]" if l > max
return "[" + _.map(item, (i) -> Utils.inspect(i, max, l+1)).join(", ") + "]"
if _.isObject(item)
objectType = Utils.inspectObjectType(item)
# We should not loop over dom trees because we will have a bad time
return "<#{objectType}>" if /HTML\w+?Element/.test(objectType)
if l > max
objectInfo = "{...}"
else
objectInfo = "{" + _.map(item, (v, k) -> "#{k}:#{Utils.inspect(v, max, l+1)}").join(", ") + "}"
return objectInfo if objectType is "Object"
return "<#{objectType} #{objectInfo}>"
return "#{item}"
Utils.uuid = ->
chars = "0123456789abcdefghijklmnopqrstuvwxyz".split("")
output = new Array(36)
random = 0
for digit in [1..32]
random = 0x2000000 + (Math.random() * 0x1000000) | 0 if (random <= 0x02)
r = random & 0xf
random = random >> 4
output[digit] = chars[if digit is 19 then (r & 0x3) | 0x8 else r]
output.join ""
Utils.findLayer = (layers, selector) ->
_.find layers, (layer) -> Utils.layerMatchesSelector(layer, selector)
Utils.filterLayers = (layers, selector) ->
_.filter layers, (layer) -> Utils.layerMatchesSelector(layer, selector)
Utils.layerMatchesSelector = (layer, selector) ->
getHierarchyString = (l) ->
# create a string of the hierarchy so we can run regex on it
nameArr = _.pluck(l.ancestors().reverse(), 'name')
return nameArr.join('>') + ">#{layer.name}"
hierarchyMatch = (hierarchy, string) ->
string = string.replace(/\s*>\s*/g, '>') # clean spaces around >
string = string.split('*').join('[^>]*') # anything but >
string = string.split(' ').join('(?:.*)>') # anything but ends with >
string = string.split(',').join('$|') # or
regexString = "(^|>)"+string+"$"
regExp = new RegExp(regexString)
return regExp.test(hierarchy)
if selector
hierarchy = getHierarchyString(layer, selector)
return hierarchyMatch(hierarchy, selector)
Utils.arrayFromArguments = (args) ->
# Convert an arguments object to an array
return args[0] if _.isArray(args[0])
return Array.prototype.slice.call(args)
Utils.cycle = ->
# Returns a function that cycles through a list of values with each call.
args = Utils.arrayFromArguments arguments
curr = -1
return ->
curr++
curr = 0 if curr >= args.length
return args[curr]
# Backwards compatibility
Utils.toggle = Utils.cycle
Utils.callAfterCount = (total, callback) ->
# This calls a function after this method is called total times
count = 0
return callAfterCount = ->
count += 1
callback?() if count is total
Utils.equal = (a, b) ->
if _.isFunction a?.isEqual
return a.isEqual(b)
if _.isFunction b?.isEqual
return b.isEqual(a)
return _.isEqual a, b
######################################################
# ENVIROMENT FUNCTIONS
Utils.isWebKit = ->
window.WebKitCSSMatrix isnt undefined and not Utils.isEdge()
Utils.webkitVersion = ->
version = -1
regexp = /AppleWebKit\/([\d.]+)/
result = regexp.exec(navigator.userAgent)
version = parseFloat(result[1]) if result
version
Utils.isChrome = ->
return /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor)
Utils.isSafari = ->
return /Safari/.test(navigator.userAgent) and /Apple Computer/.test(navigator.vendor)
Utils.isFirefox = ->
return /^Mozilla.*Firefox\/\d+\.\d+$/.test(navigator.userAgent)
Utils.isEdge = ->
return /Edge/.test(navigator.userAgent)
Utils.isAndroid = ->
return /(android)/i.test(navigator.userAgent)
Utils.isIOS = ->
return /(iPhone|iPod|iPad)/i.test(navigator.platform)
Utils.isMacOS = ->
return /Mac/.test(navigator.platform)
Utils.isWindows = ->
return /Win/.test(navigator.platform)
Utils.isTouch = ->
window.ontouchstart is null and
window.ontouchmove is null and
window.ontouchend is null
Utils.isDesktop = ->
Utils.deviceType() is "desktop"
Utils.isPhone = ->
Utils.deviceType() is "phone"
Utils.isTablet = ->
Utils.deviceType() is "tablet"
Utils.isMobile = ->
Utils.isPhone() or Utils.isTablet()
Utils.isFileUrl = (url) ->
return _.startsWith(url, "file://")
Utils.isDataUrl = (url) ->
return _.startsWith(url, "data:")
Utils.isRelativeUrl = (url) ->
not /^([a-zA-Z]{1,8}:\/\/).*$/.test(url)
Utils.isLocalServerUrl = (url) ->
return /[a-zA-Z]{1,8}:\/\/127\.0\.0\.1/.test(url) or /[a-zA-Z]{1,8}:\/\/localhost/.test(url)
Utils.isLocalUrl = (url) ->
return true if Utils.isFileUrl(url)
return true if Utils.isLocalServerUrl(url)
return false
Utils.isLocalAssetUrl = (url, baseUrl) ->
baseUrl ?= window.location.href
return false if Utils.isDataUrl(url)
return true if Utils.isLocalUrl(url)
return true if Utils.isRelativeUrl(url) and Utils.isLocalUrl(baseUrl)
return false
Utils.isFramerStudio = ->
navigator.userAgent.indexOf("FramerStudio") isnt -1
Utils.framerStudioVersion = ->
if Utils.isFramerStudio()
isBeta = navigator.userAgent.indexOf("FramerStudio/beta") >= 0
isLocal = navigator.userAgent.indexOf("FramerStudio/local") >= 0
isFuture = navigator.userAgent.indexOf("FramerStudio/future") >= 0
return Number.MAX_VALUE if isBeta or isLocal or isFuture
matches = navigator.userAgent.match(/\d+$/)
version = parseInt(matches[0]) if matches and matches.length > 0
return version if _.isNumber(version)
# if we don't know the version we are probably running the beta or a local build
return Number.MAX_VALUE
Utils.devicePixelRatio = ->
window.devicePixelRatio
Utils.isJP2Supported = ->
if Utils.isFirefox()
return false
else
return Utils.isWebKit() and not Utils.isChrome()
Utils.isWebPSupported = ->
return Utils.isChrome()
Utils.deviceType = ->
# Taken from
# https://github.com/jeffmcmahan/device-detective/blob/master/bin/device-detect.js
if /(tablet)|(iPad)|(Nexus 9)/i.test(navigator.userAgent)
return "tablet"
if /(mobi)/i.test(navigator.userAgent)
return "phone"
return "desktop"
Utils.pathJoin = ->
Utils.arrayFromArguments(arguments).join("/")
Utils.deviceFont = (os) ->
# https://github.com/jonathantneal/system-font-css
if not os
os = "macOS" if Utils.isMacOS()
os = "iOS" if Utils.isIOS()
os = "Android" if Utils.isAndroid()
os = "Windows" if Utils.isWindows()
appleFont = "-apple-system, BlinkMacSystemFont, SF UI Text, Helvetica Neue"
googleFont = "Roboto, Helvetica Neue"
microsoftFont = "Segoe UI, Helvetica Neue"
switch os
when "Android" then return googleFont
when "iOS", "watchOS", "macOS" then return appleFont
when "Windows" then return microsoftFont
return appleFont
_isFontLoadedResults = {}
getWidth = (fontFamily) ->
Utils.textSize("BESbswy",
fontFamily: fontFamily
fontSize: 300).width
monoWidth = null
serifWidth = null
sansWidth = null
Utils.isFontAvailable = (fonts) ->
if _isFontLoadedResults[fonts] is true
return true
monoWidth ?= getWidth('monospace')
serifWidth ?= getWidth('serif')
sansWidth ?= getWidth('sans-serif')
if monoWidth isnt getWidth(fonts + ",monospace") or serifWidth isnt getWidth(fonts + ",serif") or sansWidth isnt getWidth(fonts + ",sans-serif")
_isFontLoadedResults[fonts] = true
return true
else
return false
Utils.isFontFamilyLoaded = (fonts, timeout = 1000) ->
if not _.isArray(fonts)
fonts = [fonts]
unavailableFonts = fonts.filter (font) -> not Utils.isFontAvailable(font)
return true if unavailableFonts.length is 0
return Utils.loadWebFontConfig
custom:
families: unavailableFonts
timeout: timeout
fontsFromConfig = (config) ->
result = []
if _.isArray(config?.custom?.families)
result = result.concat(config?.custom?.families)
if _.isArray(config?.google?.families)
result = result.concat(config?.google?.families)
return result
Utils.loadWebFontConfig = (config) ->
fonts = fontsFromConfig(config)
allLoadedResult = null
for currentFont in fonts
currentFontLoaded = _isFontLoadedResults[currentFont]
if not currentFontLoaded?
allLoadedResult = null
break
allLoadedResult ?= currentFontLoaded
allLoadedResult = allLoadedResult and currentFontLoaded
if allLoadedResult?
return allLoadedResult
customActive = config.active
customInactive = config.inactive
customFontactive = config.fontactive
customFontinactive = config.fontinactive
promise = new Promise (resolve, reject) ->
config.fontactive = (font) ->
_isFontLoadedResults[font] = true
customFontactive?(font)
if fonts.length is 1
resolve()
config.fontinactive = (font) ->
console.warn("Tried to load unavailable font: '#{font}'")
_isFontLoadedResults[font] = false
customFontinactive?(font)
if fonts.length is 1
error = new Error("#{font} failed to load")
reject(error)
config.active = ->
customActive?()
resolve()
config.inactive = ->
customInactive?()
error = new Error("#{fonts.join(', ')} failed to load")
reject(error)
WebFont.load config
return promise
# Load fonts from Google Web Fonts
Utils.loadWebFont = (font, weight, source = "google") ->
if not _isFontLoadedResults[font]? or _isFontLoadedResults[font] is false
delete _isFontLoadedResults[font]
config = {}
if source is "google"
fontToLoad = font
fontToLoad += ":#{weight}" if weight?
config.google =
families: [fontToLoad]
Utils.loadWebFontConfig config
return {fontFamily: font, fontWeight: weight}
######################################################
# MATH FUNCTIONS
Utils.round = (value, decimals=0, increment=null, min=null, max=null) ->
d = Math.pow(10, decimals)
value = Math.round(value / increment) * increment if increment
value = Math.round(value * d) / d
return min if min and value < min
return max if max and value > max
return value
Utils.roundWhole = (value, decimals=1) ->
# Return integer if whole value, else include decimals
return parseInt(value) if parseInt(value) is value
return Utils.round(value, decimals)
Utils.clamp = (value, a, b) ->
min = Math.min(a, b)
max = Math.max(a, b)
value = min if value < min
value = max if value > max
return value
# Taken from http://jsfiddle.net/Xz464/7/
# Used by animation engine, needs to be very performant
Utils.mapRange = (value, fromLow, fromHigh, toLow, toHigh) ->
toLow + (((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow))
# Kind of similar as above but with a better syntax and a limiting option
Utils.modulate = (value, rangeA, rangeB, limit=false) ->
[fromLow, fromHigh] = rangeA
[toLow, toHigh] = rangeB
# if rangeB consists of Colors we return a color tween
# if Color.isColor(toLow) or _.isString(toLow) and Color.isColorString(toLow)
# ratio = Utils.modulate(value, rangeA, [0, 1])
# result = Color.mix(toLow, toHigh, ratio)
# return result
result = toLow + (((value - fromLow) / (fromHigh - fromLow)) * (toHigh - toLow))
if limit is true
if toLow < toHigh
return toLow if result < toLow
return toHigh if result > toHigh
else
return toLow if result > toLow
return toHigh if result < toHigh
result
######################################################
# STRING FUNCTIONS
Utils.parseFunction = (str) ->
result = {name: "", args: []}
if _.endsWith str, ")"
result.name = str.split("(")[0]
result.args = str.split("(")[1].split(",").map (a) -> _.trim(_.trimEnd(a, ")"))
else
result.name = str
return result
######################################################
# DOM FUNCTIONS
__domCompleteState = "interactive"
__domComplete = []
__domReady = false
if document?
document.onreadystatechange = (event) ->
if document.readyState is __domCompleteState
__domReady = true
while __domComplete.length
f = __domComplete.shift()()
Utils.domComplete = (f) ->
if __domReady
f()
else
__domComplete.push(f)
Utils.domCompleteCancel = (f) ->
__domComplete = _.without(__domComplete, f)
Utils.domValidEvent = (element, eventName) ->
return if not eventName
return true if eventName in ["touchstart", "touchmove", "touchend"]
return typeof(element["on#{eventName.toLowerCase()}"]) isnt "undefined"
Utils.domLoadScript = (url, callback) ->
script = document.createElement "script"
script.type = "text/javascript"
script.src = url
script.onload = callback
head = document.getElementsByTagName("head")[0]
head.appendChild script
script
Utils.domLoadData = (path, callback) ->
request = new XMLHttpRequest()
# request.addEventListener "progress", updateProgress, false
# request.addEventListener "abort", transferCanceled, false
request.addEventListener "load", ->
callback null, request.responseText
, false
request.addEventListener "error", ->
callback true, null
, false
request.open "GET", path, true
request.send null
Utils.domLoadJSON = (path, callback) ->
Utils.domLoadData path, (err, data) ->
callback err, JSON.parse data
Utils.domLoadDataSync = (path) ->
request = new XMLHttpRequest()
request.open("GET", path, false)
# This does not work in Safari, see below
try
request.send(null)
catch e
console.debug("XMLHttpRequest.error", e)
handleError = ->
throw Error "Utils.domLoadDataSync: #{path} -> [#{request.status} #{request.statusText}]"
request.onerror = handleError
if request.status not in [200, 0]
handleError()
# Because I can't catch the actual 404 with Safari, I just assume something
# went wrong if there is no text data returned from the request.
if not request.responseText
handleError()
# console.log "domLoadDataSync", path
# console.log "xhr.readyState", request.readyState
# console.log "xhr.status", request.status
# console.log "xhr.responseText", request.responseText
return request.responseText
Utils.domLoadJSONSync = (path) ->
JSON.parse Utils.domLoadDataSync path
Utils.domLoadScriptSync = (path) ->
scriptData = Utils.domLoadDataSync path
eval scriptData
scriptData
Utils.insertCSS = (css) ->
styleElement = document.createElement("style")
styleElement.type = "text/css"
styleElement.innerHTML = css
Utils.domComplete ->
document.body.appendChild(styleElement)
Utils.loadImage = (url, callback, context) ->
# Loads a single image and calls callback.
# The callback will be called with true if there is an error.
element = new Image
context ?= Framer.CurrentContext
context.domEventManager.wrap(element).addEventListener "load", (event) ->
callback()
context.domEventManager.wrap(element).addEventListener "error", (event) ->
callback(true)
element.src = url
Utils.isInsideIframe = ->
return window isnt window.top unless Utils.isInsideFramerCloud()
return false
Utils.isInsideFramerCloud = ->
return Utils.getQueryParameters()["cloud"] is "1"
Utils.getQueryParameters = ->
return _.fromPairs window.location.search.slice(1).split('&').map((val) -> val.split('='))
######################################################
# GEOMETRY FUNCTIONS
# Point
Utils.point = (input) ->
return Utils.pointZero(input) if _.isNumber(input)
return Utils.pointZero() unless input
result = Utils.pointZero()
for k in ["x", "y"]
result[k] = input[k] if _.isNumber(input[k])
return result
Utils.pointZero = (n=0) ->
return {x: n, y: n}
Utils.pointDivide = (point, fraction) ->
return point =
x: point.x / fraction
y: point.y / fraction
Utils.pointAdd = (pointA, pointB) ->
return point =
x: pointA.x + pointB.x
y: pointA.y + pointB.y
Utils.pointSubtract = (pointA, pointB) ->
return point =
x: pointA.x - pointB.x
y: pointA.y - pointB.y
Utils.pointMin = ->
points = Utils.arrayFromArguments arguments
point =
x: _.min points.map (size) -> size.x
y: _.min points.map (size) -> size.y
Utils.pointMax = ->
points = Utils.arrayFromArguments arguments
point =
x: _.max points.map (size) -> size.x
y: _.max points.map (size) -> size.y
Utils.pointDelta = (pointA, pointB) ->
delta =
x: pointB.x - pointA.x
y: pointB.y - pointA.y
Utils.pointDistance = (pointA, pointB) ->
a = pointA.x - pointB.x
b = pointA.y - pointB.y
return Math.sqrt((a * a) + (b * b))
Utils.pointInvert = (point) ->
point =
x: 0 - point.x
y: 0 - point.y
Utils.pointTotal = (point) ->
point.x + point.y
Utils.pointAbs = (point) ->
point =
x: Math.abs point.x
y: Math.abs point.y
Utils.pointInFrame = (point, frame) ->
return false if point.x < Utils.frameGetMinX(frame) or point.x > Utils.frameGetMaxX(frame)
return false if point.y < Utils.frameGetMinY(frame) or point.y > Utils.frameGetMaxY(frame)
return true
Utils.pointCenter = (pointA, pointB) ->
return point =
x: (pointA.x + pointB.x) / 2
y: (pointA.y + pointB.y) / 2
Utils.pointAngle = (pointA, pointB) ->
return Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180 / Math.PI
Utils.divideFrame = (frame, scale) ->
frame.x /= scale
frame.y /= scale
frame.width /= scale
frame.height /= scale
return frame
Utils.scaleFrames = (layer, scale) ->
if layer instanceof Layer
layer.constraintValues = null
layer.children.map (l) -> Utils.scaleFrames l, scale
layer.frame = Utils.divideFrame layer.frame, scale
if _.isArray(layer)
layer.map (l) -> Utils.scaleFrames l, scale
# Size
Utils.size = (input) ->
return Utils.sizeZero(input) if _.isNumber(input)
return Utils.sizeZero() unless input
result = Utils.sizeZero()
for k in ["width", "height"]
result[k] = input[k] if _.isNumber(input[k])
return result
Utils.sizeZero = (n=0) ->
return {width: n, height: n}
Utils.sizeMin = ->
sizes = Utils.arrayFromArguments arguments
size =
width: _.min sizes.map (size) -> size.width
height: _.min sizes.map (size) -> size.height
Utils.sizeMax = ->
sizes = Utils.arrayFromArguments arguments
size =
width: _.max sizes.map (size) -> size.width
height: _.max sizes.map (size) -> size.height
# Rect
Utils.rectZero = (args={}) ->
return _.defaults(args, {top: 0, right: 0, bottom: 0, left: 0})
Utils.parseRect = (args) ->
if _.isArray(args) and _.isNumber(args[0])
return Utils.parseRect({top: args[0]}) if args.length is 1
return Utils.parseRect({top: args[0], right: args[1]}) if args.length is 2
return Utils.parseRect({top: args[0], right: args[1], bottom: args[2]}) if args.length is 3
return Utils.parseRect({top: args[0], right: args[1], bottom: args[2], left: args[3]}) if args.length is 4
if _.isArray(args) and _.isObject(args[0])
return args[0]
if _.isObject(args)
return args
if _.isNumber(args)
return {top: args, right: args, bottom: args, left: args}
return {}
# Frames
# min mid max * x, y
Utils.frameGetMinX = (frame) -> frame.x
Utils.frameSetMinX = (frame, value) -> frame.x = value
Utils.frameGetMidX = (frame) ->
if frame.width is 0 then frame.x else frame.x + (frame.width / 2.0)
Utils.frameSetMidX = (frame, value) ->
frame.x = if frame.width is 0 then value else value - (frame.width / 2.0)
Utils.frameGetMaxX = (frame) ->
if frame.width is 0 then 0 else frame.x + frame.width
Utils.frameSetMaxX = (frame, value) ->
frame.x = if frame.width is 0 then 0 else value - frame.width
Utils.frameGetMinY = (frame) -> frame.y
Utils.frameSetMinY = (frame, value) -> frame.y = value
Utils.frameGetMidY = (frame) ->
if frame.height is 0 then frame.y else frame.y + (frame.height / 2.0)
Utils.frameSetMidY = (frame, value) ->
frame.y = if frame.height is 0 then value else value - (frame.height / 2.0)
Utils.frameGetMaxY = (frame) ->
if frame.height is 0 then 0 else frame.y + frame.height
Utils.frameSetMaxY = (frame, value) ->
frame.y = if frame.height is 0 then 0 else value - frame.height
Utils.frame = (input) ->
return Utils.frameZero(input) if _.isNumber(input)
return Utils.frameZero() unless input
result = Utils.frameZero()
for k in ["x", "y", "width", "height"]
result[k] = input[k] if _.isNumber(input[k])
return result