/[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.17 - (hide annotations) (download) (as text)
Mon Jan 26 13:57:32 2009 UTC (16 years, 7 months ago) by wakaba
Branch: MAIN
Changes since 1.16: +44 -2 lines
File MIME type: application/javascript
More efficient way to support various kind of child property elements

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     } // setNamedItem
140     });
141    
142    
143 wakaba 1.1 JSTE.List = new JSTE.Class (function (arrayLike) {
144     this.list = arrayLike || [];
145     }, {
146     getLast: function () {
147     if (this.list.length) {
148     return this.list[this.list.length - 1];
149     } else {
150     return null;
151     }
152     }, // getLast
153    
154     forEach: function (code) {
155     var length = this.list.length;
156     for (var i = 0; i < length; i++) {
157     var r = code (this.list[i]);
158     if (r && r.stop) return r.returnValue;
159     }
160     return null;
161     }, // forEach
162 wakaba 1.4
163     numberToInteger: function () {
164     var newList = [];
165     this.forEach (function (item) {
166     if (typeof item === "number") {
167     newList.push (Math.floor (item));
168     } else {
169     newList.push (item);
170     }
171     });
172     return new this.constructor (newList);
173     }, // numberToInteger
174 wakaba 1.1
175     clone: function () {
176     var newList = [];
177     this.forEach (function (item) {
178     newList.push (item);
179     });
180     return new this.constructor (newList);
181     }, // clone
182    
183     grep: function (code) {
184     var newList = [];
185     this.forEach (function (item) {
186     if (code (item)) {
187     newList.push (item);
188     }
189     });
190     return new this.constructor (newList);
191     }, // grep
192     onlyNonNull: function () {
193     return this.grep (function (item) {
194     return item != null; /* Intentionally "!=" */
195     });
196     }, // onlyNonNull
197 wakaba 1.11
198     uniq: function (eq) {
199     if (!eq) eq = function (i1, i2) { return i1 === i2 };
200     var prevItems = [];
201     return this.grep (function (item) {
202     for (var i = 0; i < prevItems.length; i++) {
203     if (eq (item, prevItems[i])) {
204     return false;
205     }
206     }
207     prevItems.push (item);
208     return true;
209     });
210     }, // uniq
211 wakaba 1.1
212     getFirstMatch: function (code) {
213     return this.forEach (function (item) {
214     if (code (item)) {
215     return new JSTE.List.Return (item);
216     }
217     });
218     }, // getFirstMatch
219    
220     switchByElementType: function () {
221     var cases = new JSTE.List (arguments);
222     this.forEach (function (n) {
223     cases.forEach (function (c) {
224     if (c.namespaceURI == n.namespaceURI) {
225     return new JSTE.List.Return (c.execute (n));
226     }
227     });
228     });
229     }, // switchByElementType
230    
231 wakaba 1.10 // destructive
232 wakaba 1.1 push: function (item) {
233     this.list.push (item);
234     }, // push
235 wakaba 1.10
236     // destructive
237 wakaba 1.1 pushCloneOfLast: function () {
238     this.list.push (this.getLast ().clone ());
239     }, // pushCloneOfLast
240 wakaba 1.10
241     // destructive
242 wakaba 1.1 append: function (list) {
243     var self = this;
244     list.forEach (function (n) {
245     self.list.push (n);
246     });
247 wakaba 1.10 return this;
248 wakaba 1.1 }, // append
249    
250 wakaba 1.10 // destructive
251 wakaba 1.1 pop: function () {
252     return this.list.pop ();
253     }, // pop
254 wakaba 1.10
255     // destructive
256 wakaba 1.1 remove: function (removedItem) {
257     var length = this.list.length;
258     for (var i = length - 1; i >= 0; --i) {
259     var item = this.list[i];
260     if (item == removedItem) { // Intentionally "=="
261     this.list.splice (i, 1);
262     }
263     }
264     }, // remove
265 wakaba 1.10
266     // destructive
267 wakaba 1.1 clear: function () {
268     this.list.splice (0, this.list.length);
269     } // clear
270    
271     }); // List
272    
273 wakaba 1.10 JSTE.Class.addClassMethods (JSTE.List, {
274     spaceSeparated: function (v) {
275     return new JSTE.List ((v || '').split (JSTE.SpaceChars)).grep (function (v) {
276     return v.length;
277     });
278     }, // spaceSeparated
279    
280     getCommonItems: function (l1, l2, cb, eq) {
281 wakaba 1.11 if (!eq) eq = function (i1, i2) { return i1 === i2 };
282 wakaba 1.10
283     var common = new JSTE.List;
284    
285     l1 = l1.grep (function (i1) {
286     var hasI1;
287     l2 = l2.grep (function (i2) {
288     if (eq (i1, i2)) {
289     common.push (i1);
290     hasI1 = true;
291     return false;
292     } else {
293     return true;
294     }
295     });
296     return !hasI1;
297     });
298    
299     cb (common, l1, l2);
300     } // getCommonItems
301     }); // List class methods
302    
303 wakaba 1.1 JSTE.List.Return = new JSTE.Class (function (rv) {
304     this.stop = true;
305     this.returnValue = rv;
306     }, {
307    
308     }); // Return
309    
310     JSTE.List.SwitchByLocalName = new JSTE.Class (function (ns, cases, ow) {
311     this.namespaceURI = ns;
312     this.cases = cases;
313     this.otherwise = ow || function (n) { };
314     }, {
315     execute: function (n) {
316     for (var ln in this.cases) {
317     if (JSTE.Element.matchLocalName (n, ln)) {
318     return this.cases[ln] (n);
319     }
320     }
321     return this.otherwise (n);
322     }
323     });
324    
325    
326     if (!JSTE.Node) JSTE.Node = {};
327    
328     JSTE.Class.addClassMethods (JSTE.Node, {
329     querySelector: function (node, selectors) {
330     if (node.querySelector) {
331     var el;
332     try {
333     el = node.querySelector (selectors);
334     } catch (e) {
335     el = null;
336     }
337     return el;
338     } else if (window.uu && uu.css) {
339     if (selectors != "") {
340     /* NOTE: uu.css return all elements for "" or ",xxx" */
341     return uu.css (selectors, node)[0];
342     } else {
343     return null;
344     }
345     } else if (window.Ten && Ten.DOM && Ten.DOM.getElementsBySelector) {
346     return Ten.DOM.getElementsBySelector (selectors)[0];
347     } else {
348     return null;
349     }
350     }, // querySelector
351     querySelectorAll: function (node, selectors) {
352     if (node.querySelectorAll) {
353     var nl;
354     try {
355     nl = node.querySelectorAll (selectors);
356     } catch (e) {
357     nl = null;
358     }
359     return new JSTE.List (nl);
360     } else if (window.uu && uu.css) {
361     if (selectors != "") {
362 wakaba 1.11 /* NOTE: uu.css return all elements for "" or ",xxx". */
363 wakaba 1.1 return new JSTE.List (uu.css (selectors, node));
364     } else {
365     return new JSTE.List;
366     }
367     } else if (window.Ten && Ten.DOM && Ten.DOM.getElementsBySelector) {
368     return new JSTE.List (Ten.DOM.getElementsBySelector (selectors));
369     } else {
370     return new JSTE.List;
371     }
372     } // querySelectorAll
373     });
374    
375     if (!JSTE.Element) JSTE.Element = {};
376    
377     JSTE.Class.addClassMethods (JSTE.Element, {
378     getLocalName: function (el) {
379     var localName = el.localName;
380     if (!localName) {
381     localName = el.nodeName;
382     if (el.prefix) {
383     localName = localName.substring (el.prefix.length + 1);
384     }
385     }
386     return localName;
387     }, // getLocalName
388    
389     match: function (el, ns, ln) {
390     if (el.nodeType !== 1) return false;
391     if (el.namespaceURI !== ns) return false;
392     return JSTE.Element.matchLocalName (el, ln);
393     }, // match
394     matchLocalName: function (el, ln) {
395     var localName = JSTE.Element.getLocalName (el);
396     if (ln instanceof RegExp) {
397     if (!localName.match (ln)) return false;
398     } else {
399     if (localName !== ln) return false;
400     }
401     return true;
402     }, // matchLocalName
403    
404     getChildElement: function (el, ns, ln) {
405     return new JSTE.List (el.childNodes).getFirstMatch (function (item) {
406     return JSTE.Element.match (item, ns, ln);
407     });
408     }, // getChildElement
409     getChildElements: function (el, ns, ln) {
410     return new JSTE.List (el.childNodes).grep (function (item) {
411     return JSTE.Element.match (item, ns, ln);
412     });
413     }, // getChildElements
414 wakaba 1.17 getChildrenClassifiedByType: function (el) {
415     var r = new JSTE.ElementHash;
416     new JSTE.List (el.childNodes).forEach (function (n) {
417     if (n.nodeType == 1) {
418     r.getOrCreate (n.namespaceURI, JSTE.Element.getLocalName (n)).push (n);
419     } else {
420     r.getOrCreate (null, n.nodeType).push (n);
421     }
422     });
423     return r;
424     }, // getChildrenClassifiedByType
425 wakaba 1.1
426     appendText: function (el, s) {
427     return el.appendChild (el.ownerDocument.createTextNode (s));
428     }, // appendText
429    
430     createTemplate: function (doc, node) {
431     var df = doc.createDocumentFragment ();
432     new JSTE.List (node.childNodes).forEach (function (n) {
433     if (n.nodeType == 1) {
434     var c = doc.createElement (JSTE.Element.getLocalName (n));
435 wakaba 1.15 new JSTE.List (n.attributes).forEach (function (n) {
436 wakaba 1.1 c.setAttribute (n.name, n.value);
437     });
438     c.appendChild (JSTE.Element.createTemplate (doc, n));
439     df.appendChild (c);
440     } else if (n.nodeType == 3 || n.nodeType == 4) {
441     df.appendChild (doc.createTextNode (n.data));
442     }
443     });
444     return df;
445     }, // createTemplate
446    
447     hasAttribute: function (el, localName) {
448     if (el.hasAttribute) {
449     return el.hasAttribute (localName);
450     } else {
451     return el.getAttribute (localName) != null;
452     }
453     }, // hasAttribute
454    
455     getClassNames: function (el) {
456     return new JSTE.List (el.className.split (JSTE.SpaceChars));
457     }, // getClassNames
458     addClassName: function (el, newClassName) {
459     el.className = el.className + ' ' + newClassName;
460     }, // deleteClassName
461     deleteClassName: function (el, oldClassName) {
462     var classNames = el.className.split (JSTE.SpaceChars);
463     var newClasses = [];
464     for (var n in classNames) {
465     if (classNames[n] != oldClassName) {
466     newClasses.push (classNames[n]);
467     }
468     }
469     el.className = newClasses.join (' ');
470     }, // deleteClassName
471     replaceClassName: function (el, oldClassName, newClassName) {
472     var classNames = el.className.split (JSTE.SpaceChars);
473     var newClasses = [newClassName];
474     for (var n in classNames) {
475     if (classNames[n] != oldClassName) {
476     newClasses.push (classNames[n]);
477     }
478     }
479     el.className = newClasses.join (' ');
480     }, // replaceClassName
481    
482     getIds: function (el) {
483     return new JSTE.List (el.id != "" ? [el.id] : []);
484 wakaba 1.5 }, // getIds
485    
486     /*
487     NR.js <http://suika.fam.cx/www/css/noderect/NodeRect.js> must be loaded
488     before the invocation.
489     */
490     scroll: function (elements) {
491     if (!JSTE.windowLoaded) {
492     new JSTE.Observer ('load', window, function () {
493     JSTE.Element.scroll (elements);
494     });
495     return;
496     }
497    
498     var top = Infinity;
499     var left = Infinity;
500     var topEl;
501     var leftEl;
502     elements.forEach (function (el) {
503     var rect = NR.Element.getRects (el, window).borderBox;
504     if (rect.top < top) {
505     top = rect.top;
506     topEl = el;
507     }
508     if (rect.left < left) {
509     left = rect.left;
510     leftEl = el;
511     }
512     });
513    
514     if (!leftEl && !topEl) {
515     return;
516     }
517    
518     var doc = (leftEl || topEl).ownerDocument;
519 wakaba 1.1
520 wakaba 1.5 var rect = NR.View.getViewportRects (window, doc).contentBox;
521     if (rect.top <= top && top <= rect.bottom) {
522     top = rect.top;
523     }
524     if (rect.left <= left && left <= rect.right) {
525     left = rect.left;
526     }
527    
528     /*
529     Set scroll* of both <html> and <body> elements, to support all of
530     four browsers and two (or three) rendering modes. This might result
531     in confusing the user if both <html> and <body> elements have their
532     'overflow' properties specified to 'scroll'.
533    
534     Note that this code does not do a good job if the |el| is within an
535     |overflow: scroll| element.
536     */
537     doc.body.scrollTop = top;
538     doc.body.scrollLeft = left;
539     doc.documentElement.scrollTop = top;
540     doc.documentElement.scrollLeft = left;
541     } // scroll
542    
543 wakaba 1.1 }); // JSTE.Element
544    
545 wakaba 1.17 JSTE.ElementHash = new JSTE.Class (function () {
546     this.items = [];
547     }, {
548     get: function (ns, ln) {
549     ns = ns || '';
550     if (this.items[ns]) {
551     return this.items[ns].getNamedItem (ln) || new JSTE.List;
552     } else {
553     return new JSTE.List;
554     }
555     }, // get
556     getOrCreate: function (ns, ln) {
557     ns = ns || '';
558     if (this.items[ns]) {
559     var l = this.items[ns].getNamedItem (ln);
560     if (!l) this.items[ns].setNamedItem (ln, l = new JSTE.List);
561     return l;
562     } else {
563     var l;
564     this.items[ns] = new JSTE.Hash;
565     this.items[ns].setNamedItem (ln, l = new JSTE.List);
566     return l;
567     }
568     } // getOrCreate
569     }); // ElementHash
570    
571 wakaba 1.9 JSTE.XHR = new JSTE.Class (function (url, onsuccess, onerror) {
572     try {
573     this._xhr = new XMLHttpRequest ();
574     } catch (e) {
575     try {
576     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP');
577     } catch (e) {
578     try {
579     this._xhr = new ActiveXObject ('Microsoft.XMLHTTP');
580     } catch (e) {
581     try {
582     this._xhr = new ActiveXObject ('Msxml2.XMLHTTP.4.0');
583     } catch (e) {
584     this._xhr = null;
585     }
586     }
587     }
588     }
589    
590     this._url = url;
591     this._onsuccess = onsuccess || function () { };
592     this._onerror = onerror || function () { };
593     }, {
594     get: function () {
595     if (!this._xhr) return;
596    
597     var self = this;
598     this._xhr.open ('GET', this._url, true);
599     this._xhr.onreadystatechange = function () {
600     self._onreadystatechange ();
601     }; // onreadystatechange
602     this._xhr.send (null);
603     }, // get
604    
605     _onreadystatechange: function () {
606     if (this._xhr.readyState == 4) {
607     if (this.succeeded ()) {
608     this._onsuccess ();
609     } else {
610     this._onerror ();
611     }
612     }
613     }, // _onreadystatechange
614    
615     succeeded: function () {
616     return (this._xhr.status < 400);
617     }, // succeeded
618    
619     getDocument: function () {
620     return this._xhr.responseXML;
621     } // getDocument
622     }); // XHR
623    
624    
625 wakaba 1.1 /* Events: load, close, shown, hidden */
626     JSTE.Message = new JSTE.Class (function (doc, template, commandTarget) {
627     if (!doc) return;
628     this._targetDocument = doc;
629     this._template = template || doc.createDocumentFragment ();
630 wakaba 1.8
631 wakaba 1.1 this._commandTarget = commandTarget;
632 wakaba 1.8 this._availCommands = new JSTE.List;
633    
634 wakaba 1.1 this.hidden = true;
635     this.select = "";
636    
637     var e = new JSTE.Event ('load');
638     this.dispatchEvent (e);
639     }, {
640     render: function () {
641     var self = this;
642     var doc = this._targetDocument;
643    
644     var msgContainer = doc.createElement ('section');
645     msgContainer.appendChild (this._template);
646    
647 wakaba 1.7 if (this._commandTarget.canBack ()) {
648 wakaba 1.8 this._availCommands.push ({name: 'back'});
649 wakaba 1.7 }
650    
651     if (this._commandTarget.canNext ()) {
652 wakaba 1.8 this._availCommands.push ({name: 'next'});
653 wakaba 1.7 }
654 wakaba 1.1
655 wakaba 1.8 this._outermostElement = this._render (msgContainer);
656 wakaba 1.1
657     this.show ();
658     }, // render
659     _render: function (msgContainer, buttonContainer) {
660     var doc = this._targetDocument;
661    
662     var container = doc.createElement ('article');
663    
664     container.appendChild (msgContainer);
665 wakaba 1.8
666     var buttonContainer = this.createCommandButtons ();
667 wakaba 1.1 container.appendChild (buttonContainer);
668 wakaba 1.8
669 wakaba 1.1 doc.documentElement.appendChild (container);
670    
671     return container;
672     }, // _render
673 wakaba 1.8 createCommandButtons: function () {
674     var self = this;
675     var buttonContainer = this._targetDocument.createElement ('menu');
676     this._availCommands.forEach (function (cmd) {
677     var button = new JSTE.Message.Button
678     (cmd.name, self._commandTarget, cmd.name);
679     buttonContainer.appendChild (button.element);
680     });
681     return buttonContainer;
682     }, // createCommandButtons
683    
684 wakaba 1.1 remove: function () {
685     this.hide ();
686    
687     this._remove ();
688    
689     if (this._outermostElement && this._outermostElement.parentNode) {
690     this._outermostElement.parentNode.removeChild (this._outermostElement);
691     }
692    
693     var e = new JSTE.Event ("close");
694     this.dispatchEvent (e);
695     }, // remove
696     _remove: function () {
697    
698     }, // remove
699    
700     show: function () {
701     if (!this.hidden) return;
702     this.hidden = false;
703     if (this._outermostElement) {
704     JSTE.Element.replaceClassName
705     (this._outermostElement, "jste-hidden", "jste-shown");
706     }
707    
708     var e = new JSTE.Event ("shown");
709     this.dispatchEvent (e);
710     }, // show
711     hide: function () {
712     if (this.hidden) return;
713     this.hidden = true;
714     if (this._outermostElement) {
715     JSTE.Element.replaceClassName
716     (this._outermostElement, "jste-shown", "jste-hidden");
717     }
718    
719     var e = new JSTE.Event ("hidden");
720     this.dispatchEvent (e);
721     }, // hide
722    
723     setTimeout: function () {
724     /* TODO: ... */
725    
726     }
727    
728     }); // Message
729    
730 wakaba 1.7 /* TODO: button label text should refer message catalog */
731    
732 wakaba 1.1 JSTE.Message.Button =
733     new JSTE.Class (function (labelText, commandTarget, commandName, commandArgs) {
734 wakaba 1.6 this._labelText = labelText != null ? labelText : "";
735    
736 wakaba 1.1 if (commandTarget && commandTarget instanceof Function) {
737     this._command = commandTarget;
738 wakaba 1.6 this._classNames = new JSTE.List;
739 wakaba 1.1 } else if (commandTarget) {
740     this._command = function () {
741     return commandTarget.executeCommand.apply
742     (commandTarget, [commandName, commandArgs]);
743     };
744 wakaba 1.6 this._classNames = new JSTE.List (['jste-command-' + commandName]);
745 wakaba 1.1 } else {
746     this._command = function () { };
747 wakaba 1.6 this._classNames = new JSTE.List;
748 wakaba 1.1 }
749    
750 wakaba 1.6 this._createElement ();
751 wakaba 1.1 }, {
752 wakaba 1.6 _createElement: function () {
753     try {
754     this.element = document.createElement ('button');
755     this.element.setAttribute ('type', 'button');
756     } catch (e) {
757     this.element = document.createElement ('<button type=button>');
758     }
759     JSTE.Element.appendText (this.element, this._labelText);
760     this.element.className = this._classNames.list.join (' ');
761 wakaba 1.1
762 wakaba 1.6 var self = this;
763     new JSTE.Observer ("click", this.element, function (e) {
764     self._command (e);
765     });
766     } // _createElement
767 wakaba 1.1 }); // Button
768    
769     JSTE.Course = new JSTE.Class (function (doc) {
770     this._targetDocument = doc;
771    
772     this._entryPointsByURL = {};
773     this._entryPointsById = {};
774     this._entryPointsByClassName = {};
775    
776     this._stepsState = new JSTE.List ([new JSTE.Hash]);
777     this._steps = new JSTE.Hash;
778    
779     var nullState = new JSTE.Step;
780     nullState.uid = "";
781     this._steps.setNamedItem (nullState.uid, nullState);
782     this._initialStepUid = nullState.uid;
783     }, {
784 wakaba 1.10 _processStepsContent: function (el, parentSteps) {
785 wakaba 1.1 var self = this;
786     new JSTE.List (el.childNodes).switchByElementType (
787     new JSTE.List.SwitchByLocalName (JSTE.WATNS, {
788 wakaba 1.10 steps: function (n) { self._processStepsElement (n, parentSteps) },
789     step: function (n) { self._processStepElement (n, parentSteps) },
790     jump: function (n) { self._processJumpElement (n, parentSteps) },
791 wakaba 1.14 entryPoint: function (n) { self._processEntryPointElement (n, parentSteps) }
792 wakaba 1.1 })
793     );
794     }, // _processStepsContent
795 wakaba 1.10 _processStepsElement: function (e, parentSteps) {
796     var steps = new JSTE.Steps ();
797     steps.parentSteps = parentSteps;
798 wakaba 1.1 this._stepsState.pushCloneOfLast ();
799     this._stepsState.getLast ().prevStep = null;
800 wakaba 1.10 this._processStepsContent (e, steps);
801 wakaba 1.1 this._stepsState.pop ();
802     }, // _processStepsElement
803    
804 wakaba 1.14 _processEntryPointElement: function (e, parentSteps) {
805 wakaba 1.1 if (JSTE.Element.hasAttribute (e, 'url')) {
806     this.setEntryPointByURL
807     (e.getAttribute ('url'), e.getAttribute ('step'));
808     } else if (JSTE.Element.hasAttribute (e, 'root-id')) {
809     this.setEntryPointById
810     (e.getAttribute ('root-id'), e.getAttribute ('step'));
811     } else if (JSTE.Element.hasAttribute (e, 'root-class')) {
812     this.setEntryPointByClassName
813     (e.getAttribute ('root-class'), e.getAttribute ('step'));
814     }
815 wakaba 1.14 }, // _processEntryPointElement
816 wakaba 1.1 setEntryPointByURL: function (url, stepName) {
817     this._entryPointsByURL[url] = stepName || '';
818     }, // setEntryPointByURL
819     setEntryPointById: function (id, stepName) {
820     this._entryPointsById[id] = stepName || '';
821     }, // setEntryPointById
822     setEntryPointByClassName: function (className, stepName) {
823     this._entryPointsByClassName[className] = stepName || '';
824     }, // setEntryPointByClassName
825     findEntryPoint: function (doc) {
826     var self = this;
827     var td = this._targetDocument;
828     var stepName;
829    
830     var url = doc.URL;
831     if (url) {
832     stepName = self._entryPointsByURL[url];
833     if (stepName) return 'id-' + stepName;
834     }
835    
836     var docEl = td.documentElement;
837     if (docEl) {
838     var docElId = JSTE.Element.getIds (docEl).forEach (function (i) {
839     stepName = self._entryPointsById[i];
840     if (stepName) return new JSTE.List.Return (stepName);
841     });
842     if (stepName) return 'id-' + stepName;
843    
844     stepName = JSTE.Element.getClassNames (docEl).forEach (function (c) {
845     stepName = self._entryPointsByClassName[c];
846     if (stepName) return new JSTE.List.Return (stepName);
847     });
848     if (stepName) return 'id-' + stepName;
849     }
850    
851     var bodyEl = td.body;
852     if (bodyEl) {
853     var bodyElId = JSTE.Element.getIds (bodyEl).forEach (function (i) {
854     stepName = self._entryPointsById[i];
855     if (stepName) return new JSTE.List.Return (stepName);
856     });
857     if (stepName) return 'id-' + stepName;
858    
859     stepName = JSTE.Element.getClassNames (bodyEl).forEach (function (c) {
860     stepName = self._entryPointsByClassName[c];
861     if (stepName) return new JSTE.List.Return (stepName);
862     });
863     if (stepName) return 'id-' + stepName;
864     }
865    
866     return this._initialStepUid;
867     }, // findEntryPoint
868    
869 wakaba 1.10 _processStepElement: function (e, parentSteps) {
870 wakaba 1.1 var step = new JSTE.Step (e.getAttribute ('id'));
871 wakaba 1.10 step.parentSteps = parentSteps;
872 wakaba 1.1 step.setPreviousStep (this._stepsState.getLast ().prevStep);
873     step.select = e.getAttribute ('select') || "";
874     step.nextEvents.append
875 wakaba 1.10 (JSTE.List.spaceSeparated (e.getAttribute ('next-event')));
876 wakaba 1.17
877     var cs = JSTE.Element.getChildrenClassifiedByType (e);
878    
879     var msgEl = cs.get (JSTE.WATNS, 'message').list[0];
880 wakaba 1.1 if (msgEl) {
881     var msg = JSTE.Element.createTemplate (this._targetDocument, msgEl);
882     step.setMessageTemplate (msg);
883     }
884 wakaba 1.17
885     var nextEls = cs.get (JSTE.WATNS, 'next-step');
886 wakaba 1.16 if (nextEls.list.length) {
887 wakaba 1.1 nextEls.forEach (function (nextEl) {
888     step.addNextStep
889     (nextEl.getAttribute ('if'), nextEl.getAttribute ('step'));
890     });
891     this._stepsState.getLast ().prevStep = null;
892     } else {
893     this._stepsState.getLast ().prevStep = step;
894     }
895 wakaba 1.17
896 wakaba 1.1 /* TODO: @save */
897 wakaba 1.13
898     var evs = JSTE.List.spaceSeparated (e.getAttribute ('entry-event'));
899     if (evs.list.length) {
900     var jump = new JSTE.Jump (step.select, evs, step.uid);
901     if (parentSteps) parentSteps._jumps.push (jump);
902     }
903 wakaba 1.1
904     this._steps.setNamedItem (step.uid, step);
905     if (!this._initialStepUid) {
906     this._initialStepUid = step.uid;
907     }
908     }, // _processStepElement
909    
910 wakaba 1.10 _processJumpElement: function (e, parentSteps) {
911     var target = e.getAttribute ('target') || '';
912     var evs = JSTE.List.spaceSeparated (e.getAttribute ('event'));
913     var stepName = e.getAttribute ('step') || '';
914    
915     var jump = new JSTE.Jump (target, evs, 'id-' + stepName);
916     if (parentSteps) parentSteps._jumps.push (jump);
917 wakaba 1.1 }, // _processJumpElement
918    
919     getStep: function (uid) {
920     return this._steps.getNamedItem (uid);
921     } // getStep
922     }); // Course
923    
924 wakaba 1.9 JSTE.Class.addClassMethods (JSTE.Course, {
925     createFromDocument: function (doc, targetDoc) {
926     var course = new JSTE.Course (targetDoc);
927     var docEl = doc.documentElement;
928     if (!docEl) return course;
929     if (!JSTE.Element.match (docEl, JSTE.WATNS, 'course')) return course;
930 wakaba 1.10 course._processStepsContent (docEl, null);
931 wakaba 1.9 return course;
932     }, // createFromDocument
933     createFromURL: function (url, targetDoc, onload, onerror) {
934     new JSTE.XHR (url, function () {
935     var course = JSTE.Course.createFromDocument
936     (this.getDocument (), targetDoc);
937     if (onload) onload (course);
938     }, onerror).get ();
939     } // creatFromURL
940     }); // Course class methods
941 wakaba 1.1
942 wakaba 1.10 JSTE.Jump = new JSTE.Class (function (selectors, eventNames, stepUid) {
943     this.selectors = selectors;
944     this.eventNames = eventNames;
945     this.stepUid = stepUid;
946     // this.parentSteps
947     }, {
948     startObserver: function (doc, commandTarget) {
949     var self = this;
950     var observers = new JSTE.List;
951    
952     var onev = function () {
953     commandTarget.gotoStep (self.stepUid);
954     };
955    
956     JSTE.Node.querySelectorAll (doc, this.selectors).forEach
957     (function (el) {
958     self.eventNames.forEach (function (evName) {
959     var ob = new JSTE.Observer (evName, el, onev);
960     ob._stepUid = self.stepUid;
961     observers.push (ob);
962     });
963     });
964    
965     return observers;
966     } // startObserver
967     }); // Jump
968    
969     JSTE.Steps = new JSTE.Class (function () {
970     this._jumps = new JSTE.List;
971     this._jumpHandlers = new JSTE.List;
972     }, {
973     setCurrentStepByUid: function (uid) {
974     this._jumpHandlers.forEach (function (jh) {
975     if (jh._stepUid != uid && jh.disabled) {
976     jh.start ();
977     } else if (jh._stepUid == uid && !jh.disabled) {
978     jh.stop ();
979     }
980     });
981     }, // setCurrentStepByUid
982    
983     installJumps: function (doc, commandTarget) {
984     if (this._jumpHandlers.list.length) return;
985     var self = this;
986     this._jumps.forEach (function (j) {
987     self._jumpHandlers.append (j.startObserver (doc, commandTarget));
988     });
989     }, // installJumps
990    
991     uninstallJumps: function () {
992     this._jumpHandlers.forEach (function (jh) {
993     jh.stop ();
994     });
995     this._jumpHandlers.clear ();
996     } // uninstallJumps
997     }); // Steps
998    
999 wakaba 1.1 JSTE.Step = new JSTE.Class (function (id) {
1000     if (id != null && id != '') {
1001     this.uid = 'id-' + id;
1002     } else {
1003     this.uid = 'rand-' + Math.random ();
1004     }
1005     this._nextSteps = new JSTE.List;
1006     this.nextEvents = new JSTE.List;
1007     this.select = "";
1008     }, {
1009     setMessageTemplate: function (msg) {
1010     this._messageTemplate = msg;
1011     }, // setMessageTemplate
1012     hasMessage: function () {
1013     return this._messageTemplate ? true : false;
1014     }, // hasMessage
1015     createMessage: function (msg, doc, commandTarget) {
1016     var msg;
1017     if (this._messageTemplate) {
1018     var clone = JSTE.Element.createTemplate (doc, this._messageTemplate);
1019     msg = new msg (doc, clone, commandTarget);
1020     } else {
1021     msg = new msg (doc, null, commandTarget);
1022     }
1023     msg.select = this.select;
1024     return msg;
1025     }, // createMessage
1026    
1027     addNextStep: function (condition, stepId) {
1028 wakaba 1.16 if (stepId != null) this._nextSteps.push ([condition, stepId]);
1029 wakaba 1.1 }, // addNextStep
1030     setPreviousStep: function (prevStep) {
1031     if (!prevStep) return;
1032     if (prevStep._defaultNextStepUid) return;
1033     prevStep._defaultNextStepUid = this.uid;
1034     }, // setPreviousStep
1035    
1036     getNextStepUid: function (doc) {
1037     var m = this._nextSteps.getFirstMatch (function (item) {
1038     var condition = item[0];
1039     if (condition) {
1040     return JSTE.Node.querySelector (doc, condition) != null;
1041     } else {
1042     return true;
1043     }
1044     });
1045     if (m) {
1046     return 'id-' + m[1];
1047     } else if (this._defaultNextStepUid) {
1048     return this._defaultNextStepUid;
1049     } else {
1050     return null;
1051     }
1052 wakaba 1.10 }, // getNextStepUid
1053    
1054     getAncestorStepsObjects: function () {
1055     var steps = new JSTE.List;
1056     var s = this.parentSteps;
1057     while (s != null) {
1058     steps.push (s);
1059     s = s.parentSteps;
1060     }
1061     return steps;
1062     } // getAncestorStepsObjects
1063 wakaba 1.1 }); // Step
1064    
1065 wakaba 1.3 /* Events: load, error, cssomready */
1066 wakaba 1.9 JSTE.Tutorial = new JSTE.Class (function (course, doc, args) {
1067 wakaba 1.1 this._course = course;
1068     this._targetDocument = doc;
1069     this._messageClass = JSTE.Message;
1070     if (args) {
1071     if (args.messageClass) this._messageClass = args.messageClass;
1072     }
1073    
1074     this._currentMessages = new JSTE.List;
1075     this._currentObservers = new JSTE.List;
1076     this._prevStepUids = new JSTE.List;
1077 wakaba 1.10 this._currentStepsObjects = new JSTE.List;
1078 wakaba 1.1
1079     var stepUid = this._course.findEntryPoint (document);
1080     this._currentStep = this._getStepOrError (stepUid);
1081     if (this._currentStep) {
1082     var e = new JSTE.Event ('load');
1083     this.dispatchEvent (e);
1084    
1085 wakaba 1.3 var self = this;
1086     new JSTE.Observer ('cssomready', this, function () {
1087     self._renderCurrentStep ();
1088     });
1089     this._dispatchCSSOMReadyEvent ();
1090 wakaba 1.1 return this;
1091     } else {
1092     return {};
1093     }
1094     }, {
1095     _getStepOrError: function (stepUid) {
1096     var step = this._course.getStep (stepUid);
1097     if (step) {
1098     return step;
1099     } else {
1100     var e = new JSTE.Event ('error');
1101     e.errorMessage = 'Step not found';
1102     e.errorArguments = [this._currentStepUid];
1103     this.dispatchEvent (e);
1104     return null;
1105     }
1106     }, // _getStepOrError
1107    
1108     _renderCurrentStep: function () {
1109     var self = this;
1110     var step = this._currentStep;
1111    
1112     /* Message */
1113     var msg = step.createMessage
1114     (this._messageClass, this._targetDocument, this);
1115     msg.render ();
1116     this._currentMessages.push (msg);
1117    
1118     /* Next-events */
1119     var selectedNodes = JSTE.Node.querySelectorAll
1120     (this._targetDocument, step.select);
1121     var handler = function () {
1122     self.executeCommand ("next");
1123     };
1124     selectedNodes.forEach (function (node) {
1125     step.nextEvents.forEach (function (eventType) {
1126     self._currentObservers.push
1127     (new JSTE.Observer (eventType, node, handler));
1128     });
1129     });
1130 wakaba 1.10
1131     JSTE.List.getCommonItems (this._currentStepsObjects,
1132     step.getAncestorStepsObjects (),
1133     function (common, onlyInOld, onlyInNew) {
1134     common.forEach (function (item) {
1135     item.setCurrentStepByUid (step.uid);
1136     });
1137     onlyInOld.forEach (function (item) {
1138     item.uninstallJumps ();
1139     });
1140     onlyInNew.forEach (function (item) {
1141     item.installJumps (self._targetDocument, self);
1142     });
1143     self._currentStepsObjects = common.append (onlyInNew);
1144     });
1145 wakaba 1.1 }, // _renderCurrentStep
1146     clearMessages: function () {
1147     this._currentMessages.forEach (function (msg) {
1148     msg.remove ();
1149     });
1150     this._currentMessages.clear ();
1151    
1152     this._currentObservers.forEach (function (ob) {
1153     ob.stop ();
1154     });
1155     this._currentObservers.clear ();
1156     }, // clearMessages
1157 wakaba 1.10 clearStepsHandlers: function () {
1158     this._currentStepsObjects.forEach (function (item) {
1159     item.uninstallJumps ();
1160     });
1161     this._currentStepsObjects.clear ();
1162     }, // clearStepsHandlers
1163 wakaba 1.1
1164     executeCommand: function (commandName, commandArgs) {
1165     if (this[commandName]) {
1166     return this[commandName].apply (this, commandArgs || []);
1167     } else {
1168     var e = new JSTE.Event ('error');
1169     e.errorMessage = 'Command not found';
1170     e.errorArguments = [commandName];
1171     return null;
1172     }
1173     }, // executeCommand
1174 wakaba 1.7 canExecuteCommand: function (commandName, commandArgs) {
1175     if (this[commandName]) {
1176     var can = this['can' + commandName.substring (0, 1).toUpperCase ()
1177     + commandName.substring (1)];
1178     if (can) {
1179     return can.apply (this, arguments);
1180     } else {
1181     return true;
1182     }
1183     } else {
1184     return false;
1185     }
1186     }, // canExecuteCommand
1187 wakaba 1.1
1188     startTutorial: function () {
1189     this.resetVisited ();
1190    
1191     }, // startTutorial
1192     continueTutorial: function () {
1193    
1194     }, // continueTutorial
1195    
1196     saveVisited: function () {
1197    
1198     }, // saveVisited
1199     resetVisited: function () {
1200    
1201     }, // resetVisited
1202    
1203     back: function () {
1204     var prevStepUid = this._prevStepUids.pop ();
1205     var prevStep = this._getStepOrError (prevStepUid);
1206     if (prevStep) {
1207     this.clearMessages ();
1208     this._currentStep = prevStep;
1209     this._renderCurrentStep ();
1210     }
1211     }, // back
1212 wakaba 1.7 canBack: function () {
1213     return this._prevStepUids.list.length > 0;
1214     }, // canBack
1215 wakaba 1.1 next: function () {
1216     var nextStepUid = this._currentStep.getNextStepUid (this._targetDocument);
1217     var nextStep = this._getStepOrError (nextStepUid);
1218     if (nextStep) {
1219     this._prevStepUids.push (this._currentStep.uid);
1220     this.clearMessages ();
1221     this._currentStep = nextStep;
1222     this._renderCurrentStep ();
1223     }
1224 wakaba 1.3 }, // next
1225 wakaba 1.7 canNext: function () {
1226     return this._currentStep.getNextStepUid (this._targetDocument) != null;
1227     }, // canNext
1228 wakaba 1.10 gotoStep: function (uid) {
1229     var nextStep = this._getStepOrError (uid);
1230     if (nextStep) {
1231     this._prevStepUids.push (this._currentStep.uid);
1232     this.clearMessages ();
1233     this._currentStep = nextStep;
1234     this._renderCurrentStep ();
1235     }
1236     }, // gotoStep
1237 wakaba 1.3
1238     // <http://twitter.com/waka/status/1129513097>
1239     _dispatchCSSOMReadyEvent: function () {
1240     var self = this;
1241     var e = new JSTE.Event ('cssomready');
1242     if (window.opera && document.readyState != 'complete') {
1243     new JSTE.Observer ('readystatechange', document, function () {
1244     if (document.readyState == 'complete') {
1245     self.dispatchEvent (e);
1246     }
1247     });
1248     } else {
1249     this.dispatchEvent (e);
1250     }
1251     } // dispatchCSSOMReadyEvent
1252    
1253 wakaba 1.1 }); // Tutorial
1254 wakaba 1.9
1255     JSTE.Class.addClassMethods (JSTE.Tutorial, {
1256 wakaba 1.12 createFromURL: function (url, doc, args, onload) {
1257 wakaba 1.9 JSTE.Course.createFromURL (url, doc, function (course) {
1258 wakaba 1.12 var tutorial = new JSTE.Tutorial (course, doc, args);
1259     if (onload) onload (tutorial);
1260 wakaba 1.9 });
1261     } // createFromURL
1262     }); // Tutorial class methods
1263    
1264    
1265 wakaba 1.5
1266     if (JSTE.onLoadFunctions) {
1267     new JSTE.List (JSTE.onLoadFunctions).forEach (function (code) {
1268     code ();
1269     });
1270     }
1271    
1272     if (JSTE.isDynamicallyLoaded) {
1273     JSTE.windowLoaded = true;
1274     }
1275 wakaba 1.2
1276     /* ***** BEGIN LICENSE BLOCK *****
1277     * Copyright 2008-2009 Wakaba <w@suika.fam.cx>. All rights reserved.
1278     *
1279     * This program is free software; you can redistribute it and/or
1280     * modify it under the same terms as Perl itself.
1281     *
1282     * Alternatively, the contents of this file may be used
1283     * under the following terms (the "MPL/GPL/LGPL"),
1284     * in which case the provisions of the MPL/GPL/LGPL are applicable instead
1285     * of those above. If you wish to allow use of your version of this file only
1286     * under the terms of the MPL/GPL/LGPL, and not to allow others to
1287     * use your version of this file under the terms of the Perl, indicate your
1288     * decision by deleting the provisions above and replace them with the notice
1289     * and other provisions required by the MPL/GPL/LGPL. If you do not delete
1290     * the provisions above, a recipient may use your version of this file under
1291     * the terms of any one of the Perl or the MPL/GPL/LGPL.
1292     *
1293     * "MPL/GPL/LGPL":
1294     *
1295     * Version: MPL 1.1/GPL 2.0/LGPL 2.1
1296     *
1297     * The contents of this file are subject to the Mozilla Public License Version
1298     * 1.1 (the "License"); you may not use this file except in compliance with
1299     * the License. You may obtain a copy of the License at
1300     * <http://www.mozilla.org/MPL/>
1301     *
1302     * Software distributed under the License is distributed on an "AS IS" basis,
1303     * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
1304     * for the specific language governing rights and limitations under the
1305     * License.
1306     *
1307     * The Original Code is JSTE code.
1308     *
1309     * The Initial Developer of the Original Code is Wakaba.
1310     * Portions created by the Initial Developer are Copyright (C) 2008
1311     * the Initial Developer. All Rights Reserved.
1312     *
1313     * Contributor(s):
1314     * Wakaba <w@suika.fam.cx>
1315     *
1316     * Alternatively, the contents of this file may be used under the terms of
1317     * either the GNU General Public License Version 2 or later (the "GPL"), or
1318     * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
1319     * in which case the provisions of the GPL or the LGPL are applicable instead
1320     * of those above. If you wish to allow use of your version of this file only
1321     * under the terms of either the GPL or the LGPL, and not to allow others to
1322     * use your version of this file under the terms of the MPL, indicate your
1323     * decision by deleting the provisions above and replace them with the notice
1324     * and other provisions required by the LGPL or the GPL. If you do not delete
1325     * the provisions above, a recipient may use your version of this file under
1326     * the terms of any one of the MPL, the GPL or the LGPL.
1327     *
1328     * ***** END LICENSE BLOCK ***** */

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24