/[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.30 - (hide annotations) (download) (as text)
Tue Feb 3 09:36:21 2009 UTC (16 years, 6 months ago) by wakaba
Branch: MAIN
Changes since 1.29: +3 -2 lines
File MIME type: application/javascript
Enable commands even if message is missing

1 wakaba 1.1
2     if (typeof (JSTE) === "undefined") var JSTE = {};
3    
4     JSTE.WATNS = 'http://suika.fam.cx/ns/wat';
5     JSTE.SpaceChars = /[\x09\x0A\x0C\x0D\x20]+/;
6    
7     JSTE.Class = function (constructor, prototype) {
8     return JSTE.Subclass (constructor, JSTE.EventTarget, prototype);
9     }; // Class
10    
11     JSTE.Class.addClassMethods = function (classObject, methods) {
12     new JSTE.Hash (methods).forEach (function (n, v) {
13     if (!classObject[n]) {
14     classObject[n] = v;
15     }
16     });
17     }; // addClassMethods
18    
19     JSTE.Subclass = function (constructor, superclass, prototype) {
20     constructor.prototype = new superclass;
21     for (var n in prototype) {
22     constructor.prototype[n] = prototype[n];
23     }
24     constructor.prototype.constructor = constructor;
25     constructor.prototype._super = superclass;
26     return constructor;
27     }; // Subclass
28    
29     JSTE.EventTarget = new JSTE.Subclass (function () {
30    
31     }, function () {}, {
32     addEventListener: function (eventType, handler, useCapture) {
33     if (useCapture) return;
34     if (!this.eventListeners) this.eventListeners = {};
35     if (!this.eventListeners[eventType]) {
36     this.eventListeners[eventType] = new JSTE.List;
37     }
38     this.eventListeners[eventType].push (handler);
39     }, // addEventListener
40     removeEventListener: function (eventType, handler, useCapture) {
41     if (useCapture) return;
42     if (!this.eventListeners) return;
43     if (!this.eventListeners[eventType]) return;
44     this.eventListeners[eventType].remove (handler);
45     }, // removeEventListener
46     dispatchEvent: function (e) {
47     if (!this.eventListeners) return;
48     var handlers = this.eventListeners[e.type];
49     if (!handlers) return;
50     e.currentTarget = this;
51     e.target = this;
52     var preventDefault;
53     handlers.forEach (function (handler) {
54     if (handler.apply (this, [e])) {
55     preventDefault = true;
56     }
57     });
58     return preventDefault || e.isDefaultPrevented ();
59     } // dispatchEvent
60     }); // EventTarget
61    
62     JSTE.Event = new JSTE.Class (function (eventType, canBubble, cancelable) {
63     this.type = eventType;
64     this.bubbles = canBubble;
65     this.cancelable = cancelable;
66     }, {
67     preventDefault: function () {
68     this.defaultPrevented = true;
69     }, // preventDefault
70     isDefaultPrevented: function () {
71     return this.defaultPrevented;
72     } // isDefaultPrevented
73     });
74    
75     JSTE.Observer = new JSTE.Class (function (eventType, target, onevent) {
76     this.eventType = eventType;
77 wakaba 1.10 this.target = target;
78 wakaba 1.1 if (target.addEventListener) {
79     this.code = onevent;
80     } else if (target.attachEvent) {
81     this.code = function () {
82     onevent (event);
83     };
84 wakaba 1.10 } else {
85     this.code = onevent;
86 wakaba 1.1 }
87 wakaba 1.10 this.disabled = true;
88     this.start ();
89 wakaba 1.1 }, {
90 wakaba 1.10 start: function () {
91     if (!this.disabled) return;
92     if (this.target.addEventListener) {
93     this.target.addEventListener (this.eventType, this.code, false);
94     this.disabled = false;
95     } else if (this.target.attachEvent) {
96     this.target.attachEvent ("on" + this.eventType, this.code);
97     this.disabled = false;
98     }
99     }, // start
100 wakaba 1.1 stop: function () {
101 wakaba 1.10 if (this.disabled) return;
102 wakaba 1.1 if (this.target.removeEventListener) {
103     this.target.removeEventListener (this.eventType, this.code, false);
104 wakaba 1.10 this.disabled = true;
105 wakaba 1.11 } else if (this.target.detachEvent) {
106 wakaba 1.1 this.target.detachEvent ("on" + this.eventType, this.code);
107 wakaba 1.10 this.disabled = true;
108 wakaba 1.1 }
109     } // stop
110     }); // Observer
111    
112 wakaba 1.5 new JSTE.Observer ('load', window, function () {
113     JSTE.windowLoaded = true;
114     });
115    
116 wakaba 1.10
117     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    
696 wakaba 1.27 JSTE.Prefetch = {};
697    
698     JSTE.Class.addClassMethods (JSTE.Prefetch, {
699     URL: function (url) {
700     var link = document.createElement ('link');
701     link.rel = 'prefetch';
702     link.href = url;
703 wakaba 1.29 JSTE.Element.appendToHead (link);
704 wakaba 1.27 } // url
705     }); // JSTE.Prefetch class methods
706    
707 wakaba 1.9 JSTE.XHR = new JSTE.Class (function (url, onsuccess, onerror) {
708     try {
709     this._xhr = new XMLHttpRequest ();
710     } catch (e) {
711     try {
712     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP');
713     } catch (e) {
714     try {
715     this._xhr = new ActiveXObject ('Microsoft.XMLHTTP');
716     } catch (e) {
717     try {
718     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP.4.0');
719     } catch (e) {
720     this._xhr = null;
721     }
722     }
723     }
724     }
725    
726     this._url = url;
727     this._onsuccess = onsuccess || function () { };
728     this._onerror = onerror || function () { };
729     }, {
730     get: function () {
731     if (!this._xhr) return;
732    
733     var self = this;
734     this._xhr.open ('GET', this._url, true);
735     this._xhr.onreadystatechange = function () {
736     self._onreadystatechange ();
737     }; // onreadystatechange
738     this._xhr.send (null);
739     }, // get
740    
741     _onreadystatechange: function () {
742     if (this._xhr.readyState == 4) {
743     if (this.succeeded ()) {
744     this._onsuccess ();
745     } else {
746     this._onerror ();
747     }
748     }
749     }, // _onreadystatechange
750    
751     succeeded: function () {
752     return (this._xhr.status < 400);
753     }, // succeeded
754    
755     getDocument: function () {
756     return this._xhr.responseXML;
757     } // getDocument
758     }); // XHR
759    
760 wakaba 1.22 // An abstract class
761     JSTE.Storage = new JSTE.Class (function () {
762    
763     }, {
764 wakaba 1.23 get: function (name) {
765     throw "not implemented";
766     }, // get
767 wakaba 1.25 getJSON: function (name) {
768     var value = this.get (name);
769     if (value != null) {
770     return JSTE.JSON.parse (value); // XXX: try-catch?
771     } else {
772     return value;
773     }
774     }, // getJSON
775    
776 wakaba 1.23 set: function (name, value) {
777     throw "not implemented";
778     }, // set
779 wakaba 1.25 setJSON: function (name, obj) {
780     this.set (name, JSTE.JSON.stringify (obj));
781     }, // setJSON
782    
783     has: function (name) {
784     return this.get (name) !== undefined;
785     }, // has
786    
787     delete: function (name) {
788     throw "delete not implemented";
789     }, // delete
790    
791     flushGet: function (name) {
792     var v = this.get ('flush-' + name);
793     if (v !== undefined) {
794     this.delete ('flush-' + name);
795     }
796     return v;
797     }, // flushGet
798     flushSet: function (name, value) {
799     this.set ('flush-' + name, value);
800     }, // flushSet
801 wakaba 1.23
802     getNames: function () {
803     throw "not implemented";
804 wakaba 1.24 }, // getNames
805    
806     setPrefix: function (newPrefix) {
807     throw "not implemented";
808     } // setPrefix
809 wakaba 1.22 }); // Storage
810    
811     JSTE.Storage.PageLocal = new JSTE.Subclass (function () {
812 wakaba 1.24 this.keyPrefix = '';
813 wakaba 1.22 }, JSTE.Storage, {
814     get: function (name) {
815 wakaba 1.24 return this['value-' + this.keyPrefix + name];
816 wakaba 1.22 }, // get
817     set: function (name, value) {
818 wakaba 1.24 this['value-' + this.keyPrefix + name] = value;
819 wakaba 1.22 }, // set
820    
821     getNames: function () {
822     var names = new JSTE.List;
823     for (var n in this) {
824 wakaba 1.24 if (n.substring (0, 6 + this.keyPrefix.length) == 'value-' + this.keyPrefix) {
825     names.push (n.substring (6 + this.keyPrefix.length));
826 wakaba 1.22 }
827     }
828     return names;
829 wakaba 1.24 }, // getNames
830    
831     setPrefix: function (newPrefix) {
832     this.keyPrefix = newPrefix;
833     } // setPrefix
834 wakaba 1.23 }); // PageLocal
835    
836     JSTE.Storage.Cookie = JSTE.Subclass (function () {
837     this.keyPrefix = '';
838     this.domain = null;
839     this.path = '/';
840     this.persistent = false;
841     this.expires = null; // or Date
842     }, JSTE.Storage, {
843     _parse: function () {
844     return new JSTE.List (document.cookie.split (/;/)).mapToHash (function (nv) {
845     nv = nv.replace (/^\s+/, '').replace (/\s+$/, '').split (/=/, 2);
846     nv[0] = decodeURIComponent (nv[0]);
847     nv[1] = decodeURIComponent (nv[1]);
848     return nv;
849     });
850     }, // _parse
851    
852     get: function (name) {
853     return this._parse ().getNamedItem (this.keyPrefix + name);
854     }, // get
855     set: function (name, value) {
856     name = this.keyPrefix + name;
857     var r = encodeURIComponent (name) + '=' + encodeURIComponent (value);
858     if (this.domain) {
859     r += '; domain=' + this.domain;
860     }
861     if (this.path) {
862     r += '; path=' + this.path;
863     }
864     if (this.persistent) {
865     r += '; expires=' + new Date (2030, 1-1, 1).toUTCString ();
866     } else if (this.expires) {
867     r += '; expires=' + this.expires.toUTCString ();
868     }
869     document.cookie = r;
870     }, // set
871     delete: function (name) {
872     var expires = this.expires;
873     var persistent = this.persistent;
874     this.expires = new Date (0);
875     this.persistent = false;
876     this.set (name, '');
877     this.expires = expires;
878     this.persistent = persistent;
879     }, // delete
880    
881     getNames: function () {
882     var self = this;
883     return this._parse ().getNames ().grep (function (name) {
884     return name.substring (0, self.keyPrefix.length) == self.keyPrefix;
885     }).map (function (name) {
886     return name.substring (self.keyPrefix.length);
887     });
888 wakaba 1.24 }, // getNames
889    
890     setPrefix: function (newPrefix) {
891     this.keyPrefix = newPrefix;
892     } // setPrefix
893 wakaba 1.23 }); // Cookie
894    
895     JSTE.Storage.Local = JSTE.Class (function () {
896     var self = new JSTE.Storage.Cookie;
897     self.keyPrefix = 'localStorage-';
898     self.persistent = true;
899 wakaba 1.24 self.setPrefix = function (newPrefix) {
900     this.keyPrefix = 'localStorage-' + newPrefix;
901     }; // setPrefix
902 wakaba 1.23 return self;
903     }); // Local
904 wakaba 1.22
905 wakaba 1.25 JSTE.JSON = {};
906    
907     JSTE.Class.addClassMethods (JSTE.JSON, {
908     parse: function (value) {
909     if (self.JSON && JSON.parse) {
910     return JSON.parse (value); // json2.js or ES3.1
911     } else {
912     return eval ('(' + value + ')');
913     }
914     }, // parse
915    
916     stringify: function (obj) {
917     if (self.JSON && JSON.stringify) {
918     return JSON.stringify (obj); // json2.js or ES3.1
919     } else {
920     throw "JSTE.JSON.stringify not implemented";
921     }
922     } // serialize
923     }); // JSON class methods
924    
925    
926 wakaba 1.9
927 wakaba 1.1 /* Events: load, close, shown, hidden */
928 wakaba 1.18 JSTE.Message = new JSTE.Class (function (doc, template, commandTarget, availCommands) {
929 wakaba 1.1 if (!doc) return;
930     this._targetDocument = doc;
931     this._template = template || doc.createDocumentFragment ();
932 wakaba 1.8
933 wakaba 1.1 this._commandTarget = commandTarget;
934 wakaba 1.18 this._availCommands = availCommands || new JSTE.List;
935 wakaba 1.8
936 wakaba 1.1 this.hidden = true;
937     this.select = "";
938    
939     var e = new JSTE.Event ('load');
940     this.dispatchEvent (e);
941     }, {
942     render: function () {
943     var self = this;
944     var doc = this._targetDocument;
945    
946     var msgContainer = doc.createElement ('section');
947     msgContainer.appendChild (this._template);
948 wakaba 1.20
949     if (!this._availCommands.list.length) {
950 wakaba 1.8 this._availCommands.push ({name: 'back'});
951     this._availCommands.push ({name: 'next'});
952 wakaba 1.7 }
953 wakaba 1.20
954 wakaba 1.30 this._availCommands = this._availCommands.grep (function (item) {
955 wakaba 1.20 return self._commandTarget.canExecuteCommand (item.name, item.args);
956     });
957 wakaba 1.1
958 wakaba 1.8 this._outermostElement = this._render (msgContainer);
959 wakaba 1.1
960     this.show ();
961     }, // render
962     _render: function (msgContainer, buttonContainer) {
963     var doc = this._targetDocument;
964    
965     var container = doc.createElement ('article');
966    
967     container.appendChild (msgContainer);
968 wakaba 1.8
969     var buttonContainer = this.createCommandButtons ();
970 wakaba 1.1 container.appendChild (buttonContainer);
971 wakaba 1.8
972 wakaba 1.1 doc.documentElement.appendChild (container);
973    
974     return container;
975     }, // _render
976 wakaba 1.8 createCommandButtons: function () {
977     var self = this;
978 wakaba 1.18 var doc = this._targetDocument;
979     var buttonContainer = doc.createElement ('menu');
980 wakaba 1.8 this._availCommands.forEach (function (cmd) {
981 wakaba 1.18 var label = cmd.name;
982     if (cmd.labelTemplate) {
983     label = JSTE.Element.createTemplate (doc, cmd.labelTemplate);
984     }
985    
986 wakaba 1.8 var button = new JSTE.Message.Button
987 wakaba 1.26 (label, self._commandTarget, cmd.name, cmd.args, cmd.actions);
988 wakaba 1.8 buttonContainer.appendChild (button.element);
989 wakaba 1.27
990     if (cmd.name == 'url') {
991     JSTE.Prefetch.URL (cmd.args.url);
992     }
993 wakaba 1.8 });
994     return buttonContainer;
995     }, // createCommandButtons
996    
997 wakaba 1.1 remove: function () {
998     this.hide ();
999    
1000     this._remove ();
1001    
1002     if (this._outermostElement && this._outermostElement.parentNode) {
1003     this._outermostElement.parentNode.removeChild (this._outermostElement);
1004     }
1005    
1006     var e = new JSTE.Event ("close");
1007     this.dispatchEvent (e);
1008     }, // remove
1009     _remove: function () {
1010    
1011     }, // remove
1012    
1013     show: function () {
1014     if (!this.hidden) return;
1015     this.hidden = false;
1016     if (this._outermostElement) {
1017     JSTE.Element.replaceClassName
1018     (this._outermostElement, "jste-hidden", "jste-shown");
1019     }
1020    
1021     var e = new JSTE.Event ("shown");
1022     this.dispatchEvent (e);
1023     }, // show
1024     hide: function () {
1025     if (this.hidden) return;
1026     this.hidden = true;
1027     if (this._outermostElement) {
1028     JSTE.Element.replaceClassName
1029     (this._outermostElement, "jste-shown", "jste-hidden");
1030     }
1031    
1032     var e = new JSTE.Event ("hidden");
1033     this.dispatchEvent (e);
1034     }, // hide
1035    
1036     setTimeout: function () {
1037     /* TODO: ... */
1038    
1039     }
1040    
1041     }); // Message
1042    
1043 wakaba 1.7 /* TODO: button label text should refer message catalog */
1044    
1045 wakaba 1.1 JSTE.Message.Button =
1046 wakaba 1.26 new JSTE.Class (function (label, commandTarget, commandName, commandArgs, commandActions) {
1047 wakaba 1.18 this._label = label != null ? label : "";
1048 wakaba 1.6
1049 wakaba 1.1 if (commandTarget && commandTarget instanceof Function) {
1050     this._command = commandTarget;
1051 wakaba 1.6 this._classNames = new JSTE.List;
1052 wakaba 1.1 } else if (commandTarget) {
1053     this._command = function () {
1054     return commandTarget.executeCommand.apply
1055 wakaba 1.26 (commandTarget, [commandName, commandArgs, commandActions]);
1056 wakaba 1.1 };
1057 wakaba 1.6 this._classNames = new JSTE.List (['jste-command-' + commandName]);
1058 wakaba 1.1 } else {
1059     this._command = function () { };
1060 wakaba 1.6 this._classNames = new JSTE.List;
1061 wakaba 1.1 }
1062    
1063 wakaba 1.6 this._createElement ();
1064 wakaba 1.1 }, {
1065 wakaba 1.6 _createElement: function () {
1066     try {
1067     this.element = document.createElement ('button');
1068     this.element.setAttribute ('type', 'button');
1069     } catch (e) {
1070     this.element = document.createElement ('<button type=button>');
1071     }
1072 wakaba 1.18 if (this._label.nodeType) {
1073     this.element.appendChild (this._label);
1074     } else {
1075     JSTE.Element.appendText (this.element, this._label);
1076     }
1077 wakaba 1.6 this.element.className = this._classNames.list.join (' ');
1078 wakaba 1.1
1079 wakaba 1.6 var self = this;
1080     new JSTE.Observer ("click", this.element, function (e) {
1081     self._command (e);
1082     });
1083     } // _createElement
1084 wakaba 1.1 }); // Button
1085    
1086     JSTE.Course = new JSTE.Class (function (doc) {
1087     this._targetDocument = doc;
1088    
1089 wakaba 1.29 this._entryPoints = new JSTE.List;
1090     this._entryPoints.push
1091     ({conditions: new JSTE.List ([{type: 'state', value: 'done'}]),
1092     stepUid: 'special-none'});
1093 wakaba 1.1
1094     this._stepsState = new JSTE.List ([new JSTE.Hash]);
1095     this._steps = new JSTE.Hash;
1096    
1097     var nullState = new JSTE.Step;
1098 wakaba 1.29 nullState.uid = "special-none";
1099 wakaba 1.1 this._steps.setNamedItem (nullState.uid, nullState);
1100     this._initialStepUid = nullState.uid;
1101     }, {
1102 wakaba 1.10 _processStepsContent: function (el, parentSteps) {
1103 wakaba 1.1 var self = this;
1104     new JSTE.List (el.childNodes).switchByElementType (
1105     new JSTE.List.SwitchByLocalName (JSTE.WATNS, {
1106 wakaba 1.10 steps: function (n) { self._processStepsElement (n, parentSteps) },
1107     step: function (n) { self._processStepElement (n, parentSteps) },
1108     jump: function (n) { self._processJumpElement (n, parentSteps) },
1109 wakaba 1.29 'entry-point': function (n) { self._processEntryPointElement (n, parentSteps) }
1110 wakaba 1.1 })
1111     );
1112     }, // _processStepsContent
1113 wakaba 1.10 _processStepsElement: function (e, parentSteps) {
1114     var steps = new JSTE.Steps ();
1115     steps.parentSteps = parentSteps;
1116 wakaba 1.1 this._stepsState.pushCloneOfLast ();
1117     this._stepsState.getLast ().prevStep = null;
1118 wakaba 1.29
1119     this._addConditionsFromElement (e, steps.conditions);
1120 wakaba 1.10 this._processStepsContent (e, steps);
1121 wakaba 1.29
1122 wakaba 1.1 this._stepsState.pop ();
1123     }, // _processStepsElement
1124    
1125 wakaba 1.14 _processEntryPointElement: function (e, parentSteps) {
1126 wakaba 1.29 var conds = parentSteps ? parentSteps.conditions.clone () : new JSTE.List;
1127     this._addConditionsFromElement (e, conds);
1128    
1129     var stepUid = e.getAttribute ('step');
1130     if (stepUid != null) stepUid = 'id-' + stepUid;
1131     this._entryPoints.push ({conditions: conds, stepUid: stepUid});
1132 wakaba 1.14 }, // _processEntryPointElement
1133 wakaba 1.22
1134 wakaba 1.29 _addConditionsFromElement: function (e, conds) {
1135     var urls = e.getAttribute ('document-url');
1136     if (urls != null) {
1137     JSTE.List.spaceSeparated (urls).forEach (function (url) {
1138     conds.push ({type: 'url', value: encodeURI (url)});
1139     // TODO: resolve relative URL, URL->URI
1140     });
1141 wakaba 1.22 }
1142 wakaba 1.29
1143     var urls = e.getAttribute ('not-document-url');
1144     if (urls != null) {
1145     JSTE.List.spaceSeparated (urls).forEach (function (url) {
1146     conds.push ({type: 'url', value: encodeURI (url), not: true});
1147     // TODO: resolve relative URL
1148     });
1149 wakaba 1.1 }
1150 wakaba 1.29
1151     var classNames = e.getAttribute ('document-class');
1152     if (classNames != null) {
1153     JSTE.List.spaceSeparated (classNames).forEach (function (className) {
1154     conds.push ({type: 'class', value: className});
1155 wakaba 1.1 });
1156 wakaba 1.29 }
1157    
1158     var classNames = e.getAttribute ('not-document-class');
1159     if (classNames != null) {
1160     JSTE.List.spaceSeparated (classNames).forEach (function (className) {
1161     conds.push ({type: 'class', value: className, not: true});
1162 wakaba 1.1 });
1163     }
1164 wakaba 1.29
1165     var stateNames = e.getAttribute ('state');
1166     if (stateNames != null) {
1167     JSTE.List.spaceSeparated (stateNames).forEach (function (stateName) {
1168     conds.push ({type: 'state', value: stateName});
1169 wakaba 1.1 });
1170 wakaba 1.29 }
1171    
1172     var stateNames = e.getAttribute ('not-state');
1173     if (stateNames != null) {
1174     JSTE.List.spaceSeparated (stateNames).forEach (function (stateName) {
1175     conds.push ({type: 'state', value: stateName, not: true});
1176 wakaba 1.1 });
1177     }
1178 wakaba 1.29 }, // _addConditionsFromElement
1179    
1180     findEntryPoint: function (doc, states) {
1181     var self = this;
1182    
1183     var td = this._targetDocument;
1184     var docURL = td.URL; // TODO: drop fragments?
1185     var docClassNames = JSTE.Document.getClassNames (td);
1186    
1187     var stepUid = this._entryPoints.forEach (function (ep) {
1188     if (ep.conditions.forEach (function (cond) {
1189     var matched;
1190     if (cond.type == 'state') {
1191     matched = states.has (cond.value);
1192     } else if (cond.type == 'class') {
1193     matched = docClassNames.has (cond.value);
1194     } else if (cond.type == 'url') {
1195     matched = cond.value == docURL;
1196     } else {
1197     //
1198     }
1199     if (cond.not) matched = !matched;
1200     if (!matched) return new JSTE.List.Return (true);
1201     })) return; // true = not matched
1202    
1203     // matched
1204     return new JSTE.List.Return (ep.stepUid);
1205     });
1206    
1207     // TODO: multiple elements with same ID
1208    
1209     if (stepUid != null) {
1210     return stepUid;
1211     } else {
1212     return this._initialStepUid;
1213     }
1214 wakaba 1.1 }, // findEntryPoint
1215    
1216 wakaba 1.10 _processStepElement: function (e, parentSteps) {
1217 wakaba 1.18 var self = this;
1218    
1219 wakaba 1.1 var step = new JSTE.Step (e.getAttribute ('id'));
1220 wakaba 1.10 step.parentSteps = parentSteps;
1221 wakaba 1.1 step.setPreviousStep (this._stepsState.getLast ().prevStep);
1222     step.select = e.getAttribute ('select') || "";
1223     step.nextEvents.append
1224 wakaba 1.10 (JSTE.List.spaceSeparated (e.getAttribute ('next-event')));
1225 wakaba 1.17
1226 wakaba 1.28 step.noHistory = JSTE.Element.hasAttribute (e, 'nohistory');
1227    
1228 wakaba 1.17 var cs = JSTE.Element.getChildrenClassifiedByType (e);
1229    
1230     var msgEl = cs.get (JSTE.WATNS, 'message').list[0];
1231 wakaba 1.1 if (msgEl) {
1232     var msg = JSTE.Element.createTemplate (this._targetDocument, msgEl);
1233     step.setMessageTemplate (msg);
1234     }
1235 wakaba 1.17
1236     var nextEls = cs.get (JSTE.WATNS, 'next-step');
1237 wakaba 1.16 if (nextEls.list.length) {
1238 wakaba 1.1 nextEls.forEach (function (nextEl) {
1239     step.addNextStep
1240     (nextEl.getAttribute ('if'), nextEl.getAttribute ('step'));
1241     });
1242     this._stepsState.getLast ().prevStep = null;
1243     } else {
1244     this._stepsState.getLast ().prevStep = step;
1245     }
1246 wakaba 1.17
1247 wakaba 1.19 cs.get (JSTE.WATNS, 'command').forEach (function (bEl) {
1248 wakaba 1.18 var cmd = {
1249 wakaba 1.20 name: bEl.getAttribute ('type') || 'gotoStep'
1250 wakaba 1.18 };
1251     if (cmd.name == 'gotoStep') {
1252 wakaba 1.25 cmd.args = {stepUid: 'id-' + bEl.getAttribute ('step')};
1253 wakaba 1.24 } else if (cmd.name == 'url') {
1254 wakaba 1.27 // TODO: relative URL
1255 wakaba 1.26 cmd.args = {url: bEl.getAttribute ('href')};
1256 wakaba 1.18 }
1257 wakaba 1.26 cmd.actions = {
1258 wakaba 1.28 saveStateNames: JSTE.List.spaceSeparated (bEl.getAttribute ('save-state')),
1259 wakaba 1.26 clearStateNames: JSTE.List.spaceSeparated (bEl.getAttribute ('clear-state'))
1260     };
1261 wakaba 1.18 if (!JSTE.Element.isEmpty (bEl)) {
1262     cmd.labelTemplate = JSTE.Element.createTemplate (self._targetDocument, bEl);
1263     }
1264     step.availCommands.push (cmd);
1265 wakaba 1.22 }); // wat:command
1266 wakaba 1.18
1267 wakaba 1.22 cs.get (JSTE.WATNS, 'save-state').forEach (function (bEl) {
1268     var ss = new JSTE.SaveState
1269     (bEl.getAttribute ('name'), bEl.getAttribute ('value'));
1270     step.saveStates.push (ss);
1271     }); // wat:save-state
1272 wakaba 1.13
1273     var evs = JSTE.List.spaceSeparated (e.getAttribute ('entry-event'));
1274     if (evs.list.length) {
1275     var jump = new JSTE.Jump (step.select, evs, step.uid);
1276     if (parentSteps) parentSteps._jumps.push (jump);
1277     }
1278 wakaba 1.1
1279     this._steps.setNamedItem (step.uid, step);
1280 wakaba 1.29 /*if (!this._initialStepUid) {
1281 wakaba 1.1 this._initialStepUid = step.uid;
1282 wakaba 1.29 }*/
1283 wakaba 1.1 }, // _processStepElement
1284    
1285 wakaba 1.10 _processJumpElement: function (e, parentSteps) {
1286     var target = e.getAttribute ('target') || '';
1287     var evs = JSTE.List.spaceSeparated (e.getAttribute ('event'));
1288     var stepName = e.getAttribute ('step') || '';
1289    
1290     var jump = new JSTE.Jump (target, evs, 'id-' + stepName);
1291     if (parentSteps) parentSteps._jumps.push (jump);
1292 wakaba 1.1 }, // _processJumpElement
1293    
1294     getStep: function (uid) {
1295     return this._steps.getNamedItem (uid);
1296     } // getStep
1297     }); // Course
1298    
1299 wakaba 1.9 JSTE.Class.addClassMethods (JSTE.Course, {
1300     createFromDocument: function (doc, targetDoc) {
1301     var course = new JSTE.Course (targetDoc);
1302     var docEl = doc.documentElement;
1303     if (!docEl) return course;
1304     if (!JSTE.Element.match (docEl, JSTE.WATNS, 'course')) return course;
1305 wakaba 1.10 course._processStepsContent (docEl, null);
1306 wakaba 1.24 course.name = docEl.hasAttribute ('name') ? docEl.getAttribute ('name') + '-' : '';
1307 wakaba 1.9 return course;
1308     }, // createFromDocument
1309     createFromURL: function (url, targetDoc, onload, onerror) {
1310     new JSTE.XHR (url, function () {
1311     var course = JSTE.Course.createFromDocument
1312     (this.getDocument (), targetDoc);
1313     if (onload) onload (course);
1314     }, onerror).get ();
1315     } // creatFromURL
1316     }); // Course class methods
1317 wakaba 1.1
1318 wakaba 1.10 JSTE.Jump = new JSTE.Class (function (selectors, eventNames, stepUid) {
1319     this.selectors = selectors;
1320     this.eventNames = eventNames;
1321     this.stepUid = stepUid;
1322     // this.parentSteps
1323     }, {
1324     startObserver: function (doc, commandTarget) {
1325     var self = this;
1326     var observers = new JSTE.List;
1327    
1328     var onev = function () {
1329 wakaba 1.25 commandTarget.gotoStep ({stepUid: self.stepUid});
1330 wakaba 1.10 };
1331    
1332     JSTE.Node.querySelectorAll (doc, this.selectors).forEach
1333     (function (el) {
1334     self.eventNames.forEach (function (evName) {
1335     var ob = new JSTE.Observer (evName, el, onev);
1336     ob._stepUid = self.stepUid;
1337     observers.push (ob);
1338     });
1339     });
1340    
1341     return observers;
1342     } // startObserver
1343     }); // Jump
1344    
1345     JSTE.Steps = new JSTE.Class (function () {
1346     this._jumps = new JSTE.List;
1347     this._jumpHandlers = new JSTE.List;
1348 wakaba 1.29 this.conditions = new JSTE.List;
1349 wakaba 1.10 }, {
1350     setCurrentStepByUid: function (uid) {
1351     this._jumpHandlers.forEach (function (jh) {
1352     if (jh._stepUid != uid && jh.disabled) {
1353     jh.start ();
1354     } else if (jh._stepUid == uid && !jh.disabled) {
1355     jh.stop ();
1356     }
1357     });
1358     }, // setCurrentStepByUid
1359    
1360     installJumps: function (doc, commandTarget) {
1361     if (this._jumpHandlers.list.length) return;
1362     var self = this;
1363     this._jumps.forEach (function (j) {
1364     self._jumpHandlers.append (j.startObserver (doc, commandTarget));
1365     });
1366     }, // installJumps
1367    
1368     uninstallJumps: function () {
1369     this._jumpHandlers.forEach (function (jh) {
1370     jh.stop ();
1371     });
1372     this._jumpHandlers.clear ();
1373     } // uninstallJumps
1374     }); // Steps
1375    
1376 wakaba 1.1 JSTE.Step = new JSTE.Class (function (id) {
1377     if (id != null && id != '') {
1378     this.uid = 'id-' + id;
1379     } else {
1380     this.uid = 'rand-' + Math.random ();
1381     }
1382     this._nextSteps = new JSTE.List;
1383     this.nextEvents = new JSTE.List;
1384 wakaba 1.18 this.availCommands = new JSTE.List;
1385 wakaba 1.22 this.saveStates = new JSTE.List;
1386 wakaba 1.1 this.select = "";
1387 wakaba 1.30 // this._messageTemplate
1388 wakaba 1.1 }, {
1389     setMessageTemplate: function (msg) {
1390     this._messageTemplate = msg;
1391     }, // setMessageTemplate
1392     hasMessage: function () {
1393     return this._messageTemplate ? true : false;
1394     }, // hasMessage
1395     createMessage: function (msg, doc, commandTarget) {
1396     var msg;
1397     if (this._messageTemplate) {
1398     var clone = JSTE.Element.createTemplate (doc, this._messageTemplate);
1399 wakaba 1.18 msg = new msg (doc, clone, commandTarget, this.availCommands.clone ());
1400 wakaba 1.1 } else {
1401 wakaba 1.30 msg = new msg (doc, null, commandTarget, this.availCommands.clone ());
1402 wakaba 1.1 }
1403     msg.select = this.select;
1404     return msg;
1405     }, // createMessage
1406    
1407     addNextStep: function (condition, stepId) {
1408 wakaba 1.16 if (stepId != null) this._nextSteps.push ([condition, stepId]);
1409 wakaba 1.1 }, // addNextStep
1410     setPreviousStep: function (prevStep) {
1411     if (!prevStep) return;
1412     if (prevStep._defaultNextStepUid) return;
1413     prevStep._defaultNextStepUid = this.uid;
1414     }, // setPreviousStep
1415    
1416     getNextStepUid: function (doc) {
1417     var m = this._nextSteps.getFirstMatch (function (item) {
1418     var condition = item[0];
1419     if (condition) {
1420     return JSTE.Node.querySelector (doc, condition) != null;
1421     } else {
1422     return true;
1423     }
1424     });
1425     if (m) {
1426     return 'id-' + m[1];
1427     } else if (this._defaultNextStepUid) {
1428     return this._defaultNextStepUid;
1429     } else {
1430     return null;
1431     }
1432 wakaba 1.10 }, // getNextStepUid
1433    
1434     getAncestorStepsObjects: function () {
1435     var steps = new JSTE.List;
1436     var s = this.parentSteps;
1437     while (s != null) {
1438     steps.push (s);
1439     s = s.parentSteps;
1440     }
1441     return steps;
1442     } // getAncestorStepsObjects
1443 wakaba 1.1 }); // Step
1444    
1445 wakaba 1.22 JSTE.SaveState = new JSTE.Class (function (name, value) {
1446     this.name = name || '';
1447     this.value = value || '';
1448     }, {
1449 wakaba 1.25 save: function (tutorial) {
1450     var name = this.name;
1451     var value = this.value;
1452     if (name == 'back-state') return;
1453     tutorial._states.set (name, value);
1454 wakaba 1.22 } // save
1455     }); // SaveState
1456    
1457     /* Events: load, error, cssomready, close */
1458 wakaba 1.9 JSTE.Tutorial = new JSTE.Class (function (course, doc, args) {
1459 wakaba 1.1 this._course = course;
1460     this._targetDocument = doc;
1461     this._messageClass = JSTE.Message;
1462     if (args) {
1463     if (args.messageClass) this._messageClass = args.messageClass;
1464 wakaba 1.22 if (args.states) this._states = args.states;
1465 wakaba 1.1 }
1466 wakaba 1.22 if (!this._states) this._states = new JSTE.Storage.PageLocal;
1467 wakaba 1.24 this._states.setPrefix (course.name);
1468 wakaba 1.1
1469     this._currentMessages = new JSTE.List;
1470     this._currentObservers = new JSTE.List;
1471 wakaba 1.25 this._currentStepsObjects = new JSTE.List;
1472    
1473 wakaba 1.1 this._prevStepUids = new JSTE.List;
1474 wakaba 1.25 this._loadBackState ();
1475    
1476     var stepUid;
1477 wakaba 1.29 if (this._states.flushGet ('is-back') && this._prevStepUids.list.length) {
1478 wakaba 1.25 stepUid = this._prevStepUids.pop ();
1479     } else {
1480     stepUid = this._course.findEntryPoint (document, this._states);
1481     }
1482    
1483 wakaba 1.1 this._currentStep = this._getStepOrError (stepUid);
1484     if (this._currentStep) {
1485     var e = new JSTE.Event ('load');
1486     this.dispatchEvent (e);
1487 wakaba 1.25
1488     this._saveBackState ();
1489    
1490 wakaba 1.3 var self = this;
1491     new JSTE.Observer ('cssomready', this, function () {
1492     self._renderCurrentStep ();
1493     });
1494     this._dispatchCSSOMReadyEvent ();
1495 wakaba 1.1 return this;
1496     } else {
1497     return {};
1498     }
1499     }, {
1500     _getStepOrError: function (stepUid) {
1501 wakaba 1.29 if (stepUid == 'special-none') {
1502     return null;
1503     }
1504    
1505 wakaba 1.1 var step = this._course.getStep (stepUid);
1506     if (step) {
1507     return step;
1508     } else {
1509     var e = new JSTE.Event ('error');
1510     e.errorMessage = 'Step not found';
1511     e.errorArguments = [this._currentStepUid];
1512     this.dispatchEvent (e);
1513     return null;
1514     }
1515     }, // _getStepOrError
1516    
1517     _renderCurrentStep: function () {
1518     var self = this;
1519     var step = this._currentStep;
1520 wakaba 1.22
1521 wakaba 1.25 step.saveStates.forEach (function (ss) { ss.save (self) });
1522 wakaba 1.1
1523     /* Message */
1524     var msg = step.createMessage
1525     (this._messageClass, this._targetDocument, this);
1526     msg.render ();
1527     this._currentMessages.push (msg);
1528    
1529     /* Next-events */
1530     var selectedNodes = JSTE.Node.querySelectorAll
1531     (this._targetDocument, step.select);
1532     var handler = function () {
1533     self.executeCommand ("next");
1534     };
1535     selectedNodes.forEach (function (node) {
1536     step.nextEvents.forEach (function (eventType) {
1537     self._currentObservers.push
1538     (new JSTE.Observer (eventType, node, handler));
1539     });
1540     });
1541 wakaba 1.10
1542     JSTE.List.getCommonItems (this._currentStepsObjects,
1543     step.getAncestorStepsObjects (),
1544     function (common, onlyInOld, onlyInNew) {
1545     common.forEach (function (item) {
1546     item.setCurrentStepByUid (step.uid);
1547     });
1548     onlyInOld.forEach (function (item) {
1549     item.uninstallJumps ();
1550     });
1551     onlyInNew.forEach (function (item) {
1552     item.installJumps (self._targetDocument, self);
1553     });
1554     self._currentStepsObjects = common.append (onlyInNew);
1555     });
1556 wakaba 1.1 }, // _renderCurrentStep
1557     clearMessages: function () {
1558     this._currentMessages.forEach (function (msg) {
1559     msg.remove ();
1560     });
1561     this._currentMessages.clear ();
1562    
1563     this._currentObservers.forEach (function (ob) {
1564     ob.stop ();
1565     });
1566     this._currentObservers.clear ();
1567     }, // clearMessages
1568 wakaba 1.10 clearStepsHandlers: function () {
1569     this._currentStepsObjects.forEach (function (item) {
1570     item.uninstallJumps ();
1571     });
1572     this._currentStepsObjects.clear ();
1573     }, // clearStepsHandlers
1574 wakaba 1.1
1575 wakaba 1.26 executeCommand: function (commandName, commandArgs, commandActions) {
1576 wakaba 1.1 if (this[commandName]) {
1577 wakaba 1.26 // Common actions
1578 wakaba 1.28 if (commandActions) {
1579 wakaba 1.26 var self = this;
1580 wakaba 1.28 if (commandActions.saveStateNames) {
1581     commandActions.saveStateNames.forEach (function (stateName) {
1582     self._states.set (stateName, '');
1583     });
1584     }
1585     if (commandActions.clearStateNames) {
1586     commandActions.clearStateNames.forEach (function (stateName) {
1587 wakaba 1.29 if (stateName == 'back-state') {
1588     self._prevStateUids = new JSTE.List;
1589     self._prevPages = new JSTE.List;
1590     }
1591 wakaba 1.28 self._states.delete (stateName);
1592     });
1593     }
1594 wakaba 1.26 }
1595    
1596 wakaba 1.25 return this[commandName].apply (this, [commandArgs || {}]);
1597 wakaba 1.1 } else {
1598     var e = new JSTE.Event ('error');
1599     e.errorMessage = 'Command not found';
1600     e.errorArguments = [commandName];
1601     return null;
1602     }
1603     }, // executeCommand
1604 wakaba 1.7 canExecuteCommand: function (commandName, commandArgs) {
1605     if (this[commandName]) {
1606     var can = this['can' + commandName.substring (0, 1).toUpperCase ()
1607     + commandName.substring (1)];
1608     if (can) {
1609     return can.apply (this, arguments);
1610     } else {
1611     return true;
1612     }
1613     } else {
1614     return false;
1615     }
1616     }, // canExecuteCommand
1617 wakaba 1.1
1618     back: function () {
1619 wakaba 1.25 while (this._prevStepUids.list.length == 0 &&
1620     this._prevPages.list.length > 0) {
1621     var prevPage = this._prevPages.pop ();
1622     if (prevPage.url != location.href) {
1623     this._saveBackState (true);
1624 wakaba 1.29 this._states.flushSet ('is-back', true);
1625 wakaba 1.26 if (document.referrer == prevPage.url) {
1626     history.back ();
1627     } else {
1628     location.href = prevPage.url;
1629     }
1630 wakaba 1.25 // TODO: maybe we should not return if locaton.href and prevPage.,url only differs their fragment ids?
1631     return;
1632     }
1633     this._prevStepUids = prevPage;
1634     }
1635    
1636 wakaba 1.1 var prevStepUid = this._prevStepUids.pop ();
1637     var prevStep = this._getStepOrError (prevStepUid);
1638     if (prevStep) {
1639     this.clearMessages ();
1640 wakaba 1.25 this._saveBackState ();
1641 wakaba 1.1 this._currentStep = prevStep;
1642     this._renderCurrentStep ();
1643     }
1644     }, // back
1645 wakaba 1.7 canBack: function () {
1646 wakaba 1.25 return this._prevStepUids.list.length > 0 || this._prevPages.list.length > 0;
1647 wakaba 1.7 }, // canBack
1648 wakaba 1.1 next: function () {
1649     var nextStepUid = this._currentStep.getNextStepUid (this._targetDocument);
1650     var nextStep = this._getStepOrError (nextStepUid);
1651     if (nextStep) {
1652 wakaba 1.28 if (!this._currentStep.noHistory) {
1653     this._prevStepUids.push (this._currentStep.uid);
1654     }
1655 wakaba 1.1 this.clearMessages ();
1656 wakaba 1.25 this._saveBackState ();
1657 wakaba 1.1 this._currentStep = nextStep;
1658     this._renderCurrentStep ();
1659     }
1660 wakaba 1.3 }, // next
1661 wakaba 1.7 canNext: function () {
1662     return this._currentStep.getNextStepUid (this._targetDocument) != null;
1663     }, // canNext
1664 wakaba 1.25 gotoStep: function (args) {
1665     var nextStep = this._getStepOrError (args.stepUid);
1666 wakaba 1.10 if (nextStep) {
1667 wakaba 1.28 if (!this._currentStep.noHistory) {
1668     this._prevStepUids.push (this._currentStep.uid);
1669     }
1670 wakaba 1.25 this._saveBackState ();
1671 wakaba 1.10 this.clearMessages ();
1672     this._currentStep = nextStep;
1673     this._renderCurrentStep ();
1674     }
1675     }, // gotoStep
1676 wakaba 1.24
1677 wakaba 1.25 url: function (args) {
1678     location.href = args.url;
1679 wakaba 1.24 }, // url
1680 wakaba 1.20
1681     close: function () {
1682     this.clearMessages ();
1683 wakaba 1.22 var e = new JSTE.Event ('closed');
1684     this.dispatchEvent (e);
1685 wakaba 1.20 }, // close
1686 wakaba 1.25
1687     _loadBackState: function () {
1688     var self = this;
1689     this._prevPages = new JSTE.List;
1690     var bs = this._states.getJSON ('back-state');
1691     new JSTE.List (bs).forEach (function (b) {
1692     var i = new JSTE.List (b.stepUids);
1693     i.url = b.url;
1694     self._prevPages.push (i);
1695     });
1696     if ((this._prevPages.getLast () || {}).url == location.href) {
1697     this._prevStepUids = this._prevPages.pop ();
1698     }
1699     }, // loadBackState
1700     _saveBackState: function (ignoreCurrentPage) {
1701     var bs = [];
1702     this._prevPages.forEach (function (pp) {
1703     bs.push ({url: pp.url, stepUids: pp.list});
1704     });
1705     if (!ignoreCurrentPage) {
1706     var uids = this._prevStepUids.clone ();
1707 wakaba 1.28 if (!this._currentStep.noHistory) {
1708     uids.push (this._currentStep.uid);
1709     }
1710     if (uids.list.length) {
1711     bs.push ({url: location.href, stepUids: uids.list});
1712     }
1713 wakaba 1.25 }
1714     this._states.setJSON ('back-state', bs);
1715     }, // _saveBackState
1716 wakaba 1.3
1717     // <http://twitter.com/waka/status/1129513097>
1718     _dispatchCSSOMReadyEvent: function () {
1719     var self = this;
1720     var e = new JSTE.Event ('cssomready');
1721     if (window.opera && document.readyState != 'complete') {
1722     new JSTE.Observer ('readystatechange', document, function () {
1723     if (document.readyState == 'complete') {
1724     self.dispatchEvent (e);
1725     }
1726     });
1727     } else {
1728     this.dispatchEvent (e);
1729     }
1730     } // dispatchCSSOMReadyEvent
1731    
1732 wakaba 1.1 }); // Tutorial
1733 wakaba 1.9
1734     JSTE.Class.addClassMethods (JSTE.Tutorial, {
1735 wakaba 1.12 createFromURL: function (url, doc, args, onload) {
1736 wakaba 1.9 JSTE.Course.createFromURL (url, doc, function (course) {
1737 wakaba 1.12 var tutorial = new JSTE.Tutorial (course, doc, args);
1738     if (onload) onload (tutorial);
1739 wakaba 1.9 });
1740     } // createFromURL
1741     }); // Tutorial class methods
1742    
1743    
1744 wakaba 1.5
1745     if (JSTE.onLoadFunctions) {
1746     new JSTE.List (JSTE.onLoadFunctions).forEach (function (code) {
1747     code ();
1748     });
1749     }
1750    
1751     if (JSTE.isDynamicallyLoaded) {
1752     JSTE.windowLoaded = true;
1753     }
1754 wakaba 1.2
1755     /* ***** BEGIN LICENSE BLOCK *****
1756     * Copyright 2008-2009 Wakaba <w@suika.fam.cx>. All rights reserved.
1757     *
1758     * This program is free software; you can redistribute it and/or
1759     * modify it under the same terms as Perl itself.
1760     *
1761     * Alternatively, the contents of this file may be used
1762     * under the following terms (the "MPL/GPL/LGPL"),
1763     * in which case the provisions of the MPL/GPL/LGPL are applicable instead
1764     * of those above. If you wish to allow use of your version of this file only
1765     * under the terms of the MPL/GPL/LGPL, and not to allow others to
1766     * use your version of this file under the terms of the Perl, indicate your
1767     * decision by deleting the provisions above and replace them with the notice
1768     * and other provisions required by the MPL/GPL/LGPL. If you do not delete
1769     * the provisions above, a recipient may use your version of this file under
1770     * the terms of any one of the Perl or the MPL/GPL/LGPL.
1771     *
1772     * "MPL/GPL/LGPL":
1773     *
1774     * Version: MPL 1.1/GPL 2.0/LGPL 2.1
1775     *
1776     * The contents of this file are subject to the Mozilla Public License Version
1777     * 1.1 (the "License"); you may not use this file except in compliance with
1778     * the License. You may obtain a copy of the License at
1779     * <http://www.mozilla.org/MPL/>
1780     *
1781     * Software distributed under the License is distributed on an "AS IS" basis,
1782     * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
1783     * for the specific language governing rights and limitations under the
1784     * License.
1785     *
1786     * The Original Code is JSTE code.
1787     *
1788     * The Initial Developer of the Original Code is Wakaba.
1789     * Portions created by the Initial Developer are Copyright (C) 2008
1790     * the Initial Developer. All Rights Reserved.
1791     *
1792     * Contributor(s):
1793     * Wakaba <w@suika.fam.cx>
1794     *
1795     * Alternatively, the contents of this file may be used under the terms of
1796     * either the GNU General Public License Version 2 or later (the "GPL"), or
1797     * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
1798     * in which case the provisions of the GPL or the LGPL are applicable instead
1799     * of those above. If you wish to allow use of your version of this file only
1800     * under the terms of either the GPL or the LGPL, and not to allow others to
1801     * use your version of this file under the terms of the MPL, indicate your
1802     * decision by deleting the provisions above and replace them with the notice
1803     * and other provisions required by the LGPL or the GPL. If you do not delete
1804     * the provisions above, a recipient may use your version of this file under
1805     * the terms of any one of the MPL, the GPL or the LGPL.
1806     *
1807     * ***** END LICENSE BLOCK ***** */

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24