Implement a new control panel.
[hacks/simpleWebSlides.git] / simpleWebSlides.js
1 /*
2   Namespace object.
3 */
4
5 var SWS = SWS || {};
6
7
8
9 SWS.Utils = new function () {
10     var self = this;
11
12     self.isUndefined = function (o) { return typeof o == "undefined"; };
13     self.push2 = function (t, i, v) {
14         if ((typeof t[i]) == 'undefined') {
15             t[i] = new Array();
16         };
17         var l = t[i].length;
18         t[i][l] = v;
19     };
20
21     self.isEmpty = function (o) {
22         for(var _ in o) return false;
23         return true;
24     };
25
26     self.parseFrameSpec = function (s) {
27         var elems = s.split("_");
28         var result = {};
29         var min_last = 10000;
30         var max_value = -1;
31         for(var i = 0; i < elems.length; i++){
32             var bounds = elems[i].split("-");
33             if (bounds.length > 2 || bounds.length == 0) return {};
34             if (bounds.length == 1) bounds[1] = bounds[0];
35             var a = parseInt(bounds[0]);
36             var b = parseInt(bounds[1])
37             if (!isFinite(a) || !isFinite(b)) return {};
38             a = Math.min(a, 1000); // don't allow more than 1000 frames/slide
39             b = Math.min(b, 1000);
40             if (b > max_value) max_value = b;
41             for (var j = a; j <= b; j++)
42                 result[j] = true;
43         };
44         return result;
45     };
46
47
48 };
49
50
51
52
53 SWS.Templates = new function () {
54     var self = this;
55     self.controlPanel = "<div id='sws-control-panel-canvas'><div id='sws-control-panel'>\
56 <div id='sws-control-panel-title-bar'>\
57 <a title='Toggle fullscreen' id='sws-control-panel-fullscreen' class='sws-symbol' onclick='SWS.Presentation.toggleFullScreen();'></a>\
58 <a title='Close panel' id='sws-control-panel-close' onclick='$(\"#sws-control-panel-canvas\").toggle();'>&#x2716;</a>\
59 </div>\
60 <div id='sws-control-panel-options'>\
61 <span title='Change the aspect ratio' class='sws-symbol' >&#x1f4bb;</span><select id='sws-aspect-select' onchange='SWS.Presentation.changeAspect();'>\
62 <option value='sws-aspect-4-3'>4:3</option>\
63 <option value='sws-aspect-16-9'>16:9</option>\
64 <option value='sws-aspect-16-10'>16:10</option>\
65 </select>\
66 <span title='Change the theme' class='sws-symbol'>&#x1f3a8;</span><select id='sws-theme-select' onchange='SWS.Presentation.changeTheme();'></select>\
67 </div>\
68 <div id='sws-control-panel-navigation'>\
69 <a title='First slide' class='sws-symbol' onclick='SWS.Presentation.goToSlide(SWS.Presentation.firstSlide());' >&#x23ee;</a>\
70 <a title='Previous slide' class='sws-symbol' onclick='SWS.Presentation.previousSlide();SWS.Presentation.refresh();'>&#x23ea;</a>\
71 <a title='Previous step' class='sws-symbol' style='-webkit-transform: scaleX(-1);' onclick='SWS.Presentation.previous();SWS.Presentation.refresh();'>&#x25b6;</a>\
72 <a title='Next step' class='sws-symbol' onclick='SWS.Presentation.next();SWS.Presentation.refresh();'>&#x25b6;</a>\
73 <a title='Next slide' class='sws-symbol' onclick='SWS.Presentation.nextSlide();SWS.Presentation.refresh();'>&#x23e9;</a>\
74 <a title='Last slide' class='sws-symbol' onclick='SWS.Presentation.goToSlide(SWS.Presentation.lastSlide());'>&#x23ed;</a>\
75 <br/>\
76 <span class='sws-symbol'>&#xe4ae;</span><input type='text' id='sws-control-panel-slide-input' oninput='SWS.Presentation.goToSlide($(\"#sws-control-panel-slide-input\").val()-1);'></input><span id='sws-control-panel-total-slides'></span>\
77 <input type='range' title='Navigate the presentation' id='sws-control-panel-navigation-bar' onchange='SWS.Presentation.navigate();' step='1'></input>\
78 </div>\
79 </div>\
80 </div>";
81     self.slideActivate = function (o) {
82         if (!(o.hasClass("sws-active-slide"))){
83             o.removeClass("sws-inactive-slide").addClass("sws-active-slide");
84         };
85     };
86
87     self.slideDeactivate = function (o) {
88         if (!(o.hasClass("sws-inactive-slide"))){
89             o.removeClass("sws-active-slide").addClass("sws-inactive-slide");
90         };
91     };
92
93     self.slideChange = function (from, to) {
94         var canvas = $(".sws-canvas");
95         self.slideDeactivate($(canvas[from]));
96         self.slideActivate($(canvas[to]));
97     };
98
99     self.objectActivate = function (o) {
100         if (!(o.hasClass("sws-active-object"))){
101             o.removeClass("sws-inactive-object").addClass("sws-active-object");
102             o.css({'visibility':'visible'});
103             return true;
104         };
105         return false;
106     };
107
108     self.objectDeactivate = function (o) {
109         if (!(o.hasClass("sws-inactive-object"))){
110             o.addClass("sws-inactive-object").removeClass("sws-active-object");
111             return true;
112         };
113         return false;
114     };
115
116     self.updateFooter = function (o) {
117         var footer = o.find(".sws-footer");
118         if (footer.length && (footer.children("*").length == 0)) {
119             var i = SWS.Presentation.getCurrentSlide();
120             var cur = $( "<span class='sws-current-slide-number'>"
121                          + (i + 1)
122                          +"</span>");
123             var sep = $( "<span class='sws-slide-num-sep' />");
124             var tot = $( "<span class='sws-last-slide-number'>"
125                          + (SWS.Presentation.getNumSlides())
126                          +"</span>");
127             footer.append(cur).append(sep).append(tot);
128         };
129     };
130     self.updateHeader = function (o) {};
131 };
132 SWS.ConfigBuilder = function () {
133     var self = this;
134     self['sws-object-activate'] = SWS.Templates.objectActivate;
135     self['sws-object-deactivate'] = SWS.Templates.objectDeactivate;
136     self['sws-slide-change'] = SWS.Templates.slideChange;
137     self['sws-update-footer'] = SWS.Templates.updateFooter;
138     self['sws-update-header'] = SWS.Templates.updateHeader;
139 };
140
141 SWS.Defaults = new SWS.ConfigBuilder ();
142
143 SWS.Config = new SWS.ConfigBuilder ();
144
145
146 SWS.Effects = new function () {
147     var self = this;
148
149     self.objectDeactivateFadeOut = function (o) {
150         o.animate({'opacity': '0'}, 200,
151                   function () { SWS.Templates.objectDeactivate(o)});
152     };
153
154     self.objectActivateFadeIn = function (o) {
155
156         if (SWS.Templates.objectActivate(o)){
157             o.animate({'opacity': '1' }, 200);
158         };
159
160     };
161
162     self.slideChangeHorizontalFlip = function (from, to){
163         var f = SWS.Presentation.getSlide(from);
164         var t = SWS.Presentation.getSlide(to);
165         f.animate({ 'left': '50%', 'width': '0pt', 'opacity':'0' }, 150,
166                   function  () {
167                       SWS.Templates.slideDeactivate(f);
168                       f.css({'left':'0%', 'width': '100%'});
169                       t.css({ 'left': '50%', 'width': '0pt','opacity':'0' });
170                       SWS.Templates.slideActivate(t);
171                       t.animate({'left':'0%', 'width': '100%','opacity':'1'});
172                   });
173     };
174     self.slideChangeFadeOutIn = function (from, to) {
175         var f = SWS.Presentation.getSlide(from);
176         var t = SWS.Presentation.getSlide(to);
177         f.animate({ 'opacity': '0'}, 150,
178                   function () { SWS.Templates.slideDeactivate(f);
179                                 SWS.Templates.slideActivate(t);
180                                 t.css('opacity', '0');
181                                 t.animate({ 'opacity': '1'}, 150);
182                               });
183     };
184     self.slideChangeHorizontalSlide = function (from, to) {
185         var f = SWS.Presentation.getSlide(from);
186         var t = SWS.Presentation.getSlide(to);
187         if (from < to) {
188             t.css('left', '100%');
189             SWS.Templates.slideActivate(t);
190             f.animate({ 'left': '-100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
191             t.animate({ 'left': '0%' }, 250);
192         } else {
193             t.css('left', '-100%');
194             SWS.Templates.slideActivate(t);
195             f.animate({ 'left': '100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
196             t.animate({ 'left': '0%' }, 250);
197         };
198     };
199
200
201     self.slideChangeVerticalSlide = function (from, to) {
202         var f = SWS.Presentation.getSlide(from);
203         var t = SWS.Presentation.getSlide(to);
204         if (from < to) {
205             t.css('top', '100%');
206             SWS.Templates.slideActivate(t);
207             f.animate({ 'top': '-100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
208             t.animate({ 'top': '0%' }, 250);
209         } else {
210             t.css('top', '-100%');
211             SWS.Templates.slideActivate(t);
212             f.animate({ 'top': '100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
213             t.animate({ 'top': '0%' }, 250);
214         };
215     };
216
217 };
218
219 SWS.Fullscreen = new function () {
220     var self = this;
221
222     if (SWS.Utils.isUndefined(document.fullScreen)) {
223         if (SWS.Utils.isUndefined(document.mozfullScreen)) {
224             self.status = function () { return document.webkitIsFullScreen; };
225             self.enter = function(e) {
226                 e.webkitRequestFullScreen();
227             };
228             self.exit = function () {
229                 document.webkitCancelFullScreen();
230             };
231
232         } else {
233             self.status = function () { return document.mozfullScreen; };
234             self.enter = function(e) {
235                 e.mozRequestFullScreen();
236             };
237             self.exit = function () {
238                 document.mozCancelFullScreen();
239             };
240
241         };
242     } else {
243             self.status = function () { return document.fullScreen; };
244             self.enter = function(e) {
245                 e.requestFullScreen();
246             };
247             self.exit = function () {
248                 document.cancelFullScreen();
249             };
250
251     };
252
253
254 };
255
256 SWS.Presentation = new function () {
257
258
259     var self = this;
260
261     //TODO move outside of the Presentation object
262
263
264     var _total_slides;
265     var _initialized = false;
266     var _disable_input_events = false;
267
268     var _slide_callbacks = new Array ();
269
270
271     self.getNumSlides = function () { return _total_slides; };
272
273     self.getSlide = function(i) {
274         return $($(".sws-canvas")[i]);
275     };
276
277     self.registerCallback = function (i, f) {
278         if (_initialized) return;
279         //jQuery does not seem to work well
280         //on a partial DOM
281
282         var slide_num = $(".sws-slide").length - 1;
283
284         SWS.Utils.push2(_slide_callbacks, slide_num,{ 'fn': f, 'frame': i });
285
286     };
287
288     if (typeof(Storage)!=="undefined"){
289         self.getCurrentSlide = function () {
290             //unary + casts to integer
291             var i = +(sessionStorage.getItem("current_slide"));
292             if (!(i >= 0 && i < self.getNumSlides())){
293                 return 0;
294             } else {
295                 return i;
296             };
297         };
298
299         self.setCurrentSlide = function (i) {
300             sessionStorage.setItem("current_slide", i);
301         };
302
303     } else {
304         var _current_slide = 0;
305         self.getCurrentSlide = function () { return _current_slide; };
306         self.setCurrentSlide = function (i) { _current_slide = i; };
307
308     };
309     self.firstSlide = function () { return 0; };
310     self.lastSlide = function () { return self.getNumSlides() - 1; };
311     self.refresh = function () {
312         /* block upcoming input event until all animations are finished */
313         _disable_input_events = true;
314
315         var canvas = $(".sws-canvas");
316         var from_slide_num = canvas.index($(".sws-active-slide"));
317         var to_slide_num = self.getCurrentSlide();
318         var watch_slide_anim = false;
319         var to_slide = $(canvas[to_slide_num]);
320         var from_slide = $(canvas[from_slide_num]);
321         var slide_change = (from_slide_num != to_slide_num);
322
323         var info = to_slide.data("sws-frame-info");
324         SWS.Config['sws-update-header'](to_slide);
325         SWS.Config['sws-update-footer'](to_slide);
326
327         if (slide_change) {
328             //Launch a slide transition:
329             SWS.Config['sws-slide-change'](from_slide_num, to_slide_num);
330             watch_slide_anim = true;
331             for (var i = 0; i < info.callbacks.at_slide.length;i++){
332                 info.callbacks.at_slide[i](to_slide);
333             };
334         };
335
336
337         var cur = info.current;
338         var custom = info.custom;
339         var real_slide = to_slide.find(".sws-slide");
340
341         real_slide.find("*").andSelf().each(function (i){
342             var frameset = $(this).data("sws-frame-set") || {};
343             if (frameset[cur])
344                 SWS.Config['sws-object-activate']($(this));
345             else
346                 SWS.Config['sws-object-deactivate']($(this));
347         });
348
349         var callbacks;
350         if (callbacks = info.callbacks.at_frame[self.getCurrentFrame()]){
351             for (var k = 0; k < callbacks.length; k++)
352                 callbacks[k]($(to_slide));
353         };
354
355         var all = $(from_slide).add(to_slide);
356         all.find("*").addBack().promise().done(function() {
357             _disable_input_events = false;
358         });
359     };
360
361     self.nextSlide = function () {
362         self.setCurrentSlide(Math.min(self.getCurrentSlide()+1,
363                                       self.lastSlide()));
364         self.setCurrentFrame(self.firstFrame());
365     };
366
367     self.previousSlide = function () {
368         self.setCurrentSlide(Math.max(self.getCurrentSlide()-1,
369                                       self.firstSlide()));
370         self.setCurrentFrame(self.firstFrame());
371     };
372
373     self.getFrameInfo = function () {
374
375         var i = self.getCurrentSlide();
376         var canvas = $($(".sws-canvas")[i]);
377         var infos = canvas.data("sws-frame-info");
378         return infos;
379     };
380     self.getCurrentFrame = function () { return self.getFrameInfo().current; };
381     self.setCurrentFrame = function (i) { self.getFrameInfo().current = i; };
382     self.firstFrame = function () { return 0; };
383     self.lastFrame = function () { return self.getFrameInfo().last; };
384
385     self.nextFrame = function () {
386         self.setCurrentFrame(Math.min(self.getCurrentFrame()+1,
387                                       self.lastFrame()));
388
389     };
390     self.previousFrame = function () {
391         self.setCurrentFrame(Math.max(self.getCurrentFrame()-1,
392                                        self.firstFrame()));
393     };
394
395     self.next = function () {
396         var i = self.getCurrentFrame();
397         if (i == self.lastFrame()) {
398             self.nextSlide();
399             self.setCurrentFrame(self.firstFrame());
400         } else
401             self.nextFrame();
402     };
403
404     self.previous = function () {
405         var i = self.getCurrentFrame();
406         if (i == self.firstFrame()){
407             self.previousSlide();
408             self.setCurrentFrame(self.lastFrame());
409         }
410         else
411             self.previousFrame();
412     };
413
414     self.goToSlide = function (s, f) {
415         if (SWS.Utils.isUndefined(f))
416             f = 0;
417         if (!(s >= self.firstSlide() && s <= self.lastSlide())) return;
418         self.setCurrentSlide(s);
419         if (!(f >= self.firstFrame() && f <= self.lastFrame())) f = 0;
420         self.setCurrentFrame(f);
421         self.refresh();
422     };
423
424     self.cycleStyle = function() {
425         var styles = $("head").children('link[rel$="stylesheet"][title]');
426         var j = styles.index(styles.filter(':not(:disabled)'));
427         styles[j].disabled = true;
428         if (++j == styles.length) j = 0;
429         styles[j].disabled = false;
430     };
431
432     self.inputHandler = function (event) {
433         if (_disable_input_events) return;
434         switch (event.which) {
435         case 36:/* Home */
436             self.setCurrentSlide(self.firstSlide());
437             break;
438
439         case 35:/* End */
440             self.setCurrentSlide(self.lastSlide());
441             break;
442
443         case 32: /* space */
444         case 39: /* -> */
445
446             self.next();
447             break;
448         case 34: /* PgDown */
449         case 78: /* n */
450             self.nextSlide();
451             break;
452         case 8: /* backspace */
453         case 37: /* <-   */
454             self.previous();
455             break;
456         case 33: /* PgUp */
457         case 80: /* p */
458             self.previousSlide();
459             break;
460         case 83: /* s */
461             self.cycleStyle();
462             return;
463         case 67: /* c */
464             $("#sws-control-panel-canvas").toggle();
465         default:
466             return;
467         };
468         self.refresh();
469     };
470
471
472
473     function init_canvas(canvas, custom) {
474         var cur_frame = 0;
475         var last_frame = canvas.find(".sws-pause").length;
476         //Add all regular elements to the frame list
477         var slide = $(canvas.find(".sws-slide")[0]);
478
479         var callbacks = { at_slide : new Array(),
480                           at_frame : new Array() }
481
482         if (SWS.Utils.isUndefined(custom)) {
483             custom = new Array ();
484         };
485
486         for (var i = 0; i < custom.length; i++) {
487             if (isFinite(custom[i].frame)){
488                 var num = +(custom[i].frame);
489                 if (num > last_frame) last_frame = num;
490                 SWS.Utils.push2(callbacks.at_frame, num, custom[i].fn);
491             } else if (custom[i].frame == "slide")
492                 callbacks.at_slide.push(custom[i].fn);
493             else {
494                 var frame_set = SWS.Utils.parseFrameSpec(custom[i].frame);
495                 for(var f in frame_set){
496                     if (f > last_frame) last_frame = f;
497                     SWS.Utils.push2(callbacks.at_frame, +(f), custom[i].fn);
498                 };
499             }
500         };
501
502         var specials = null;
503
504         slide.find('*[class*="sws-onframe-"]').each(function(_){
505             var cls = $(this).attr('class');
506             var idx = cls.indexOf("sws-onframe-");
507             if (idx >= 0) {
508                 var end = cls.indexOf(" ", idx);
509                 end = (end == -1) ? cls.length : end;
510                 var spec = cls.substring(idx+12, end);
511                 var o = SWS.Utils.parseFrameSpec(spec);
512                 for(var f in o)
513                     if (f > last_frame) last_frame = f;
514                 $(this).find("*").andSelf().each(function(_){
515                     if (!SWS.Utils.isEmpty(o))
516                         $(this).data("sws-frame-set", o);
517                     if (specials)
518                         specials.add($(this));
519                     else
520                         specials = $(this);
521                 });
522             };
523         });
524
525         slide.find("*").andSelf().not(specials).each(function(i) {
526             if ($(this).hasClass("sws-pause"))  cur_frame++;
527             var o = {};
528             for (var j = cur_frame; j <= last_frame; j++)
529                 o[ j ] = true;
530             if (!SWS.Utils.isEmpty(o))
531                 $(this).data("sws-frame-set", o);
532         });
533
534         canvas.data("sws-frame-info", { current: 0,
535                                         last: last_frame,
536                                         callbacks: callbacks
537                                       });
538
539     };
540
541     /* Forces redrawing the page without reloading */
542     self.redraw = function () {
543         $("body").hide();
544         $("body").show();
545     };
546
547     self.changeAspect = function() {
548         $("html").removeClass("sws-aspect-4-3")
549             .removeClass("sws-aspect-16-9")
550             .removeClass("sws-aspect-16-10")
551             .addClass($("#sws-aspect-select").val());
552         self.redraw();
553     };
554
555
556     self.changeTheme = function () {
557         var theme_name = $("#sws-theme-select").val();
558         $("link.sws-theme").each (function (i) {
559             var e = $(this);
560             var title =  e.attr("title");
561             e[0].disabled = (title != theme_name);
562         });
563         self.redraw();
564     };
565
566
567     var _fullscreen_icon_on = "&#xe746;";
568     var _fullscreen_icon_off = "&#xe744;";
569
570     self.toggleFullScreen = function () {
571         if (SWS.Fullscreen.status()) {
572             SWS.Fullscreen.exit();
573             $("a#sws-control-panel-fullscreen")
574                 .html(_fullscreen_icon_off);
575
576
577
578         } else {
579             SWS.Fullscreen.enter($("body")[0]);
580             $("a#sws-control-panel-fullscreen")
581                 .html(_fullscreen_icon_on);
582         };
583     };
584     function _update_ui() {
585         var nav = $('#sws-control-panel-navigation-bar');
586         nav.val(SWS.Presentation.getCurrentSlide() + 1);
587         $('#sws-control-panel-slide-input').val(nav.val());
588     }
589     self.navigate = function () {
590         self.goToSlide($("#sws-control-panel-navigation-bar").val()-1);
591         _update_ui();
592     };
593
594
595     self.init = function () {
596
597
598
599         $(window).resize(self.redraw);
600
601
602         $(window).bind('storage', function (e) {
603             console.log(e);
604         });
605
606         _total_slides = $(".sws-slide").length;
607
608         $(document).keydown(self.inputHandler);
609
610
611         var cur = self.getCurrentSlide();
612         $(".sws-slide").each (function (i) {
613             var par = $(this).parent();
614
615             $(this).remove();
616             var canvas = $('<div class="sws-canvas"/>');
617
618             if (!($(this).hasClass("sws-option-noheader"))) {
619                 canvas.append($('<div class="sws-header"/><br/>'));
620             };
621
622             var inner = $('<div class="sws-inner-canvas"/>');
623             var content = $('<div class="sws-content"/>');
624             var title = $('<div class="sws-title"/>');
625             var h1 = $(this).children("h1");
626             if (h1) {
627               h1.detach();
628               title.append(h1);
629             }
630             canvas.append(title);
631             canvas.append($("<br/>"));
632             $(this).find('script[type="text/javascript"]').remove();
633             content.append($(this));
634             inner.append(content);
635             inner.append($('<span class="sws-vertical-align"> </span><br/>'));
636             canvas.append(inner);
637
638             if (!($(this).hasClass("sws-option-nofooter"))) {
639                 canvas.append($('<div class="sws-footer"/>'));
640             };
641
642             par.append(canvas);
643
644             if (i == cur) {
645                 canvas
646                     .addClass("sws-active-slide")
647                     .removeClass("sws-inactive-slide");
648             } else {
649                 canvas
650                     .addClass("sws-inactive-slide")
651                     .removeClass("sws-active-slide");
652             };
653             init_canvas(canvas,_slide_callbacks[i]);
654
655         });
656
657
658
659         // Initialize the control panel
660         $("body").append($(SWS.Templates.controlPanel));
661         // Fill the theme switcher
662         $("link.sws-theme").each (function (i) {
663             var e = $(this);
664             var opt = "<option value='";
665             opt += e.attr("title");
666             opt += "' ";
667             if (e.attr("rel") == "stylesheet") {
668                 opt+= "selected='selected'";
669             };
670             opt += ">" + e.attr("title") + "</option>";
671             $("#sws-theme-select").append($(opt));
672         });
673         // Set the fullscreen icon
674         if (SWS.Fullscreen.status()) {
675             $("a#sws-control-panel-fullscreen")
676                 .html(_fullscreen_icon_on);
677         } else {
678             $("a#sws-control-panel-fullscreen")
679                 .html(_fullscreen_icon_off);
680         };
681         // Put the navigation range at the correct position
682         var nav = $('#sws-control-panel-navigation-bar');
683         nav.attr("min", SWS.Presentation.firstSlide() + 1);
684         nav.attr("max", SWS.Presentation.lastSlide() + 1);
685         $('#sws-control-panel-total-slides').text('/' + SWS.Presentation.getNumSlides());
686         _update_ui();
687
688         _slide_callbacks = null; /* avoid a leak */
689         self.refresh();
690         _initialized = true;
691
692
693     };
694
695 };