/[suikacvs]/webroot/www/js/jste/tutorial.js
Suika

Contents of /webroot/www/js/jste/tutorial.js

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.32 - (hide annotations) (download) (as text)
Tue Feb 3 12:45:21 2009 UTC (16 years, 6 months ago) by wakaba
Branch: MAIN
Changes since 1.31: +30 -13 lines
File MIME type: application/javascript
IE support

1 wakaba 1.1 if (typeof (JSTE) === "undefined") var JSTE = {};
2    
3     JSTE.WATNS = 'http://suika.fam.cx/ns/wat';
4     JSTE.SpaceChars = /[\x09\x0A\x0C\x0D\x20]+/;
5    
6     JSTE.Class = function (constructor, prototype) {
7     return JSTE.Subclass (constructor, JSTE.EventTarget, prototype);
8     }; // Class
9    
10     JSTE.Class.addClassMethods = function (classObject, methods) {
11     new JSTE.Hash (methods).forEach (function (n, v) {
12     if (!classObject[n]) {
13     classObject[n] = v;
14     }
15     });
16     }; // addClassMethods
17    
18     JSTE.Subclass = function (constructor, superclass, prototype) {
19     constructor.prototype = new superclass;
20     for (var n in prototype) {
21     constructor.prototype[n] = prototype[n];
22     }
23     constructor.prototype.constructor = constructor;
24     constructor.prototype._super = superclass;
25     return constructor;
26     }; // Subclass
27    
28     JSTE.EventTarget = new JSTE.Subclass (function () {
29    
30     }, function () {}, {
31     addEventListener: function (eventType, handler, useCapture) {
32     if (useCapture) return;
33     if (!this.eventListeners) this.eventListeners = {};
34     if (!this.eventListeners[eventType]) {
35     this.eventListeners[eventType] = new JSTE.List;
36     }
37     this.eventListeners[eventType].push (handler);
38     }, // addEventListener
39     removeEventListener: function (eventType, handler, useCapture) {
40     if (useCapture) return;
41     if (!this.eventListeners) return;
42     if (!this.eventListeners[eventType]) return;
43     this.eventListeners[eventType].remove (handler);
44     }, // removeEventListener
45     dispatchEvent: function (e) {
46     if (!this.eventListeners) return;
47     var handlers = this.eventListeners[e.type];
48     if (!handlers) return;
49     e.currentTarget = this;
50     e.target = this;
51     var preventDefault;
52     handlers.forEach (function (handler) {
53     if (handler.apply (this, [e])) {
54     preventDefault = true;
55     }
56     });
57     return preventDefault || e.isDefaultPrevented ();
58     } // dispatchEvent
59     }); // EventTarget
60    
61     JSTE.Event = new JSTE.Class (function (eventType, canBubble, cancelable) {
62     this.type = eventType;
63     this.bubbles = canBubble;
64     this.cancelable = cancelable;
65     }, {
66     preventDefault: function () {
67     this.defaultPrevented = true;
68     }, // preventDefault
69     isDefaultPrevented: function () {
70     return this.defaultPrevented;
71     } // isDefaultPrevented
72     });
73    
74     JSTE.Observer = new JSTE.Class (function (eventType, target, onevent) {
75     this.eventType = eventType;
76 wakaba 1.10 this.target = target;
77 wakaba 1.1 if (target.addEventListener) {
78     this.code = onevent;
79     } else if (target.attachEvent) {
80     this.code = function () {
81     onevent (event);
82     };
83 wakaba 1.10 } else {
84     this.code = onevent;
85 wakaba 1.1 }
86 wakaba 1.10 this.disabled = true;
87     this.start ();
88 wakaba 1.1 }, {
89 wakaba 1.10 start: function () {
90     if (!this.disabled) return;
91     if (this.target.addEventListener) {
92     this.target.addEventListener (this.eventType, this.code, false);
93     this.disabled = false;
94     } else if (this.target.attachEvent) {
95     this.target.attachEvent ("on" + this.eventType, this.code);
96     this.disabled = false;
97     }
98     }, // start
99 wakaba 1.1 stop: function () {
100 wakaba 1.10 if (this.disabled) return;
101 wakaba 1.1 if (this.target.removeEventListener) {
102     this.target.removeEventListener (this.eventType, this.code, false);
103 wakaba 1.10 this.disabled = true;
104 wakaba 1.11 } else if (this.target.detachEvent) {
105 wakaba 1.1 this.target.detachEvent ("on" + this.eventType, this.code);
106 wakaba 1.10 this.disabled = true;
107 wakaba 1.1 }
108     } // stop
109     }); // Observer
110    
111 wakaba 1.5 new JSTE.Observer ('load', window, function () {
112     JSTE.windowLoaded = true;
113     });
114    
115 wakaba 1.10
116 wakaba 1.31
117 wakaba 1.10 JSTE.Hash = new JSTE.Class (function (hash) {
118     this.hash = hash || {};
119     }, {
120     forEach: function (code) {
121     for (var n in this.hash) {
122     var r = code (n, this.hash[n]);
123     if (r && r.stop) break;
124     }
125     }, // forEach
126     clone: function (code) {
127     var newHash = {};
128     this.forEach (function (n, v) {
129     newHash[n] = v;
130     });
131     return new this.constructor (newHash);
132     }, // clone
133    
134     getNamedItem: function (n) {
135     return this.hash[n];
136     }, // getNamedItem
137     setNamedItem: function (n, v) {
138     return this.hash[n] = v;
139 wakaba 1.22 }, // setNamedItem
140    
141 wakaba 1.23 getNames: function () {
142     var r = new JSTE.List;
143     for (var n in this.hash) {
144     r.push (n);
145     }
146     return r;
147     }, // getNames
148    
149 wakaba 1.22 getByNames: function (names) {
150     var self = this;
151     return names.forEach (function (name) {
152     var value = self.getNamedItem (name);
153     if (value != null) {
154     return new JSTE.List.Return (value);
155     } else {
156     return null;
157     }
158     });
159     } // getByNames
160     }); // Hash
161 wakaba 1.10
162    
163 wakaba 1.1 JSTE.List = new JSTE.Class (function (arrayLike) {
164     this.list = arrayLike || [];
165     }, {
166     getLast: function () {
167     if (this.list.length) {
168     return this.list[this.list.length - 1];
169     } else {
170     return null;
171     }
172     }, // getLast
173    
174     forEach: function (code) {
175     var length = this.list.length;
176     for (var i = 0; i < length; i++) {
177     var r = code (this.list[i]);
178     if (r && r.stop) return r.returnValue;
179     }
180     return null;
181     }, // forEach
182 wakaba 1.23 map: function (code) {
183     var newList = new this.constructor;
184     var length = this.list.length;
185     for (var i = 0; i < length; i++) {
186     newList.push (code (this.list[i]));
187     }
188     return newList;
189     }, // map
190     mapToHash: function (code) {
191     var newHash = new JSTE.Hash;
192     var length = this.list.length;
193     for (var i = 0; i < length; i++) {
194     var nv = code (this.list[i]);
195     newHash.setNamedItem (nv[0], nv[1]);
196     }
197     return newHash;
198     }, // mapToHash
199 wakaba 1.4
200     numberToInteger: function () {
201     var newList = [];
202     this.forEach (function (item) {
203     if (typeof item === "number") {
204     newList.push (Math.floor (item));
205     } else {
206     newList.push (item);
207     }
208     });
209     return new this.constructor (newList);
210     }, // numberToInteger
211 wakaba 1.23
212 wakaba 1.1 clone: function () {
213     var newList = [];
214     this.forEach (function (item) {
215     newList.push (item);
216     });
217     return new this.constructor (newList);
218     }, // clone
219    
220     grep: function (code) {
221     var newList = [];
222     this.forEach (function (item) {
223     if (code (item)) {
224     newList.push (item);
225     }
226     });
227     return new this.constructor (newList);
228     }, // grep
229     onlyNonNull: function () {
230     return this.grep (function (item) {
231     return item != null; /* Intentionally "!=" */
232     });
233     }, // onlyNonNull
234 wakaba 1.11
235     uniq: function (eq) {
236     if (!eq) eq = function (i1, i2) { return i1 === i2 };
237     var prevItems = [];
238     return this.grep (function (item) {
239     for (var i = 0; i < prevItems.length; i++) {
240     if (eq (item, prevItems[i])) {
241     return false;
242     }
243     }
244     prevItems.push (item);
245     return true;
246     });
247     }, // uniq
248 wakaba 1.1
249     getFirstMatch: function (code) {
250     return this.forEach (function (item) {
251     if (code (item)) {
252     return new JSTE.List.Return (item);
253     }
254     });
255     }, // getFirstMatch
256    
257     switchByElementType: function () {
258     var cases = new JSTE.List (arguments);
259     this.forEach (function (n) {
260     cases.forEach (function (c) {
261     if (c.namespaceURI == n.namespaceURI) {
262     return new JSTE.List.Return (c.execute (n));
263     }
264     });
265     });
266     }, // switchByElementType
267    
268 wakaba 1.10 // destructive
269 wakaba 1.1 push: function (item) {
270     this.list.push (item);
271     }, // push
272 wakaba 1.10
273     // destructive
274 wakaba 1.1 pushCloneOfLast: function () {
275     this.list.push (this.getLast ().clone ());
276     }, // pushCloneOfLast
277 wakaba 1.10
278     // destructive
279 wakaba 1.1 append: function (list) {
280     var self = this;
281     list.forEach (function (n) {
282     self.list.push (n);
283     });
284 wakaba 1.10 return this;
285 wakaba 1.1 }, // append
286    
287 wakaba 1.10 // destructive
288 wakaba 1.1 pop: function () {
289     return this.list.pop ();
290     }, // pop
291 wakaba 1.10
292     // destructive
293 wakaba 1.1 remove: function (removedItem) {
294     var length = this.list.length;
295     for (var i = length - 1; i >= 0; --i) {
296     var item = this.list[i];
297     if (item == removedItem) { // Intentionally "=="
298     this.list.splice (i, 1);
299     }
300     }
301     }, // remove
302 wakaba 1.10
303     // destructive
304 wakaba 1.1 clear: function () {
305     this.list.splice (0, this.list.length);
306     } // clear
307    
308     }); // List
309    
310 wakaba 1.10 JSTE.Class.addClassMethods (JSTE.List, {
311     spaceSeparated: function (v) {
312     return new JSTE.List ((v || '').split (JSTE.SpaceChars)).grep (function (v) {
313     return v.length;
314     });
315     }, // spaceSeparated
316    
317     getCommonItems: function (l1, l2, cb, eq) {
318 wakaba 1.11 if (!eq) eq = function (i1, i2) { return i1 === i2 };
319 wakaba 1.10
320     var common = new JSTE.List;
321    
322     l1 = l1.grep (function (i1) {
323     var hasI1;
324     l2 = l2.grep (function (i2) {
325     if (eq (i1, i2)) {
326     common.push (i1);
327     hasI1 = true;
328     return false;
329     } else {
330     return true;
331     }
332     });
333     return !hasI1;
334     });
335    
336     cb (common, l1, l2);
337     } // getCommonItems
338     }); // List class methods
339    
340 wakaba 1.1 JSTE.List.Return = new JSTE.Class (function (rv) {
341     this.stop = true;
342     this.returnValue = rv;
343     }, {
344    
345     }); // Return
346    
347     JSTE.List.SwitchByLocalName = new JSTE.Class (function (ns, cases, ow) {
348     this.namespaceURI = ns;
349     this.cases = cases;
350     this.otherwise = ow || function (n) { };
351     }, {
352     execute: function (n) {
353     for (var ln in this.cases) {
354     if (JSTE.Element.matchLocalName (n, ln)) {
355     return this.cases[ln] (n);
356     }
357     }
358     return this.otherwise (n);
359     }
360     });
361    
362 wakaba 1.29 JSTE.Set = {};
363    
364     JSTE.Set.Unordered = new JSTE.Class (function () {
365     // this.caseInsensitive
366     }, {
367     addFromList: function (list) {
368     var self = this;
369     list.forEach (function (name) {
370     if (self.caseInsensitive) name = name.toLowerCase ();
371     self['value-' + name] = true;
372     });
373     }, // addFromList
374    
375     has: function (name) {
376     if (this.caseInsensitive) name = name.toLowerCase ();
377     return this['value-' + name] !== undefined;
378     } // has
379     }); // Unordered
380    
381 wakaba 1.1
382     if (!JSTE.Node) JSTE.Node = {};
383    
384     JSTE.Class.addClassMethods (JSTE.Node, {
385     querySelector: function (node, selectors) {
386     if (node.querySelector) {
387     var el;
388     try {
389     el = node.querySelector (selectors);
390     } catch (e) {
391     el = null;
392     }
393     return el;
394     } else if (window.uu && uu.css) {
395     if (selectors != "") {
396     /* NOTE: uu.css return all elements for "" or ",xxx" */
397     return uu.css (selectors, node)[0];
398     } else {
399     return null;
400     }
401     } else if (window.Ten && Ten.DOM && Ten.DOM.getElementsBySelector) {
402     return Ten.DOM.getElementsBySelector (selectors)[0];
403     } else {
404     return null;
405     }
406     }, // querySelector
407     querySelectorAll: function (node, selectors) {
408     if (node.querySelectorAll) {
409     var nl;
410     try {
411     nl = node.querySelectorAll (selectors);
412     } catch (e) {
413     nl = null;
414     }
415     return new JSTE.List (nl);
416     } else if (window.uu && uu.css) {
417     if (selectors != "") {
418 wakaba 1.11 /* NOTE: uu.css return all elements for "" or ",xxx". */
419 wakaba 1.1 return new JSTE.List (uu.css (selectors, node));
420     } else {
421     return new JSTE.List;
422     }
423     } else if (window.Ten && Ten.DOM && Ten.DOM.getElementsBySelector) {
424     return new JSTE.List (Ten.DOM.getElementsBySelector (selectors));
425     } else {
426     return new JSTE.List;
427     }
428     } // querySelectorAll
429     });
430    
431 wakaba 1.27 JSTE.Document = {};
432    
433     JSTE.Class.addClassMethods (JSTE.Document, {
434 wakaba 1.29 getTheHTMLElement: function (doc) {
435     var el = doc.documentElement;
436     // BUG: XML support
437 wakaba 1.27 if (el.nodeName.toUpperCase () == 'HTML') {
438     return el;
439     } else {
440     return null;
441     }
442     }, // getTheHTMLElement
443 wakaba 1.29 getTheHeadElement: function (doc) {
444     // BUG: XML support
445     var el = JSTE.Document.getTheHTMLElement (doc);
446 wakaba 1.27 if (!el) return null;
447     var elc = el.childNodes;
448     for (i = 0; i < elc.length; i++) {
449     var cel = elc[i];
450     if (cel.nodeName.toUpperCase () == 'HEAD') {
451     return cel;
452     }
453     }
454     return null;
455     }, // getTheHeadElement
456    
457 wakaba 1.29 getClassNames: function (doc) {
458     // BUG: XML support
459     var r = new JSTE.Set.Unordered ();
460     r.caseInsensitive = doc.compatMode != 'CSS1Compat';
461    
462     var docEl = doc.documentElement;
463     if (docEl) {
464     r.addFromList (JSTE.List.spaceSeparated (docEl.className));
465     }
466    
467     var bodyEl = doc.body;
468     if (bodyEl) {
469     r.addFromList (JSTE.List.spaceSeparated (bodyEl.className));
470     }
471    
472     return r;
473     } // getClassNames
474 wakaba 1.27 }); // JSTE.Document class methods
475    
476 wakaba 1.1 if (!JSTE.Element) JSTE.Element = {};
477    
478     JSTE.Class.addClassMethods (JSTE.Element, {
479     getLocalName: function (el) {
480     var localName = el.localName;
481     if (!localName) {
482     localName = el.nodeName;
483     if (el.prefix) {
484     localName = localName.substring (el.prefix.length + 1);
485     }
486     }
487     return localName;
488     }, // getLocalName
489    
490     match: function (el, ns, ln) {
491     if (el.nodeType !== 1) return false;
492     if (el.namespaceURI !== ns) return false;
493     return JSTE.Element.matchLocalName (el, ln);
494     }, // match
495     matchLocalName: function (el, ln) {
496     var localName = JSTE.Element.getLocalName (el);
497     if (ln instanceof RegExp) {
498     if (!localName.match (ln)) return false;
499     } else {
500     if (localName !== ln) return false;
501     }
502     return true;
503     }, // matchLocalName
504    
505     getChildElement: function (el, ns, ln) {
506     return new JSTE.List (el.childNodes).getFirstMatch (function (item) {
507     return JSTE.Element.match (item, ns, ln);
508     });
509     }, // getChildElement
510     getChildElements: function (el, ns, ln) {
511     return new JSTE.List (el.childNodes).grep (function (item) {
512     return JSTE.Element.match (item, ns, ln);
513     });
514     }, // getChildElements
515 wakaba 1.17 getChildrenClassifiedByType: function (el) {
516     var r = new JSTE.ElementHash;
517     new JSTE.List (el.childNodes).forEach (function (n) {
518     if (n.nodeType == 1) {
519     r.getOrCreate (n.namespaceURI, JSTE.Element.getLocalName (n)).push (n);
520     } else {
521     r.getOrCreate (null, n.nodeType).push (n);
522     }
523     });
524     return r;
525     }, // getChildrenClassifiedByType
526 wakaba 1.18
527     isEmpty: function (el) {
528     // HTML5 definition of "empty"
529     return !new JSTE.List (el.childNodes).forEach (function (n) {
530     var nt = n.nodeType;
531     if (nt == 1) {
532     return new JSTE.List.Return (true /* not empty */);
533     } else if (nt == 3 || nt == 4) {
534     if (/[^\u0009\u000A\u000C\u000D\u0020]/.test (n.data)) {
535     return new JSTE.List.Return (true /* not empty */);
536     }
537     } else if (nt == 7 || nt == 8) { // comment/pi
538     // does not affect emptyness
539     } else {
540     // We don't support EntityReference.
541     return new JSTE.List.Return (true /* not empty */);
542     }
543     });
544     }, // isEmpty
545 wakaba 1.1
546     appendText: function (el, s) {
547     return el.appendChild (el.ownerDocument.createTextNode (s));
548     }, // appendText
549    
550 wakaba 1.29 appendToHead: function (el) {
551     var doc = el.ownerDocument;
552     var head = JSTE.Document.getTheHeadElement (doc) || doc.body || doc.documentElement || doc;
553     head.appendChild (el);
554     }, // appendToHead
555    
556 wakaba 1.1 createTemplate: function (doc, node) {
557     var df = doc.createDocumentFragment ();
558     new JSTE.List (node.childNodes).forEach (function (n) {
559     if (n.nodeType == 1) {
560     var c = doc.createElement (JSTE.Element.getLocalName (n));
561 wakaba 1.15 new JSTE.List (n.attributes).forEach (function (n) {
562 wakaba 1.1 c.setAttribute (n.name, n.value);
563     });
564     c.appendChild (JSTE.Element.createTemplate (doc, n));
565     df.appendChild (c);
566     } else if (n.nodeType == 3 || n.nodeType == 4) {
567     df.appendChild (doc.createTextNode (n.data));
568     }
569     });
570     return df;
571     }, // createTemplate
572    
573     hasAttribute: function (el, localName) {
574     if (el.hasAttribute) {
575     return el.hasAttribute (localName);
576     } else {
577     return el.getAttribute (localName) != null;
578     }
579     }, // hasAttribute
580    
581     getClassNames: function (el) {
582     return new JSTE.List (el.className.split (JSTE.SpaceChars));
583     }, // getClassNames
584     addClassName: function (el, newClassName) {
585     el.className = el.className + ' ' + newClassName;
586     }, // deleteClassName
587     deleteClassName: function (el, oldClassName) {
588     var classNames = el.className.split (JSTE.SpaceChars);
589     var newClasses = [];
590     for (var n in classNames) {
591     if (classNames[n] != oldClassName) {
592     newClasses.push (classNames[n]);
593     }
594     }
595     el.className = newClasses.join (' ');
596     }, // deleteClassName
597     replaceClassName: function (el, oldClassName, newClassName) {
598     var classNames = el.className.split (JSTE.SpaceChars);
599     var newClasses = [newClassName];
600     for (var n in classNames) {
601     if (classNames[n] != oldClassName) {
602     newClasses.push (classNames[n]);
603     }
604     }
605     el.className = newClasses.join (' ');
606     }, // replaceClassName
607    
608     getIds: function (el) {
609     return new JSTE.List (el.id != "" ? [el.id] : []);
610 wakaba 1.5 }, // getIds
611    
612     /*
613     NR.js <http://suika.fam.cx/www/css/noderect/NodeRect.js> must be loaded
614     before the invocation.
615     */
616     scroll: function (elements) {
617     if (!JSTE.windowLoaded) {
618     new JSTE.Observer ('load', window, function () {
619     JSTE.Element.scroll (elements);
620     });
621     return;
622     }
623    
624     var top = Infinity;
625     var left = Infinity;
626     var topEl;
627     var leftEl;
628     elements.forEach (function (el) {
629     var rect = NR.Element.getRects (el, window).borderBox;
630     if (rect.top < top) {
631     top = rect.top;
632     topEl = el;
633     }
634     if (rect.left < left) {
635     left = rect.left;
636     leftEl = el;
637     }
638     });
639    
640     if (!leftEl && !topEl) {
641     return;
642     }
643    
644     var doc = (leftEl || topEl).ownerDocument;
645 wakaba 1.1
646 wakaba 1.5 var rect = NR.View.getViewportRects (window, doc).contentBox;
647     if (rect.top <= top && top <= rect.bottom) {
648     top = rect.top;
649     }
650     if (rect.left <= left && left <= rect.right) {
651     left = rect.left;
652     }
653    
654     /*
655     Set scroll* of both <html> and <body> elements, to support all of
656     four browsers and two (or three) rendering modes. This might result
657     in confusing the user if both <html> and <body> elements have their
658     'overflow' properties specified to 'scroll'.
659    
660     Note that this code does not do a good job if the |el| is within an
661     |overflow: scroll| element.
662     */
663     doc.body.scrollTop = top;
664     doc.body.scrollLeft = left;
665     doc.documentElement.scrollTop = top;
666     doc.documentElement.scrollLeft = left;
667     } // scroll
668 wakaba 1.18 }); // Element
669 wakaba 1.1
670 wakaba 1.17 JSTE.ElementHash = new JSTE.Class (function () {
671     this.items = [];
672     }, {
673     get: function (ns, ln) {
674     ns = ns || '';
675     if (this.items[ns]) {
676     return this.items[ns].getNamedItem (ln) || new JSTE.List;
677     } else {
678     return new JSTE.List;
679     }
680     }, // get
681     getOrCreate: function (ns, ln) {
682     ns = ns || '';
683     if (this.items[ns]) {
684     var l = this.items[ns].getNamedItem (ln);
685     if (!l) this.items[ns].setNamedItem (ln, l = new JSTE.List);
686     return l;
687     } else {
688     var l;
689     this.items[ns] = new JSTE.Hash;
690     this.items[ns].setNamedItem (ln, l = new JSTE.List);
691     return l;
692     }
693     } // getOrCreate
694     }); // ElementHash
695 wakaba 1.31
696    
697    
698     JSTE.Script = {};
699    
700     JSTE.Class.addClassMethods (JSTE.Script, {
701     loadScripts: function (urls, onload) {
702     var number = urls.list.length;
703     var counter = 0;
704     var check = function () {
705     script.onload = null;
706     script.onreadystatechange = null;
707     if (counter == number) {
708     onload ();
709     }
710     };
711     urls.forEach (function (url) {
712     var script = document.createElement ('script');
713     script.src = url;
714     script.onload = function () {
715     counter++;
716     check ();
717     };
718     script.onreadystatechange = function () {
719     if (script.readyState != 'complete' && script.readyState != 'loaded') {
720     return;
721     }
722     counter++;
723     check ();
724     };
725     document.body.appendChild (script);
726     });
727     } // loadScripts
728     }); // Script class methods
729    
730     JSTE.Style = {};
731    
732     JSTE.Class.addClassMethods (JSTE.Style, {
733     loadStyle: function (url) {
734     var link = document.createElement ('link');
735     link.rel = 'stylesheet';
736     link.href = url;
737     JSTE.Element.appendToHead (link);
738     } // loadStyle
739     }); // Style class methods
740    
741    
742 wakaba 1.17
743 wakaba 1.27 JSTE.Prefetch = {};
744    
745     JSTE.Class.addClassMethods (JSTE.Prefetch, {
746     URL: function (url) {
747     var link = document.createElement ('link');
748     link.rel = 'prefetch';
749     link.href = url;
750 wakaba 1.29 JSTE.Element.appendToHead (link);
751 wakaba 1.27 } // url
752     }); // JSTE.Prefetch class methods
753    
754 wakaba 1.32
755     JSTE.URL = {};
756    
757     JSTE.Class.addClassMethods (JSTE.URL, {
758     eq: function (u1, u2) {
759     // TODO: maybe we should once decode URLs and then reencode them
760     u1 = (u1 || '').replace (/([^\x21-\x7E]+)/, function (s) { return encodeURI (s) });
761     u2 = (u2 || '').replace (/([^\x21-\x7E]+)/, function (s) { return encodeURI (s) });
762     return u1 == u2;
763     } // eq
764     }); // URL class methods
765    
766    
767 wakaba 1.9 JSTE.XHR = new JSTE.Class (function (url, onsuccess, onerror) {
768     try {
769     this._xhr = new XMLHttpRequest ();
770     } catch (e) {
771     try {
772     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP');
773     } catch (e) {
774     try {
775     this._xhr = new ActiveXObject ('Microsoft.XMLHTTP');
776     } catch (e) {
777     try {
778     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP.4.0');
779     } catch (e) {
780     this._xhr = null;
781     }
782     }
783     }
784     }
785    
786     this._url = url;
787     this._onsuccess = onsuccess || function () { };
788     this._onerror = onerror || function () { };
789     }, {
790     get: function () {
791     if (!this._xhr) return;
792    
793     var self = this;
794     this._xhr.open ('GET', this._url, true);
795     this._xhr.onreadystatechange = function () {
796     self._onreadystatechange ();
797     }; // onreadystatechange
798     this._xhr.send (null);
799     }, // get
800    
801     _onreadystatechange: function () {
802     if (this._xhr.readyState == 4) {
803     if (this.succeeded ()) {
804     this._onsuccess ();
805     } else {
806     this._onerror ();
807     }
808     }
809     }, // _onreadystatechange
810    
811     succeeded: function () {
812     return (this._xhr.status < 400);
813     }, // succeeded
814    
815     getDocument: function () {
816     return this._xhr.responseXML;
817     } // getDocument
818     }); // XHR
819    
820 wakaba 1.22 // An abstract class
821     JSTE.Storage = new JSTE.Class (function () {
822    
823     }, {
824 wakaba 1.23 get: function (name) {
825     throw "not implemented";
826     }, // get
827 wakaba 1.25 getJSON: function (name) {
828     var value = this.get (name);
829     if (value != null) {
830     return JSTE.JSON.parse (value); // XXX: try-catch?
831     } else {
832     return value;
833     }
834     }, // getJSON
835    
836 wakaba 1.23 set: function (name, value) {
837     throw "not implemented";
838     }, // set
839 wakaba 1.25 setJSON: function (name, obj) {
840     this.set (name, JSTE.JSON.stringify (obj));
841     }, // setJSON
842    
843     has: function (name) {
844     return this.get (name) !== undefined;
845     }, // has
846    
847 wakaba 1.32 del: function (name) {
848     throw "del not implemented";
849     }, // del
850 wakaba 1.25
851     flushGet: function (name) {
852     var v = this.get ('flush-' + name);
853     if (v !== undefined) {
854 wakaba 1.32 this.del ('flush-' + name);
855 wakaba 1.25 }
856     return v;
857     }, // flushGet
858     flushSet: function (name, value) {
859     this.set ('flush-' + name, value);
860     }, // flushSet
861 wakaba 1.23
862     getNames: function () {
863     throw "not implemented";
864 wakaba 1.24 }, // getNames
865    
866     setPrefix: function (newPrefix) {
867     throw "not implemented";
868     } // setPrefix
869 wakaba 1.22 }); // Storage
870    
871     JSTE.Storage.PageLocal = new JSTE.Subclass (function () {
872 wakaba 1.24 this.keyPrefix = '';
873 wakaba 1.22 }, JSTE.Storage, {
874     get: function (name) {
875 wakaba 1.24 return this['value-' + this.keyPrefix + name];
876 wakaba 1.22 }, // get
877     set: function (name, value) {
878 wakaba 1.24 this['value-' + this.keyPrefix + name] = value;
879 wakaba 1.22 }, // set
880    
881     getNames: function () {
882     var names = new JSTE.List;
883     for (var n in this) {
884 wakaba 1.24 if (n.substring (0, 6 + this.keyPrefix.length) == 'value-' + this.keyPrefix) {
885     names.push (n.substring (6 + this.keyPrefix.length));
886 wakaba 1.22 }
887     }
888     return names;
889 wakaba 1.24 }, // getNames
890    
891     setPrefix: function (newPrefix) {
892     this.keyPrefix = newPrefix;
893     } // setPrefix
894 wakaba 1.23 }); // PageLocal
895    
896     JSTE.Storage.Cookie = JSTE.Subclass (function () {
897     this.keyPrefix = '';
898     this.domain = null;
899     this.path = '/';
900     this.persistent = false;
901     this.expires = null; // or Date
902     }, JSTE.Storage, {
903     _parse: function () {
904     return new JSTE.List (document.cookie.split (/;/)).mapToHash (function (nv) {
905     nv = nv.replace (/^\s+/, '').replace (/\s+$/, '').split (/=/, 2);
906     nv[0] = decodeURIComponent (nv[0]);
907     nv[1] = decodeURIComponent (nv[1]);
908     return nv;
909     });
910     }, // _parse
911    
912     get: function (name) {
913     return this._parse ().getNamedItem (this.keyPrefix + name);
914     }, // get
915     set: function (name, value) {
916     name = this.keyPrefix + name;
917     var r = encodeURIComponent (name) + '=' + encodeURIComponent (value);
918     if (this.domain) {
919     r += '; domain=' + this.domain;
920     }
921     if (this.path) {
922     r += '; path=' + this.path;
923     }
924     if (this.persistent) {
925     r += '; expires=' + new Date (2030, 1-1, 1).toUTCString ();
926     } else if (this.expires) {
927     r += '; expires=' + this.expires.toUTCString ();
928     }
929     document.cookie = r;
930     }, // set
931 wakaba 1.32 del: function (name) {
932 wakaba 1.23 var expires = this.expires;
933     var persistent = this.persistent;
934     this.expires = new Date (0);
935     this.persistent = false;
936     this.set (name, '');
937     this.expires = expires;
938     this.persistent = persistent;
939 wakaba 1.32 }, // del
940 wakaba 1.23
941     getNames: function () {
942     var self = this;
943     return this._parse ().getNames ().grep (function (name) {
944     return name.substring (0, self.keyPrefix.length) == self.keyPrefix;
945     }).map (function (name) {
946     return name.substring (self.keyPrefix.length);
947     });
948 wakaba 1.24 }, // getNames
949    
950     setPrefix: function (newPrefix) {
951     this.keyPrefix = newPrefix;
952     } // setPrefix
953 wakaba 1.23 }); // Cookie
954    
955     JSTE.Storage.Local = JSTE.Class (function () {
956     var self = new JSTE.Storage.Cookie;
957     self.keyPrefix = 'localStorage-';
958     self.persistent = true;
959 wakaba 1.24 self.setPrefix = function (newPrefix) {
960     this.keyPrefix = 'localStorage-' + newPrefix;
961     }; // setPrefix
962 wakaba 1.23 return self;
963     }); // Local
964 wakaba 1.22
965 wakaba 1.25 JSTE.JSON = {};
966    
967     JSTE.Class.addClassMethods (JSTE.JSON, {
968     parse: function (value) {
969     if (self.JSON && JSON.parse) {
970     return JSON.parse (value); // json2.js or ES3.1
971     } else {
972     return eval ('(' + value + ')');
973     }
974     }, // parse
975    
976     stringify: function (obj) {
977     if (self.JSON && JSON.stringify) {
978     return JSON.stringify (obj); // json2.js or ES3.1
979     } else {
980     throw "JSTE.JSON.stringify not implemented";
981     }
982     } // serialize
983     }); // JSON class methods
984    
985    
986 wakaba 1.9
987 wakaba 1.1 /* Events: load, close, shown, hidden */
988 wakaba 1.18 JSTE.Message = new JSTE.Class (function (doc, template, commandTarget, availCommands) {
989 wakaba 1.1 if (!doc) return;
990     this._targetDocument = doc;
991     this._template = template || doc.createDocumentFragment ();
992 wakaba 1.8
993 wakaba 1.1 this._commandTarget = commandTarget;
994 wakaba 1.18 this._availCommands = availCommands || new JSTE.List;
995 wakaba 1.8
996 wakaba 1.1 this.hidden = true;
997     this.select = "";
998    
999     var e = new JSTE.Event ('load');
1000     this.dispatchEvent (e);
1001     }, {
1002     render: function () {
1003     var self = this;
1004     var doc = this._targetDocument;
1005    
1006     var msgContainer = doc.createElement ('section');
1007     msgContainer.appendChild (this._template);
1008 wakaba 1.20
1009     if (!this._availCommands.list.length) {
1010 wakaba 1.8 this._availCommands.push ({name: 'back'});
1011     this._availCommands.push ({name: 'next'});
1012 wakaba 1.7 }
1013 wakaba 1.20
1014 wakaba 1.30 this._availCommands = this._availCommands.grep (function (item) {
1015 wakaba 1.20 return self._commandTarget.canExecuteCommand (item.name, item.args);
1016     });
1017 wakaba 1.1
1018 wakaba 1.8 this._outermostElement = this._render (msgContainer);
1019 wakaba 1.1
1020     this.show ();
1021     }, // render
1022     _render: function (msgContainer, buttonContainer) {
1023     var doc = this._targetDocument;
1024    
1025     var container = doc.createElement ('article');
1026    
1027     container.appendChild (msgContainer);
1028 wakaba 1.8
1029     var buttonContainer = this.createCommandButtons ();
1030 wakaba 1.1 container.appendChild (buttonContainer);
1031 wakaba 1.8
1032 wakaba 1.1 doc.documentElement.appendChild (container);
1033    
1034     return container;
1035     }, // _render
1036 wakaba 1.8 createCommandButtons: function () {
1037     var self = this;
1038 wakaba 1.18 var doc = this._targetDocument;
1039     var buttonContainer = doc.createElement ('menu');
1040 wakaba 1.8 this._availCommands.forEach (function (cmd) {
1041 wakaba 1.18 var label = cmd.name;
1042     if (cmd.labelTemplate) {
1043     label = JSTE.Element.createTemplate (doc, cmd.labelTemplate);
1044     }
1045    
1046 wakaba 1.8 var button = new JSTE.Message.Button
1047 wakaba 1.26 (label, self._commandTarget, cmd.name, cmd.args, cmd.actions);
1048 wakaba 1.8 buttonContainer.appendChild (button.element);
1049 wakaba 1.27
1050     if (cmd.name == 'url') {
1051     JSTE.Prefetch.URL (cmd.args.url);
1052     }
1053 wakaba 1.8 });
1054     return buttonContainer;
1055     }, // createCommandButtons
1056    
1057 wakaba 1.1 remove: function () {
1058     this.hide ();
1059    
1060     this._remove ();
1061    
1062     if (this._outermostElement && this._outermostElement.parentNode) {
1063     this._outermostElement.parentNode.removeChild (this._outermostElement);
1064     }
1065    
1066     var e = new JSTE.Event ("close");
1067     this.dispatchEvent (e);
1068     }, // remove
1069     _remove: function () {
1070    
1071     }, // remove
1072    
1073     show: function () {
1074     if (!this.hidden) return;
1075     this.hidden = false;
1076     if (this._outermostElement) {
1077     JSTE.Element.replaceClassName
1078     (this._outermostElement, "jste-hidden", "jste-shown");
1079     }
1080    
1081     var e = new JSTE.Event ("shown");
1082     this.dispatchEvent (e);
1083     }, // show
1084     hide: function () {
1085     if (this.hidden) return;
1086     this.hidden = true;
1087     if (this._outermostElement) {
1088     JSTE.Element.replaceClassName
1089     (this._outermostElement, "jste-shown", "jste-hidden");
1090     }
1091    
1092     var e = new JSTE.Event ("hidden");
1093     this.dispatchEvent (e);
1094     }, // hide
1095    
1096     setTimeout: function () {
1097     /* TODO: ... */
1098    
1099     }
1100    
1101     }); // Message
1102    
1103 wakaba 1.7 /* TODO: button label text should refer message catalog */
1104    
1105 wakaba 1.1 JSTE.Message.Button =
1106 wakaba 1.26 new JSTE.Class (function (label, commandTarget, commandName, commandArgs, commandActions) {
1107 wakaba 1.18 this._label = label != null ? label : "";
1108 wakaba 1.6
1109 wakaba 1.1 if (commandTarget && commandTarget instanceof Function) {
1110     this._command = commandTarget;
1111 wakaba 1.6 this._classNames = new JSTE.List;
1112 wakaba 1.1 } else if (commandTarget) {
1113     this._command = function () {
1114     return commandTarget.executeCommand.apply
1115 wakaba 1.26 (commandTarget, [commandName, commandArgs, commandActions]);
1116 wakaba 1.1 };
1117 wakaba 1.6 this._classNames = new JSTE.List (['jste-command-' + commandName]);
1118 wakaba 1.1 } else {
1119     this._command = function () { };
1120 wakaba 1.6 this._classNames = new JSTE.List;
1121 wakaba 1.1 }
1122    
1123 wakaba 1.6 this._createElement ();
1124 wakaba 1.1 }, {
1125 wakaba 1.6 _createElement: function () {
1126     try {
1127     this.element = document.createElement ('button');
1128     this.element.setAttribute ('type', 'button');
1129     } catch (e) {
1130     this.element = document.createElement ('<button type=button>');
1131     }
1132 wakaba 1.18 if (this._label.nodeType) {
1133     this.element.appendChild (this._label);
1134     } else {
1135     JSTE.Element.appendText (this.element, this._label);
1136     }
1137 wakaba 1.6 this.element.className = this._classNames.list.join (' ');
1138 wakaba 1.1
1139 wakaba 1.6 var self = this;
1140     new JSTE.Observer ("click", this.element, function (e) {
1141     self._command (e);
1142     });
1143     } // _createElement
1144 wakaba 1.1 }); // Button
1145    
1146     JSTE.Course = new JSTE.Class (function (doc) {
1147     this._targetDocument = doc;
1148    
1149 wakaba 1.29 this._entryPoints = new JSTE.List;
1150     this._entryPoints.push
1151     ({conditions: new JSTE.List ([{type: 'state', value: 'done'}]),
1152     stepUid: 'special-none'});
1153 wakaba 1.1
1154     this._stepsState = new JSTE.List ([new JSTE.Hash]);
1155     this._steps = new JSTE.Hash;
1156    
1157     var nullState = new JSTE.Step;
1158 wakaba 1.29 nullState.uid = "special-none";
1159 wakaba 1.1 this._steps.setNamedItem (nullState.uid, nullState);
1160     this._initialStepUid = nullState.uid;
1161     }, {
1162 wakaba 1.10 _processStepsContent: function (el, parentSteps) {
1163 wakaba 1.1 var self = this;
1164     new JSTE.List (el.childNodes).switchByElementType (
1165     new JSTE.List.SwitchByLocalName (JSTE.WATNS, {
1166 wakaba 1.10 steps: function (n) { self._processStepsElement (n, parentSteps) },
1167     step: function (n) { self._processStepElement (n, parentSteps) },
1168     jump: function (n) { self._processJumpElement (n, parentSteps) },
1169 wakaba 1.29 'entry-point': function (n) { self._processEntryPointElement (n, parentSteps) }
1170 wakaba 1.1 })
1171     );
1172     }, // _processStepsContent
1173 wakaba 1.10 _processStepsElement: function (e, parentSteps) {
1174     var steps = new JSTE.Steps ();
1175     steps.parentSteps = parentSteps;
1176 wakaba 1.1 this._stepsState.pushCloneOfLast ();
1177     this._stepsState.getLast ().prevStep = null;
1178 wakaba 1.29
1179     this._addConditionsFromElement (e, steps.conditions);
1180 wakaba 1.10 this._processStepsContent (e, steps);
1181 wakaba 1.29
1182 wakaba 1.1 this._stepsState.pop ();
1183     }, // _processStepsElement
1184    
1185 wakaba 1.14 _processEntryPointElement: function (e, parentSteps) {
1186 wakaba 1.29 var conds = parentSteps ? parentSteps.conditions.clone () : new JSTE.List;
1187     this._addConditionsFromElement (e, conds);
1188    
1189     var stepUid = e.getAttribute ('step');
1190     if (stepUid != null) stepUid = 'id-' + stepUid;
1191     this._entryPoints.push ({conditions: conds, stepUid: stepUid});
1192 wakaba 1.14 }, // _processEntryPointElement
1193 wakaba 1.22
1194 wakaba 1.29 _addConditionsFromElement: function (e, conds) {
1195     var urls = e.getAttribute ('document-url');
1196     if (urls != null) {
1197     JSTE.List.spaceSeparated (urls).forEach (function (url) {
1198     conds.push ({type: 'url', value: encodeURI (url)});
1199     // TODO: resolve relative URL, URL->URI
1200     });
1201 wakaba 1.22 }
1202 wakaba 1.29
1203     var urls = e.getAttribute ('not-document-url');
1204     if (urls != null) {
1205     JSTE.List.spaceSeparated (urls).forEach (function (url) {
1206     conds.push ({type: 'url', value: encodeURI (url), not: true});
1207     // TODO: resolve relative URL
1208     });
1209 wakaba 1.1 }
1210 wakaba 1.29
1211     var classNames = e.getAttribute ('document-class');
1212     if (classNames != null) {
1213     JSTE.List.spaceSeparated (classNames).forEach (function (className) {
1214     conds.push ({type: 'class', value: className});
1215 wakaba 1.1 });
1216 wakaba 1.29 }
1217    
1218     var classNames = e.getAttribute ('not-document-class');
1219     if (classNames != null) {
1220     JSTE.List.spaceSeparated (classNames).forEach (function (className) {
1221     conds.push ({type: 'class', value: className, not: true});
1222 wakaba 1.1 });
1223     }
1224 wakaba 1.29
1225     var stateNames = e.getAttribute ('state');
1226     if (stateNames != null) {
1227     JSTE.List.spaceSeparated (stateNames).forEach (function (stateName) {
1228     conds.push ({type: 'state', value: stateName});
1229 wakaba 1.1 });
1230 wakaba 1.29 }
1231    
1232     var stateNames = e.getAttribute ('not-state');
1233     if (stateNames != null) {
1234     JSTE.List.spaceSeparated (stateNames).forEach (function (stateName) {
1235     conds.push ({type: 'state', value: stateName, not: true});
1236 wakaba 1.1 });
1237     }
1238 wakaba 1.29 }, // _addConditionsFromElement
1239    
1240     findEntryPoint: function (doc, states) {
1241     var self = this;
1242    
1243     var td = this._targetDocument;
1244     var docURL = td.URL; // TODO: drop fragments?
1245     var docClassNames = JSTE.Document.getClassNames (td);
1246    
1247     var stepUid = this._entryPoints.forEach (function (ep) {
1248     if (ep.conditions.forEach (function (cond) {
1249     var matched;
1250     if (cond.type == 'state') {
1251     matched = states.has (cond.value);
1252     } else if (cond.type == 'class') {
1253     matched = docClassNames.has (cond.value);
1254     } else if (cond.type == 'url') {
1255 wakaba 1.32 matched = JSTE.URL.eq (cond.value, docURL);
1256 wakaba 1.29 } else {
1257     //
1258     }
1259     if (cond.not) matched = !matched;
1260     if (!matched) return new JSTE.List.Return (true);
1261     })) return; // true = not matched
1262    
1263     // matched
1264     return new JSTE.List.Return (ep.stepUid);
1265     });
1266    
1267     // TODO: multiple elements with same ID
1268    
1269     if (stepUid != null) {
1270     return stepUid;
1271     } else {
1272     return this._initialStepUid;
1273     }
1274 wakaba 1.1 }, // findEntryPoint
1275    
1276 wakaba 1.10 _processStepElement: function (e, parentSteps) {
1277 wakaba 1.18 var self = this;
1278    
1279 wakaba 1.1 var step = new JSTE.Step (e.getAttribute ('id'));
1280 wakaba 1.10 step.parentSteps = parentSteps;
1281 wakaba 1.1 step.setPreviousStep (this._stepsState.getLast ().prevStep);
1282     step.select = e.getAttribute ('select') || "";
1283     step.nextEvents.append
1284 wakaba 1.10 (JSTE.List.spaceSeparated (e.getAttribute ('next-event')));
1285 wakaba 1.17
1286 wakaba 1.28 step.noHistory = JSTE.Element.hasAttribute (e, 'nohistory');
1287    
1288 wakaba 1.17 var cs = JSTE.Element.getChildrenClassifiedByType (e);
1289    
1290     var msgEl = cs.get (JSTE.WATNS, 'message').list[0];
1291 wakaba 1.1 if (msgEl) {
1292     var msg = JSTE.Element.createTemplate (this._targetDocument, msgEl);
1293     step.setMessageTemplate (msg);
1294     }
1295 wakaba 1.17
1296     var nextEls = cs.get (JSTE.WATNS, 'next-step');
1297 wakaba 1.16 if (nextEls.list.length) {
1298 wakaba 1.1 nextEls.forEach (function (nextEl) {
1299     step.addNextStep
1300     (nextEl.getAttribute ('if'), nextEl.getAttribute ('step'));
1301     });
1302     this._stepsState.getLast ().prevStep = null;
1303     } else {
1304     this._stepsState.getLast ().prevStep = step;
1305     }
1306 wakaba 1.17
1307 wakaba 1.19 cs.get (JSTE.WATNS, 'command').forEach (function (bEl) {
1308 wakaba 1.18 var cmd = {
1309 wakaba 1.20 name: bEl.getAttribute ('type') || 'gotoStep'
1310 wakaba 1.18 };
1311     if (cmd.name == 'gotoStep') {
1312 wakaba 1.25 cmd.args = {stepUid: 'id-' + bEl.getAttribute ('step')};
1313 wakaba 1.24 } else if (cmd.name == 'url') {
1314 wakaba 1.27 // TODO: relative URL
1315 wakaba 1.26 cmd.args = {url: bEl.getAttribute ('href')};
1316 wakaba 1.18 }
1317 wakaba 1.26 cmd.actions = {
1318 wakaba 1.28 saveStateNames: JSTE.List.spaceSeparated (bEl.getAttribute ('save-state')),
1319 wakaba 1.26 clearStateNames: JSTE.List.spaceSeparated (bEl.getAttribute ('clear-state'))
1320     };
1321 wakaba 1.18 if (!JSTE.Element.isEmpty (bEl)) {
1322     cmd.labelTemplate = JSTE.Element.createTemplate (self._targetDocument, bEl);
1323     }
1324     step.availCommands.push (cmd);
1325 wakaba 1.22 }); // wat:command
1326 wakaba 1.18
1327 wakaba 1.22 cs.get (JSTE.WATNS, 'save-state').forEach (function (bEl) {
1328     var ss = new JSTE.SaveState
1329     (bEl.getAttribute ('name'), bEl.getAttribute ('value'));
1330     step.saveStates.push (ss);
1331     }); // wat:save-state
1332 wakaba 1.13
1333     var evs = JSTE.List.spaceSeparated (e.getAttribute ('entry-event'));
1334     if (evs.list.length) {
1335     var jump = new JSTE.Jump (step.select, evs, step.uid);
1336     if (parentSteps) parentSteps._jumps.push (jump);
1337     }
1338 wakaba 1.1
1339     this._steps.setNamedItem (step.uid, step);
1340 wakaba 1.29 /*if (!this._initialStepUid) {
1341 wakaba 1.1 this._initialStepUid = step.uid;
1342 wakaba 1.29 }*/
1343 wakaba 1.1 }, // _processStepElement
1344    
1345 wakaba 1.10 _processJumpElement: function (e, parentSteps) {
1346     var target = e.getAttribute ('target') || '';
1347     var evs = JSTE.List.spaceSeparated (e.getAttribute ('event'));
1348     var stepName = e.getAttribute ('step') || '';
1349    
1350     var jump = new JSTE.Jump (target, evs, 'id-' + stepName);
1351     if (parentSteps) parentSteps._jumps.push (jump);
1352 wakaba 1.1 }, // _processJumpElement
1353    
1354     getStep: function (uid) {
1355     return this._steps.getNamedItem (uid);
1356     } // getStep
1357     }); // Course
1358    
1359 wakaba 1.9 JSTE.Class.addClassMethods (JSTE.Course, {
1360     createFromDocument: function (doc, targetDoc) {
1361     var course = new JSTE.Course (targetDoc);
1362     var docEl = doc.documentElement;
1363     if (!docEl) return course;
1364     if (!JSTE.Element.match (docEl, JSTE.WATNS, 'course')) return course;
1365 wakaba 1.10 course._processStepsContent (docEl, null);
1366 wakaba 1.32 var name = docEl.getAttribute ('name');
1367     if (name != null) {
1368     course.name = name + '-';
1369     } else {
1370     course.name = '';
1371     }
1372 wakaba 1.9 return course;
1373     }, // createFromDocument
1374     createFromURL: function (url, targetDoc, onload, onerror) {
1375     new JSTE.XHR (url, function () {
1376     var course = JSTE.Course.createFromDocument
1377     (this.getDocument (), targetDoc);
1378     if (onload) onload (course);
1379     }, onerror).get ();
1380     } // creatFromURL
1381     }); // Course class methods
1382 wakaba 1.1
1383 wakaba 1.10 JSTE.Jump = new JSTE.Class (function (selectors, eventNames, stepUid) {
1384     this.selectors = selectors;
1385     this.eventNames = eventNames;
1386     this.stepUid = stepUid;
1387     // this.parentSteps
1388     }, {
1389     startObserver: function (doc, commandTarget) {
1390     var self = this;
1391     var observers = new JSTE.List;
1392    
1393     var onev = function () {
1394 wakaba 1.25 commandTarget.gotoStep ({stepUid: self.stepUid});
1395 wakaba 1.10 };
1396    
1397     JSTE.Node.querySelectorAll (doc, this.selectors).forEach
1398     (function (el) {
1399     self.eventNames.forEach (function (evName) {
1400     var ob = new JSTE.Observer (evName, el, onev);
1401     ob._stepUid = self.stepUid;
1402     observers.push (ob);
1403     });
1404     });
1405    
1406     return observers;
1407     } // startObserver
1408     }); // Jump
1409    
1410     JSTE.Steps = new JSTE.Class (function () {
1411     this._jumps = new JSTE.List;
1412     this._jumpHandlers = new JSTE.List;
1413 wakaba 1.29 this.conditions = new JSTE.List;
1414 wakaba 1.10 }, {
1415     setCurrentStepByUid: function (uid) {
1416     this._jumpHandlers.forEach (function (jh) {
1417     if (jh._stepUid != uid && jh.disabled) {
1418     jh.start ();
1419     } else if (jh._stepUid == uid && !jh.disabled) {
1420     jh.stop ();
1421     }
1422     });
1423     }, // setCurrentStepByUid
1424    
1425     installJumps: function (doc, commandTarget) {
1426     if (this._jumpHandlers.list.length) return;
1427     var self = this;
1428     this._jumps.forEach (function (j) {
1429     self._jumpHandlers.append (j.startObserver (doc, commandTarget));
1430     });
1431     }, // installJumps
1432    
1433     uninstallJumps: function () {
1434     this._jumpHandlers.forEach (function (jh) {
1435     jh.stop ();
1436     });
1437     this._jumpHandlers.clear ();
1438     } // uninstallJumps
1439     }); // Steps
1440    
1441 wakaba 1.1 JSTE.Step = new JSTE.Class (function (id) {
1442     if (id != null && id != '') {
1443     this.uid = 'id-' + id;
1444     } else {
1445     this.uid = 'rand-' + Math.random ();
1446     }
1447     this._nextSteps = new JSTE.List;
1448     this.nextEvents = new JSTE.List;
1449 wakaba 1.18 this.availCommands = new JSTE.List;
1450 wakaba 1.22 this.saveStates = new JSTE.List;
1451 wakaba 1.1 this.select = "";
1452 wakaba 1.30 // this._messageTemplate
1453 wakaba 1.1 }, {
1454     setMessageTemplate: function (msg) {
1455     this._messageTemplate = msg;
1456     }, // setMessageTemplate
1457     hasMessage: function () {
1458     return this._messageTemplate ? true : false;
1459     }, // hasMessage
1460     createMessage: function (msg, doc, commandTarget) {
1461     var msg;
1462     if (this._messageTemplate) {
1463     var clone = JSTE.Element.createTemplate (doc, this._messageTemplate);
1464 wakaba 1.18 msg = new msg (doc, clone, commandTarget, this.availCommands.clone ());
1465 wakaba 1.1 } else {
1466 wakaba 1.30 msg = new msg (doc, null, commandTarget, this.availCommands.clone ());
1467 wakaba 1.1 }
1468     msg.select = this.select;
1469     return msg;
1470     }, // createMessage
1471    
1472     addNextStep: function (condition, stepId) {
1473 wakaba 1.16 if (stepId != null) this._nextSteps.push ([condition, stepId]);
1474 wakaba 1.1 }, // addNextStep
1475     setPreviousStep: function (prevStep) {
1476     if (!prevStep) return;
1477     if (prevStep._defaultNextStepUid) return;
1478     prevStep._defaultNextStepUid = this.uid;
1479     }, // setPreviousStep
1480    
1481     getNextStepUid: function (doc) {
1482     var m = this._nextSteps.getFirstMatch (function (item) {
1483     var condition = item[0];
1484     if (condition) {
1485     return JSTE.Node.querySelector (doc, condition) != null;
1486     } else {
1487     return true;
1488     }
1489     });
1490     if (m) {
1491     return 'id-' + m[1];
1492     } else if (this._defaultNextStepUid) {
1493     return this._defaultNextStepUid;
1494     } else {
1495     return null;
1496     }
1497 wakaba 1.10 }, // getNextStepUid
1498    
1499     getAncestorStepsObjects: function () {
1500     var steps = new JSTE.List;
1501     var s = this.parentSteps;
1502     while (s != null) {
1503     steps.push (s);
1504     s = s.parentSteps;
1505     }
1506     return steps;
1507     } // getAncestorStepsObjects
1508 wakaba 1.1 }); // Step
1509    
1510 wakaba 1.22 JSTE.SaveState = new JSTE.Class (function (name, value) {
1511     this.name = name || '';
1512     this.value = value || '';
1513     }, {
1514 wakaba 1.25 save: function (tutorial) {
1515     var name = this.name;
1516     var value = this.value;
1517     if (name == 'back-state') return;
1518     tutorial._states.set (name, value);
1519 wakaba 1.22 } // save
1520     }); // SaveState
1521    
1522     /* Events: load, error, cssomready, close */
1523 wakaba 1.9 JSTE.Tutorial = new JSTE.Class (function (course, doc, args) {
1524 wakaba 1.1 this._course = course;
1525     this._targetDocument = doc;
1526     this._messageClass = JSTE.Message;
1527     if (args) {
1528     if (args.messageClass) this._messageClass = args.messageClass;
1529 wakaba 1.22 if (args.states) this._states = args.states;
1530 wakaba 1.1 }
1531 wakaba 1.22 if (!this._states) this._states = new JSTE.Storage.PageLocal;
1532 wakaba 1.24 this._states.setPrefix (course.name);
1533 wakaba 1.1
1534     this._currentMessages = new JSTE.List;
1535     this._currentObservers = new JSTE.List;
1536 wakaba 1.25 this._currentStepsObjects = new JSTE.List;
1537    
1538 wakaba 1.1 this._prevStepUids = new JSTE.List;
1539 wakaba 1.25 this._loadBackState ();
1540    
1541     var stepUid;
1542 wakaba 1.29 if (this._states.flushGet ('is-back') && this._prevStepUids.list.length) {
1543 wakaba 1.25 stepUid = this._prevStepUids.pop ();
1544     } else {
1545     stepUid = this._course.findEntryPoint (document, this._states);
1546     }
1547    
1548 wakaba 1.1 this._currentStep = this._getStepOrError (stepUid);
1549     if (this._currentStep) {
1550     var e = new JSTE.Event ('load');
1551     this.dispatchEvent (e);
1552 wakaba 1.25
1553     this._saveBackState ();
1554    
1555 wakaba 1.3 var self = this;
1556     new JSTE.Observer ('cssomready', this, function () {
1557     self._renderCurrentStep ();
1558     });
1559     this._dispatchCSSOMReadyEvent ();
1560 wakaba 1.1 return this;
1561     } else {
1562     return {};
1563     }
1564     }, {
1565     _getStepOrError: function (stepUid) {
1566 wakaba 1.29 if (stepUid == 'special-none') {
1567     return null;
1568     }
1569    
1570 wakaba 1.1 var step = this._course.getStep (stepUid);
1571     if (step) {
1572     return step;
1573     } else {
1574     var e = new JSTE.Event ('error');
1575     e.errorMessage = 'Step not found';
1576     e.errorArguments = [this._currentStepUid];
1577     this.dispatchEvent (e);
1578     return null;
1579     }
1580     }, // _getStepOrError
1581    
1582     _renderCurrentStep: function () {
1583     var self = this;
1584     var step = this._currentStep;
1585 wakaba 1.22
1586 wakaba 1.25 step.saveStates.forEach (function (ss) { ss.save (self) });
1587 wakaba 1.1
1588     /* Message */
1589     var msg = step.createMessage
1590     (this._messageClass, this._targetDocument, this);
1591     msg.render ();
1592     this._currentMessages.push (msg);
1593    
1594     /* Next-events */
1595     var selectedNodes = JSTE.Node.querySelectorAll
1596     (this._targetDocument, step.select);
1597     var handler = function () {
1598     self.executeCommand ("next");
1599     };
1600     selectedNodes.forEach (function (node) {
1601     step.nextEvents.forEach (function (eventType) {
1602     self._currentObservers.push
1603     (new JSTE.Observer (eventType, node, handler));
1604     });
1605     });
1606 wakaba 1.10
1607     JSTE.List.getCommonItems (this._currentStepsObjects,
1608     step.getAncestorStepsObjects (),
1609     function (common, onlyInOld, onlyInNew) {
1610     common.forEach (function (item) {
1611     item.setCurrentStepByUid (step.uid);
1612     });
1613     onlyInOld.forEach (function (item) {
1614     item.uninstallJumps ();
1615     });
1616     onlyInNew.forEach (function (item) {
1617     item.installJumps (self._targetDocument, self);
1618     });
1619     self._currentStepsObjects = common.append (onlyInNew);
1620     });
1621 wakaba 1.1 }, // _renderCurrentStep
1622     clearMessages: function () {
1623     this._currentMessages.forEach (function (msg) {
1624     msg.remove ();
1625     });
1626     this._currentMessages.clear ();
1627    
1628     this._currentObservers.forEach (function (ob) {
1629     ob.stop ();
1630     });
1631     this._currentObservers.clear ();
1632     }, // clearMessages
1633 wakaba 1.10 clearStepsHandlers: function () {
1634     this._currentStepsObjects.forEach (function (item) {
1635     item.uninstallJumps ();
1636     });
1637     this._currentStepsObjects.clear ();
1638     }, // clearStepsHandlers
1639 wakaba 1.1
1640 wakaba 1.26 executeCommand: function (commandName, commandArgs, commandActions) {
1641 wakaba 1.1 if (this[commandName]) {
1642 wakaba 1.26 // Common actions
1643 wakaba 1.28 if (commandActions) {
1644 wakaba 1.26 var self = this;
1645 wakaba 1.28 if (commandActions.saveStateNames) {
1646     commandActions.saveStateNames.forEach (function (stateName) {
1647     self._states.set (stateName, '');
1648     });
1649     }
1650     if (commandActions.clearStateNames) {
1651     commandActions.clearStateNames.forEach (function (stateName) {
1652 wakaba 1.29 if (stateName == 'back-state') {
1653     self._prevStateUids = new JSTE.List;
1654     self._prevPages = new JSTE.List;
1655     }
1656 wakaba 1.32 self._states.del (stateName);
1657 wakaba 1.28 });
1658     }
1659 wakaba 1.26 }
1660    
1661 wakaba 1.25 return this[commandName].apply (this, [commandArgs || {}]);
1662 wakaba 1.1 } else {
1663     var e = new JSTE.Event ('error');
1664     e.errorMessage = 'Command not found';
1665     e.errorArguments = [commandName];
1666     return null;
1667     }
1668     }, // executeCommand
1669 wakaba 1.7 canExecuteCommand: function (commandName, commandArgs) {
1670     if (this[commandName]) {
1671     var can = this['can' + commandName.substring (0, 1).toUpperCase ()
1672     + commandName.substring (1)];
1673     if (can) {
1674     return can.apply (this, arguments);
1675     } else {
1676     return true;
1677     }
1678     } else {
1679     return false;
1680     }
1681     }, // canExecuteCommand
1682 wakaba 1.1
1683     back: function () {
1684 wakaba 1.25 while (this._prevStepUids.list.length == 0 &&
1685     this._prevPages.list.length > 0) {
1686     var prevPage = this._prevPages.pop ();
1687 wakaba 1.32 if (!JSTE.URL.eq (prevPage.url, location.href)) { // TODO: fragment?
1688 wakaba 1.25 this._saveBackState (true);
1689 wakaba 1.29 this._states.flushSet ('is-back', true);
1690 wakaba 1.32 if (JSTE.URL.eq (document.referrer, prevPage.url)) { // TODO: fragment?
1691 wakaba 1.26 history.back ();
1692     } else {
1693     location.href = prevPage.url;
1694     }
1695 wakaba 1.25 // TODO: maybe we should not return if locaton.href and prevPage.,url only differs their fragment ids?
1696     return;
1697     }
1698     this._prevStepUids = prevPage;
1699     }
1700    
1701 wakaba 1.1 var prevStepUid = this._prevStepUids.pop ();
1702     var prevStep = this._getStepOrError (prevStepUid);
1703     if (prevStep) {
1704     this.clearMessages ();
1705 wakaba 1.25 this._saveBackState ();
1706 wakaba 1.1 this._currentStep = prevStep;
1707     this._renderCurrentStep ();
1708     }
1709     }, // back
1710 wakaba 1.7 canBack: function () {
1711 wakaba 1.25 return this._prevStepUids.list.length > 0 || this._prevPages.list.length > 0;
1712 wakaba 1.7 }, // canBack
1713 wakaba 1.1 next: function () {
1714     var nextStepUid = this._currentStep.getNextStepUid (this._targetDocument);
1715     var nextStep = this._getStepOrError (nextStepUid);
1716     if (nextStep) {
1717 wakaba 1.28 if (!this._currentStep.noHistory) {
1718     this._prevStepUids.push (this._currentStep.uid);
1719     }
1720 wakaba 1.1 this.clearMessages ();
1721 wakaba 1.25 this._saveBackState ();
1722 wakaba 1.1 this._currentStep = nextStep;
1723     this._renderCurrentStep ();
1724     }
1725 wakaba 1.3 }, // next
1726 wakaba 1.7 canNext: function () {
1727     return this._currentStep.getNextStepUid (this._targetDocument) != null;
1728     }, // canNext
1729 wakaba 1.25 gotoStep: function (args) {
1730     var nextStep = this._getStepOrError (args.stepUid);
1731 wakaba 1.10 if (nextStep) {
1732 wakaba 1.28 if (!this._currentStep.noHistory) {
1733     this._prevStepUids.push (this._currentStep.uid);
1734     }
1735 wakaba 1.25 this._saveBackState ();
1736 wakaba 1.10 this.clearMessages ();
1737     this._currentStep = nextStep;
1738     this._renderCurrentStep ();
1739     }
1740     }, // gotoStep
1741 wakaba 1.24
1742 wakaba 1.25 url: function (args) {
1743     location.href = args.url;
1744 wakaba 1.24 }, // url
1745 wakaba 1.20
1746     close: function () {
1747     this.clearMessages ();
1748 wakaba 1.22 var e = new JSTE.Event ('closed');
1749     this.dispatchEvent (e);
1750 wakaba 1.20 }, // close
1751 wakaba 1.25
1752     _loadBackState: function () {
1753     var self = this;
1754     this._prevPages = new JSTE.List;
1755     var bs = this._states.getJSON ('back-state');
1756     new JSTE.List (bs).forEach (function (b) {
1757     var i = new JSTE.List (b.stepUids);
1758     i.url = b.url;
1759     self._prevPages.push (i);
1760     });
1761 wakaba 1.32 if (JSTE.URL.eq ((this._prevPages.getLast () || {}).url, location.href)) { // TODO: fragment?
1762 wakaba 1.25 this._prevStepUids = this._prevPages.pop ();
1763     }
1764     }, // loadBackState
1765     _saveBackState: function (ignoreCurrentPage) {
1766     var bs = [];
1767     this._prevPages.forEach (function (pp) {
1768     bs.push ({url: pp.url, stepUids: pp.list});
1769     });
1770     if (!ignoreCurrentPage) {
1771     var uids = this._prevStepUids.clone ();
1772 wakaba 1.28 if (!this._currentStep.noHistory) {
1773     uids.push (this._currentStep.uid);
1774     }
1775     if (uids.list.length) {
1776     bs.push ({url: location.href, stepUids: uids.list});
1777     }
1778 wakaba 1.25 }
1779     this._states.setJSON ('back-state', bs);
1780     }, // _saveBackState
1781 wakaba 1.3
1782     // <http://twitter.com/waka/status/1129513097>
1783     _dispatchCSSOMReadyEvent: function () {
1784     var self = this;
1785     var e = new JSTE.Event ('cssomready');
1786     if (window.opera && document.readyState != 'complete') {
1787     new JSTE.Observer ('readystatechange', document, function () {
1788     if (document.readyState == 'complete') {
1789     self.dispatchEvent (e);
1790     }
1791     });
1792     } else {
1793     this.dispatchEvent (e);
1794     }
1795     } // dispatchCSSOMReadyEvent
1796    
1797 wakaba 1.1 }); // Tutorial
1798 wakaba 1.9
1799     JSTE.Class.addClassMethods (JSTE.Tutorial, {
1800 wakaba 1.12 createFromURL: function (url, doc, args, onload) {
1801 wakaba 1.9 JSTE.Course.createFromURL (url, doc, function (course) {
1802 wakaba 1.12 var tutorial = new JSTE.Tutorial (course, doc, args);
1803     if (onload) onload (tutorial);
1804 wakaba 1.9 });
1805     } // createFromURL
1806     }); // Tutorial class methods
1807    
1808    
1809 wakaba 1.5
1810     if (JSTE.onLoadFunctions) {
1811     new JSTE.List (JSTE.onLoadFunctions).forEach (function (code) {
1812     code ();
1813     });
1814     }
1815    
1816     if (JSTE.isDynamicallyLoaded) {
1817     JSTE.windowLoaded = true;
1818     }
1819 wakaba 1.2
1820     /* ***** BEGIN LICENSE BLOCK *****
1821     * Copyright 2008-2009 Wakaba <w@suika.fam.cx>. All rights reserved.
1822     *
1823     * This program is free software; you can redistribute it and/or
1824     * modify it under the same terms as Perl itself.
1825     *
1826     * Alternatively, the contents of this file may be used
1827     * under the following terms (the "MPL/GPL/LGPL"),
1828     * in which case the provisions of the MPL/GPL/LGPL are applicable instead
1829     * of those above. If you wish to allow use of your version of this file only
1830     * under the terms of the MPL/GPL/LGPL, and not to allow others to
1831     * use your version of this file under the terms of the Perl, indicate your
1832     * decision by deleting the provisions above and replace them with the notice
1833     * and other provisions required by the MPL/GPL/LGPL. If you do not delete
1834     * the provisions above, a recipient may use your version of this file under
1835     * the terms of any one of the Perl or the MPL/GPL/LGPL.
1836     *
1837     * "MPL/GPL/LGPL":
1838     *
1839     * Version: MPL 1.1/GPL 2.0/LGPL 2.1
1840     *
1841     * The contents of this file are subject to the Mozilla Public License Version
1842     * 1.1 (the "License"); you may not use this file except in compliance with
1843     * the License. You may obtain a copy of the License at
1844     * <http://www.mozilla.org/MPL/>
1845     *
1846     * Software distributed under the License is distributed on an "AS IS" basis,
1847     * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
1848     * for the specific language governing rights and limitations under the
1849     * License.
1850     *
1851     * The Original Code is JSTE code.
1852     *
1853     * The Initial Developer of the Original Code is Wakaba.
1854     * Portions created by the Initial Developer are Copyright (C) 2008
1855     * the Initial Developer. All Rights Reserved.
1856     *
1857     * Contributor(s):
1858     * Wakaba <w@suika.fam.cx>
1859     *
1860     * Alternatively, the contents of this file may be used under the terms of
1861     * either the GNU General Public License Version 2 or later (the "GPL"), or
1862     * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
1863     * in which case the provisions of the GPL or the LGPL are applicable instead
1864     * of those above. If you wish to allow use of your version of this file only
1865     * under the terms of either the GPL or the LGPL, and not to allow others to
1866     * use your version of this file under the terms of the MPL, indicate your
1867     * decision by deleting the provisions above and replace them with the notice
1868     * and other provisions required by the LGPL or the GPL. If you do not delete
1869     * the provisions above, a recipient may use your version of this file under
1870     * the terms of any one of the MPL, the GPL or the LGPL.
1871     *
1872     * ***** END LICENSE BLOCK ***** */

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24