forked from dmotz/oriDomi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oridomi.coffee
1324 lines (1076 loc) · 42.8 KB
/
oridomi.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
# # OriDomi
# ### Fold up the DOM like paper.
# 1.0.4
# [oridomi.com](http://oridomi.com)
# #### by [Dan Motzenbecker](http://oxism.com)
# Copyright 2013, MIT License
'use strict'
# This variable is set to true and negated later if the browser does
# not support OriDomi.
isSupported = true
# Utility Functions
# ================
# Used for informing the developer which required feature the browser lacks.
supportWarning = (prop) ->
console?.warn "OriDomi: Missing support for `#{ prop }`."
isSupported = false
# Checks for the presence of CSS properties on a test element.
testProp = (prop) ->
# Loop through the vendor prefix list and return a match is found.
for prefix in prefixList
return full if testEl.style[(full = prefix + capitalize prop)]?
# If the unprefixed property is present, return it.
return prop if testEl.style[prop]?
# If no matches are found, return false to denote that the browser is
# missing this property.
false
# Generates CSS text based on a selector string and a map of styling rules.
addStyle = (selector, rules) ->
style = ".#{ selector }{"
for prop, val of rules
# If the CSS property is among special properties defined later, prefix it.
if prop of css
prop = css[prop]
prop = '-' + prop if prop.match /^(webkit|moz|ms)/i
# Convert camelcase to hypenated.
style += "#{ prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() }:#{ val };"
styleBuffer += style + '}'
# Defines gradient directions based on a given anchor.
getGradient = (anchor) ->
"#{ css.gradientProp }(#{ anchor }, rgba(0, 0, 0, .5) 0%, rgba(255, 255, 255, .35) 100%)"
# Used mainly when creating camelcased strings.
capitalize = (s) ->
s[0].toUpperCase() + s[1...]
# Create an element and look up the canonical class name.
createEl = (className) ->
el = document.createElement 'div'
el.className = elClasses[className]
el
# Clone an element, add an additional class, and return it.
cloneEl = (parent, deep, className) ->
el = parent.cloneNode deep
el.classList.add elClasses[className]
el
# GPU efficient ways of hiding and showing elements:
hideEl = (el) ->
el.style[css.transform] = 'translate3d(-99999px, 0, 0)'
showEl = (el) ->
el.style[css.transform] = 'translate3d(0, 0, 0)'
# This decorator is used on public effect methods to invoke preliminary tasks
# before the effect is applied.
prep = (fn) ->
->
# If the method has been initiated by a touch handler, skip this process.
if @_touchStarted
fn.apply @, arguments
else
[a0, a1, a2] = arguments
opt = {}
angle = anchor = null
# This switch is used to derive the intended order of arguments.
# This keeps argument requirements flexible, allowing most to be left out.
# By putting this logic in a decorator, it doesn't have to exist in any
# of the individual methods.
# Methods are inferred by their arity.
switch fn.length
when 1
opt.callback = a0
# If the composition is already folded up, skip the queueing process
# and invoke the supplied callback immediately.
return opt.callback?() unless @isFoldedUp
when 2
if typeof a0 is 'function'
opt.callback = a0
else
anchor = a0
opt.callback = a1
when 3
angle = a0
if arguments.length is 2
if typeof a1 is 'object'
opt = a1
else if typeof a1 is 'function'
opt.callback = a1
else
anchor = a1
else if arguments.length is 3
anchor = a1
if typeof a2 is 'object'
opt = a2
else if typeof a2 is 'function'
opt.callback = a2
angle ?= @_lastOp.angle or 0
anchor or= @_lastOp.anchor
# Here we add the called function and its normalized arguments to the
# instance's queue.
@_queue.push [fn, @_normalizeAngle(angle), @_getLonghandAnchor(anchor), opt]
# `_step()` manages the queue and decides whether the action will occur now
# or be deferred.
@_step()
# This decorator also returns the instance so effect methods are chainable.
@
# It's necessary to defer many DOM manipulations to a subsequent event loop tick.
defer = (fn) ->
setTimeout fn, 0
# Empty function to be used as placeholder for callback defaults
# (instead of creating separate empty functions).
noOp = ->
# Setup
# =====
# Set a reference to jQuery (or another `$`-aliased DOM library).
# If it doesn't exist, set to null so OriDomi knows we are working without jQuery.
# OriDomi doesn't require it to work, but offers a useful plugin bridge if present.
$ = if (window.jQuery or window.$)?.data then window.$ else null
# List of anchors and their corresponding axis pairs.
anchorList = ['left', 'right', 'top', 'bottom']
anchorListV = anchorList[..1]
anchorListH = anchorList[2..]
# Create a div for testing CSS3 properties.
testEl = document.createElement 'div'
# The style buffer is later populated with CSS rules and appended to the document.
styleBuffer = ''
# List of browser prefixes for testing CSS3 properties.
prefixList = ['Webkit', 'Moz', 'ms']
baseName = 'oridomi'
# CSS classes used by style rules.
elClasses =
active: 'active'
clone: 'clone'
holder: 'holder'
stage: 'stage'
stageLeft: 'stage-left'
stageRight: 'stage-right'
stageTop: 'stage-top'
stageBottom: 'stage-bottom'
content: 'content'
mask: 'mask'
maskH: 'mask-h'
maskV: 'mask-v'
panel: 'panel'
panelH: 'panel-h'
panelV: 'panel-v'
shader: 'shader'
shaderLeft: 'shader-left'
shaderRight: 'shader-right'
shaderTop: 'shader-top'
shaderBottom: 'shader-bottom'
# Each class is namespaced to prevent styling collisions.
elClasses[k] = "#{ baseName }-#{ v }" for k, v of elClasses
# Map of the CSS3 properties needed to support OriDomi, with shorthand names as keys.
# The keys and values are initialized as identical pairs to start with and prefixed
# subsequently when necessary.
css = new ->
@[key] = key for key in [
'transform'
'transformOrigin'
'transformStyle'
'transitionProperty'
'transitionDuration'
'transitionDelay'
'transitionTimingFunction'
'perspective'
'perspectiveOrigin'
'backfaceVisibility'
'boxSizing'
'mask'
]
@
# This section is wrapped in an immediately invoked function so that it can exit
# early when discovering a lack of browser support to prevent unnecessary work.
do ->
# Loop through the CSS map and replace each value with the result of `testProp()`.
for key, value of css
css[key] = testProp value
# If the returned value is false, warn the user that the browser doesn't support
# OriDomi, set `isSupported` to false, and break out of the loop.
return supportWarning value unless css[key]
# Test for `preserve-3d` as a transform style. This is particularly important
# since it's necessary for nested 3D transforms and recent versions of IE that
# support 3D transforms lack it.
p3d = 'preserve-3d'
testEl.style[css.transformStyle] = p3d
# Failure is indicated when querying the style lacks the correct string.
unless testEl.style[css.transformStyle] is p3d
return supportWarning p3d
# CSS3 linear gradients are used for shading.
# Testing for them is different because they are prefixed values, not properties.
# This invokes an anonymous function to loop through vendor-prefixed linear gradients.
css.gradientProp = do ->
for prefix in prefixList
hyphenated = "-#{ prefix.toLowerCase() }-linear-gradient"
testEl.style.backgroundImage = "#{ hyphenated }(left, #000, #fff)"
# After setting a gradient background on the test div, attempt to retrieve it.
return hyphenated unless testEl.style.backgroundImage.indexOf('gradient') is -1
# If none of the hyphenated values worked, return the un-prefixed version.
'linear-gradient'
# The default cursor style is set to `grab` to prompt the user to interact with the element.
# `grab` as a value isn't supported in all browsers so it has to be detected.
[css.grab, css.grabbing] = do ->
for prefix in prefixList
plainGrab = 'grab'
testEl.style.cursor = (grabValue = "-#{ prefix.toLowerCase() }-#{ plainGrab }")
# If the cursor was set correctly, return the prefixed pair.
return [grabValue, "-#{ prefix.toLowerCase() }-grabbing"] if testEl.style.cursor is grabValue
# Otherwise try the unprefixed version.
testEl.style.cursor = plainGrab
if testEl.style.cursor is plainGrab
[plainGrab, 'grabbing']
else
# Fallback to `move`.
['move', 'move']
# Like gradients, transform (as a transition value) needs to be detected and prefixed.
css.transformProp = do ->
# Use a regular expression to pluck the prefix `testProp` found.
if prefix = css.transform.match /(\w+)Transform/i
"-#{ prefix[1].toLowerCase() }-transform"
else
'transform'
# Set a `transitionEnd` property based on the browser's prefix for `transitionProperty`.
css.transitionEnd = do ->
switch css.transitionProperty.toLowerCase()
when 'transitionproperty' then 'transitionEnd'
when 'webkittransitionproperty' then 'webkitTransitionEnd'
when 'moztransitionproperty' then 'transitionend'
when 'mstransitionproperty' then 'msTransitionEnd'
# These calls generate OriDomi's stylesheet.
addStyle elClasses.active,
backgroundColor: 'transparent !important'
backgroundImage: 'none !important'
boxSizing: 'border-box !important'
border: 'none !important'
outline: 'none !important'
padding: '0 !important'
position: 'relative'
transformStyle: p3d + ' !important'
mask: 'none !important'
addStyle elClasses.clone,
margin: '0 !important'
boxSizing: 'border-box !important'
overflow: 'hidden !important'
display: 'block !important'
addStyle elClasses.holder,
width: '100%'
position: 'absolute'
top: '0'
bottom: '0'
transformStyle: p3d
addStyle elClasses.stage,
width: '100%'
height: '100%'
position: 'absolute'
transform: 'translate3d(-9999px, 0, 0)'
margin: '0'
padding: '0'
transformStyle: p3d
# Each anchor needs a particular perspective origin.
for k, v of {Left: '0% 50%', Right: '100% 50%', Top: '50% 0%', Bottom: '50% 100%'}
addStyle elClasses['stage' + k], perspectiveOrigin: v
addStyle elClasses.shader,
width: '100%'
height: '100%'
position: 'absolute'
opacity: '0'
top: '0'
left: '0'
pointerEvents: 'none'
transitionProperty: 'opacity'
# Linear gradient directions depend on their anchor.
for anchor in anchorList
addStyle elClasses['shader' + capitalize anchor], background: getGradient anchor
addStyle elClasses.content,
margin: '0 !important'
position: 'relative !important'
float: 'none !important'
boxSizing: 'border-box !important'
overflow: 'hidden !important'
addStyle elClasses.mask,
width: '100%'
height: '100%'
position: 'absolute'
overflow: 'hidden'
transform: 'translate3d(0, 0, 0)'
outline: '1px solid transparent'
addStyle elClasses.panel,
width: '100%'
height: '100%'
padding: '0'
position: 'relative'
transitionProperty: css.transformProp
transformOrigin: 'left'
transformStyle: p3d
addStyle elClasses.panelH, transformOrigin: 'top'
addStyle "#{ elClasses.stageRight } .#{ elClasses.panel }", transformOrigin: 'right'
addStyle "#{ elClasses.stageBottom } .#{ elClasses.panel }", transformOrigin: 'bottom'
styleEl = document.createElement 'style'
styleEl.type = 'text/css'
# Once the style buffer is ready, it's appended to the document as a stylesheet.
if styleEl.styleSheet
styleEl.styleSheet.cssText = styleBuffer
else
styleEl.appendChild document.createTextNode styleBuffer
document.head.appendChild styleEl
# Defaults
# ========
# These defaults are used by all OriDomi instances unless overridden.
defaults =
# The number of vertical panels (for folding left or right).
vPanels: 3
# The number of horizontal panels (for folding top or bottom).
hPanels: 3
# The determines the distance in pixels (z axis) of the camera/viewer to the paper.
# The smaller the value, the more distorted and exaggerated the effects will appear.
perspective: 1000
# The default shading style is hard, which shows distinct creases in the paper.
# Other options include `'soft'` -- for a smoother, more rounded look -- or `false`
# to disable shading altogether for a flat look.
shading: 'hard'
# Determines the duration of all animations in milliseconds.
speed: 700
# Configurable maximum angle for effects. With most effects, exceeding 90/-90 usually
# makes the element wrap around and pass through itself leading to some glitchy visuals.
maxAngle: 90
# Ripple mode causes effects to fold in a staggered, cascading manner.
# `1` indicates a forward cascade, `2` is backwards. It is disabled by default.
ripple: 0
# This CSS class is applied to OriDomi elements so they can be easily targeted later.
oriDomiClass: 'oridomi'
# This is a multiplier that determines the darkness of shading.
# If you need subtler shading, set this to a value below 1.
shadingIntensity: 1
# This option allows you to supply the name of a CSS easing method or a
# cubic bezier formula for customized animation easing.
easingMethod: ''
# Allows the user to fold the element via touch or mouse.
touchEnabled: true
# Coefficient of touch/drag action's distance delta. Higher numbers cause more movement.
touchSensitivity: .25
# Custom callbacks for touch/drag events. Each one is invoked with a relevant
# value so they can be used to manipulate objects outside of the OriDomi
# instance (e.g. sliding panels). x values are returned when folding left and
# right, y values for top and bottom. The second argument passed is the original
# touch or mouse event. These are empty functions by default. Invoked with
# starting coordinate as first argument.
touchStartCallback: noOp
# Invoked with the folded angle.
touchMoveCallback: noOp
# Inkoked with ending point.
touchEndCallback: noOp
# Constructor
# ===========
class OriDomi
constructor: (@el, options = {}) ->
return unless isSupported
# Prevent constructor calls made without `new`.
return new OriDomi arguments... unless @ instanceof OriDomi
# Support selector strings as well as elements.
@el = document.querySelector @el if typeof @el is 'string'
# Make sure element is valid.
unless @el and @el.nodeType is 1
console?.warn 'OriDomi: First argument must be a DOM element'
return
# Fill in passed options with defaults.
@_config = new ->
for k, v of defaults
if options[k]?
@[k] = options[k]
else
@[k] = v
@
# The ripple setting is converted to a number to allow boolean settings.
@_config.ripple = Number @_config.ripple
# The queue holds animation sequences.
@_queue = []
@_panels = {}
@_stages = {}
# Set the starting anchor to left.
@_lastOp = anchor: anchorList[0]
@_shading = @_config.shading
# Alias `shading: true` as hard shading.
@_shading = 'hard' if @_shading is true
# The shader elements are constructed in a conditional so the process can be
# skipped if shading is disabled.
if @_shading
@_shaders = {}
shaderProtos = {}
shaderProto = createEl 'shader'
shaderProto.style[css.transitionDuration] = @_config.speed + 'ms'
shaderProto.style[css.transitionTimingFunction] = @_config.easingMethod
stageProto = createEl 'stage'
stageProto.style[css.perspective] = @_config.perspective + 'px'
for anchor in anchorList
# Each anchor has a unique set of panels.
@_panels[anchor] = []
@_stages[anchor] = cloneEl stageProto, false, 'stage' + capitalize anchor
if @_shading
@_shaders[anchor] = {}
if anchor in anchorListV
@_shaders[anchor][side] = [] for side in anchorListV
else
@_shaders[anchor][side] = [] for side in anchorListH
shaderProtos[anchor] = cloneEl shaderProto, false, 'shader' + capitalize anchor
contentHolder = cloneEl @el, true, 'content'
maskProto = createEl 'mask'
maskProto.appendChild contentHolder
panelProto = createEl 'panel'
panelProto.style[css.transitionDuration] = @_config.speed + 'ms'
panelProto.style[css.transitionTimingFunction] = @_config.easingMethod
# This loop builds all of the panels.
for axis in ['x', 'y']
if axis is 'x'
anchorSet = anchorListV
count = @_config.vPanels
metric = 'width'
classSuffix = 'V'
else
anchorSet = anchorListH
count = @_config.hPanels
metric = 'height'
classSuffix = 'H'
# Set the panel dimension to a percentage of the container.
percent = 100 / count
mask = cloneEl maskProto, true, 'mask' + classSuffix
content = mask.children[0]
# The inner content retains the original dimensions of the element
# while being inside a small slice. By multiplying 100% by the number of
# panels on this axis, the size reduction of the parent in undone and
# sizing flexibility is achieved.
content.style.width = content.style.height = '100%'
content.style[metric] = content.style['max' + capitalize metric] = count * 100 + '%'
if @_shading
mask.appendChild shaderProtos[anchor] for anchor in anchorSet
proto = cloneEl panelProto, false, 'panel' + classSuffix
proto.appendChild mask
for anchor, n in anchorSet
for panelN in [0...count]
panel = proto.cloneNode true
# Only the first panel has its size set to a percentage since subsequent
# panels are nested children and will match its size.
panel.style[metric] = percent + '%' if panelN is 0
content = panel.children[0].children[0]
# The inner content of each panel is offset relative to the panel
# index to display a contiguous composition.
if n is 0
content.style[anchor] = -panelN * 100 + '%'
if panelN is 0
panel.style[anchor] = '0'
else
panel.style[anchor] = '100%'
else
content.style[anchorSet[0]] = (count - panelN - 1) * -100 + '%'
panel.style[css.origin] = anchor
if panelN is 0
panel.style[anchorSet[0]] = 100 - percent + '%'
else
panel.style[anchorSet[0]] = '-100%'
if @_shading
for a, i in anchorSet
@_shaders[anchor][a][panelN] = panel.children[0].children[i + 1]
@_panels[anchor][panelN] = panel
# Panels are nested inside each other.
@_panels[anchor][panelN - 1].appendChild panel unless panelN is 0
# Append the first panel to each stage.
@_stages[anchor].appendChild @_panels[anchor][0]
@_stageHolder = createEl 'holder'
@_stageHolder.appendChild @_stages[anchor] for anchor in anchorList
# Override default styling if original positioning is absolute.
if window.getComputedStyle(@el).position is 'absolute'
@el.style.position = 'absolute'
@el.classList.add elClasses.active
showEl @_stages.left
# The original element is cloned and hidden via transforms so the dimensions
# of the OriDomi content are maintained by it.
@_cloneEl = cloneEl @el, true, 'clone'
@_cloneEl.classList.remove elClasses.active
hideEl @_cloneEl
# Once the clone is stored the original element is emptied and appened with
# the clone and the OriDomi content.
@el.innerHTML = ''
@el.appendChild @_cloneEl
@el.appendChild @_stageHolder
# This ensures mouse events work correctly when panels are transformed
# away from the viewer.
@el.parentNode.style[css.transformStyle] = 'preserve-3d'
# An effect method is called since touch events rely on using the last
# method called.
@accordion 0
@setRipple @_config.ripple if @_config.ripple
@enableTouch() if @_config.touchEnabled
# Internal Methods
# ================
# This method is called for the action shifted off the queue.
_step: =>
# Return if the composition is currently in transition or the queue is empty.
return if @_inTrans or !@_queue.length
@_inTrans = true
# Destructure action arguments from the front of the queue.
[fn, angle, anchor, options] = @_queue.shift()
@unfreeze() if @isFrozen
# A local function for the next action is created should the call need to be
# deferred (if the stage is folded up or on the wrong anchor).
next = =>
@_setCallback {angle, anchor, options, fn}
args = [angle, anchor, options]
args.shift() if fn.length < 3
fn.apply @, args
if @isFoldedUp
if fn.length is 2
next()
else
@_unfold next
else if anchor isnt @_lastOp.anchor
@_stageReset anchor, next
else
next()
# This method tests if the called action is identical to the previous one.
# If two identical operations were called in a row, the transition callback
# wouldn't be called due to no animation taking place. This method reasons if
# movement has taken place, avoiding this pitfall of transition listeners.
_isIdenticalOperation: (op) ->
return true unless @_lastOp.fn
return false if @_lastOp.reset
(return false if @_lastOp[key] isnt op[key]) for key in ['angle', 'anchor', 'fn']
(return false if v isnt @_lastOp.options[k] and k isnt 'callback') for k, v of op.options
true
# This method normalizes callback handling for all public methods.
_setCallback: (operation) ->
# If there was no transformation, invoke the callback immediately.
if !@_config.speed or @_isIdenticalOperation operation
@_conclude operation.options.callback
# Otherwise, attach an event listener to be called on the transition's end.
else
@_panels[@_lastOp.anchor][0].addEventListener css.transitionEnd, @_onTransitionEnd, false
(@_lastOp = operation).reset = false
# Handler called when a CSS transition ends.
_onTransitionEnd: (e) =>
# Remove the event listener immediately to prevent bubbling.
e.currentTarget.removeEventListener css.transitionEnd, @_onTransitionEnd, false
# Initialize the transition teardown process.
@_conclude @_lastOp.options.callback, e
# Used to handle the end process of transitions and to initialize queued operations.
_conclude: (cb, event) =>
defer =>
@_inTrans = false
@_step()
cb? event, @
# Transforms a given element based on angle, anchor, and fracture boolean.
_transformPanel: (el, angle, anchor, fracture) ->
# The values of 1 and -1 are used to try to prevent small gaps from
# appearing between panels during transforms.
x = y = z = 0
switch anchor
when 'left'
y = angle
translate = 'X(-1'
when 'right'
y = -angle
translate = 'X(1'
when 'top'
x = -angle
translate = 'Y(-1'
when 'bottom'
x = angle
translate = 'Y(1'
# Rotate on every axis in fracture mode.
x = y = z = angle if fracture
el.style[css.transform] = """
rotateX(#{ x }deg)
rotateY(#{ y }deg)
rotateZ(#{ z }deg)
translate#{ translate }px)
"""
# This validates a given angle by making sure it's a float and by
# keeping it within the maximum range specified in the instance settings.
_normalizeAngle: (angle) ->
angle = parseFloat angle, 10
max = @_config.maxAngle
if isNaN angle
0
else if angle > max
max
else if angle < -max
-max
else
angle
# Allows other methods to change the transiton duration/delay or disable it altogether.
_setTrans: (duration, delay, anchor = @_lastOp.anchor) ->
@_iterate anchor, (panel, i, len) => @_setPanelTrans anchor, arguments..., duration, delay
# This method changes the transition duration and delay of panels and shaders.
_setPanelTrans: (anchor, panel, i, len, duration, delay) ->
delayMs = do =>
# Delay is a `ripple` value. The milliseconds are derived based on the
# speed setting and the number of panels.
switch delay
when 0 then 0
when 1 then @_config.speed / len * i
when 2 then @_config.speed / len * (len - i - 1)
panel.style[css.transitionDuration] = duration + 'ms'
panel.style[css.transitionDelay] = delayMs + 'ms'
if @_shading
for side in (if anchor in anchorListV then anchorListV else anchorListH)
shader = @_shaders[anchor][side][i]
shader.style[css.transitionDuration] = duration + 'ms'
shader.style[css.transitionDelay] = delayMs + 'ms'
delayMs
# Determines a shader's opacity based upon panel position, anchor, and angle.
_setShader: (n, anchor, angle) ->
# Store the angle's absolute value and generate an opacity based on `shadingIntensity`.
abs = Math.abs angle
opacity = abs / 90 * @_config.shadingIntensity
# With hard shading, opacity is reduced and `angle` is based on the global
# `lastAngle` so all panels' shaders share the same direction. Soft shaders
# have alternating directions.
if @_shading is 'hard'
opacity *= .15
if @_lastOp.angle < 0
angle = abs
else
angle = -abs
else
opacity *= .4
# This block makes sure left and top shaders appear for negative angles and right
# and bottom shaders appear for positive ones.
if anchor in anchorListV
if angle < 0
a = opacity
b = 0
else
a = 0
b = opacity
@_shaders[anchor].left[n].style.opacity = a
@_shaders[anchor].right[n].style.opacity = b
else
if angle < 0
a = 0
b = opacity
else
a = opacity
b = 0
@_shaders[anchor].top[n].style.opacity = a
@_shaders[anchor].bottom[n].style.opacity = b
# This method shows the requested stage element and sets a reference to it as
# the current stage.
_showStage: (anchor) ->
if anchor isnt @_lastOp.anchor
hideEl @_stages[@_lastOp.anchor]
@_lastOp.anchor = anchor
@_lastOp.reset = true
@_stages[anchor].style[css.transform] = 'translate3d(' + do =>
switch anchor
when 'left'
'0, 0, 0)'
when 'right'
"-#{ @_config.vPanels * 1 }px, 0, 0)"
when 'top'
'0, 0, 0)'
when 'bottom'
"0, -#{ (@_config.hPanels + 2) * 1 }px, 0)"
# If the composition needs to switch stages or fold up, it must first unfold
# all panels to 0 degrees.
_stageReset: (anchor, cb) =>
fn = (e) =>
e.currentTarget.removeEventListener css.transitionEnd, fn, false if e
@_showStage anchor
defer cb
# If already unfolded to 0, immediately invoke the change function.
return fn() if @_lastOp.angle is 0
@_panels[@_lastOp.anchor][0].addEventListener css.transitionEnd, fn, false
@_iterate @_lastOp.anchor, (panel, i) =>
@_transformPanel panel, 0, @_lastOp.anchor
@_setShader i, @_lastOp.anchor, 0 if @_shading
# Converts a shorthand anchor name to a full one.
_getLonghandAnchor: (shorthand) ->
switch shorthand.toString()
when 'left', 'l', '4'
'left'
when 'right', 'r', '2'
'right'
when 'top', 't', '1'
'top'
when 'bottom', 'b', '3'
'bottom'
else
# Left is always default.
'left'
# Gives the element a resize cursor to prompt the user to drag the mouse.
_setCursor: (bool = @_touchEnabled) ->
if bool
@el.style.cursor = css.grab
else
@el.style.cursor = 'default'
# Touch / Drag Event Handlers
# ===========================
# Adds or removes handlers from the element based on the boolean argument given.
_setTouch: (toggle) ->
if toggle
return @ if @_touchEnabled
listenFn = 'addEventListener'
else
return @ unless @_touchEnabled
listenFn = 'removeEventListener'
@_touchEnabled = toggle
@_setCursor()
# Array of event type pairs.
eventPairs = [['TouchStart', 'MouseDown'], ['TouchEnd', 'MouseUp'],
['TouchMove', 'MouseMove'], ['TouchLeave', 'MouseLeave']]
# Detect native `mouseleave` support.
mouseLeaveSupport = 'onmouseleave' of window
# Attach touch/drag event listeners in related pairs.
for eventPair in eventPairs
for eString in eventPair
unless eString is 'TouchLeave' and !mouseLeaveSupport
@el[listenFn] eString.toLowerCase(), @['_on' + eventPair[0]], false
else
@el[listenFn] 'mouseout', @_onMouseOut, false
break
@
# This method is called when a finger or mouse button is pressed on the element.
_onTouchStart: (e) =>
return if !@_touchEnabled or @isFoldedUp
e.preventDefault()
# Clear queued animations.
@emptyQueue()
# Set a property to track touch starts.
@_touchStarted = true
# Change the cursor to the active `grabbing` state.
@el.style.cursor = css.grabbing
# Disable tweening to enable instant 1 to 1 movement.
@_setTrans 0, 0
# Derive the axis to fold on.
@_touchAxis = if @_lastOp.anchor in anchorListV then 'x' else 'y'
# Set a reference to the last folded angle to accurately derive deltas.
@["_#{ @_touchAxis }Last"] = @_lastOp.angle
axis1 = "_#{ @_touchAxis }1"
# Determine the starting tap's coordinate for touch and mouse events.
if e.type is 'mousedown'
@[axis1] = e["page#{ @_touchAxis.toUpperCase() }"]
else
@[axis1] = e.targetTouches[0]["page#{ @_touchAxis.toUpperCase() }"]
# Return that value to an external listener.
@_config.touchStartCallback @[axis1], e
# Called on touch/mouse movement.
_onTouchMove: (e) =>
return unless @_touchEnabled and @_touchStarted
e.preventDefault()
# Set a reference to the current x or y position.
if e.type is 'mousemove'
current = e["page#{ @_touchAxis.toUpperCase() }"]
else
current = e.targetTouches[0]["page#{ @_touchAxis.toUpperCase() }"]
# Calculate distance and multiply by `touchSensitivity`.
distance = (current - @["_#{ @_touchAxis }1"]) * @_config.touchSensitivity
# Calculate final delta based on starting angle, anchor, and what side of zero
# the last operation was on.
if @_lastOp.angle < 0
if @_lastOp.anchor is 'right' or @_lastOp.anchor is 'bottom'
delta = @["_#{ @_touchAxis }Last"] - distance
else
delta = @["_#{ @_touchAxis }Last"] + distance
delta = 0 if delta > 0
else
if @_lastOp.anchor is 'right' or @_lastOp.anchor is 'bottom'
delta = @["_#{ @_touchAxis }Last"] + distance
else
delta = @["_#{ @_touchAxis }Last"] - distance
delta = 0 if delta < 0
@_lastOp.angle = delta = @_normalizeAngle delta
@_lastOp.fn.call @, delta, @_lastOp.anchor, @_lastOp.options
@_config.touchMoveCallback delta, e
# Teardown process when touch/drag event ends.
_onTouchEnd: (e) =>
return unless @_touchEnabled
# Restore the initial touch status and cursor.
@_touchStarted = @_inTrans = false
@el.style.cursor = css.grab
# Enable tweening again.
@_setTrans @_config.speed, @_config.ripple
# Pass callback final coordinate.
@_config.touchEndCallback @["_#{ @_touchAxis }Last"], e
# End folding when the mouse or finger leaves the composition.
_onTouchLeave: (e) =>
return unless @_touchEnabled and @_touchStarted
@_onTouchEnd e
# A fallback for browsers that don't support `mouseleave`.
_onMouseOut: (e) =>
return unless @_touchEnabled and @_touchStarted
@_onTouchEnd e if e.toElement and [email protected] e.toElement
# This method unfolds the composition after it's been folded up. It's private
# and doesn't use the decorator because it's used internally by other methods
# and skips the queue. Its public counterpart is a queued alias.
_unfold: (callback) ->
@_inTrans = true
{anchor} = @_lastOp
@_iterate anchor, (panel, i, len) =>
delay = @_setPanelTrans anchor, arguments..., @_config.speed, 1
do (panel, i, delay) =>
defer =>
@_transformPanel panel, 0, @_lastOp.anchor
setTimeout =>
showEl panel.children[0]
if i is len - 1
@_inTrans = @isFoldedUp = false
callback?()
@_lastOp.fn = @accordion
@_lastOp.angle = 0
defer => panel.style[css.transitionDuration] = @_config.speed
, delay + @_config.speed * .25
# This method is used by many others to iterate among panels within a given anchor.
_iterate: (anchor, fn) ->
fn.call @, panel, i, panels.length for panel, i in panels = @_panels[anchor]
# Public Methods
# ==============
# Enables touch events.
enableTouch: ->
@_setTouch true
# Disables touch events.
disableTouch: ->
@_setTouch false
# Public setter for transition durations.
setSpeed: (speed) ->
for anchor in anchorList
@_setTrans (@_config.speed = speed), @_config.ripple, anchor
@
# Disables OriDomi slicing by showing the original, untouched target element.