source: branches/feature-module-update/html/test/kakinaka/js/logger/logger.js @ 15079

Revision 15079, 37.9 KB checked in by nanasess, 17 years ago (diff)

svn:mime-type application/x-httpd-php; charset=UTF-8 設定

  • Property svn:mime-type set to application/x-httpd-php; charset=UTF-8
Line 
1/*
2Copyright (c) 2006, Yahoo! Inc. All rights reserved.
3Code licensed under the BSD License:
4http://developer.yahoo.com/yui/license.txt
5version: 0.11.3
6*/
7
8/****************************************************************************/
9/****************************************************************************/
10/****************************************************************************/
11/**
12 * Singleton providing core logging functionality. Saves logs written through the
13 * global YAHOO.log function or written by LogWriter. Provides access to logs
14 * for reading by LogReader. Log messages can be automatically output to browser
15 * console such as the Firebug extension to Firefox or Safari's JavaScript
16 * console, if present.
17 *
18 * requires YAHOO.util.Event Event utility
19 */
20YAHOO.widget.Logger = {
21    // Initialize members
22    loggerEnabled: true,
23    _browserConsoleEnabled: false,
24    categories: ["info","warn","error","time","window"],
25    sources: ["global"],
26    _stack: [], // holds all log msgs
27    maxStackEntries: 5,
28    _startTime: new Date().getTime(), // static start timestamp
29    _lastTime: null // timestamp of last logged message
30};
31
32/***************************************************************************
33 * Events
34 ***************************************************************************/
35/**
36 * Fired when a new category has been created. Subscribers receive the following
37 * array:<br>
38 *     - args[0] The category name
39 */
40YAHOO.widget.Logger.categoryCreateEvent = new YAHOO.util.CustomEvent("categoryCreate", this, true);
41
42/**
43 * Fired when a new source has been named. Subscribers receive the following
44 * array:<br>
45 *     - args[0] The source name
46 */
47YAHOO.widget.Logger.sourceCreateEvent = new YAHOO.util.CustomEvent("sourceCreate", this, true);
48
49/**
50 * Fired when a new log message has been created. Subscribers receive the
51 * following array:<br>
52 *     - args[0] The log message
53 */
54YAHOO.widget.Logger.newLogEvent = new YAHOO.util.CustomEvent("newLog", this, true);
55
56/**
57 * Fired when the Logger has been reset has been created.
58 */
59YAHOO.widget.Logger.logResetEvent = new YAHOO.util.CustomEvent("logReset", this, true);
60
61/***************************************************************************
62 * Public methods
63 ***************************************************************************/
64/**
65 * Saves a log message to the stack and fires newLogEvent. If the log message is
66 * assigned to an unknown category, creates a new category. If the log message is
67 * from an unknown source, creates a new source.  If browser console is enabled,
68 * outputs the log message to browser console.
69 *
70 * @param {string} sMsg The log message
71 * @param {string} sCategory Category of log message, or null
72 * @param {string} sSource Source of LogWriter, or null if global
73 */
74YAHOO.widget.Logger.log = function(sMsg, sCategory, sSource) {
75    if(this.loggerEnabled) {
76        if(!sCategory) {
77            sCategory = "info"; // default category
78        }
79        else {
80            sCategory = sCategory.toLocaleLowerCase();
81            if(this._isNewCategory(sCategory)) {
82                this._createNewCategory(sCategory);
83            }
84        }
85        var sClass = "global"; // default source
86        var sDetail = null;
87        if(sSource) {
88            var spaceIndex = sSource.indexOf(" ");
89            if(spaceIndex > 0) {
90                sClass = sSource.substring(0,spaceIndex);// substring until first space
91                sDetail = sSource.substring(spaceIndex,sSource.length);// the rest of the source
92            }
93            else {
94                sClass = sSource;
95            }
96            if(this._isNewSource(sClass)) {
97                this._createNewSource(sClass);
98            }
99        }
100
101        var timestamp = new Date();
102        var logEntry = {
103            time: timestamp,
104            category: sCategory,
105            source: sClass,
106            sourceDetail: sDetail,
107            msg: sMsg
108        };
109
110        var stack = this._stack;
111        var maxStackEntries = this.maxStackEntries;
112        if(maxStackEntries && !isNaN(maxStackEntries) && (stack.length >= maxStackEntries)) {
113            stack.shift();
114        }
115        stack.push(logEntry);
116        this.newLogEvent.fire(logEntry);
117
118        if(this._browserConsoleEnabled) {
119            this._printToBrowserConsole(logEntry);
120        }
121        return true;
122    }
123    else {
124        return false;
125    }
126};
127
128/**
129 * Resets internal stack and startTime, enables Logger, and fires logResetEvent.
130 *
131 */
132YAHOO.widget.Logger.reset = function() {
133    this._stack = [];
134    this._startTime = new Date().getTime();
135    this.loggerEnabled = true;
136    this.log("Logger reset");
137    this.logResetEvent.fire();
138};
139
140/**
141 * Public accessor to internal stack of log messages.
142 *
143 * @return {array} Array of log messages.
144 */
145YAHOO.widget.Logger.getStack = function() {
146    return this._stack;
147};
148
149/**
150 * Public accessor to internal start time.
151 *
152 * @return {date} Internal date of when Logger singleton was initialized.
153 */
154YAHOO.widget.Logger.getStartTime = function() {
155    return this._startTime;
156};
157
158/**
159 * Disables output to the browser's global console.log() function, which is used
160 * by the Firebug extension to Firefox as well as Safari.
161 */
162YAHOO.widget.Logger.disableBrowserConsole = function() {
163    YAHOO.log("Logger output to the function console.log() has been disabled.");
164    this._browserConsoleEnabled = false;
165};
166
167/**
168 * Enables output to the browser's global console.log() function, which is used
169 * by the Firebug extension to Firefox as well as Safari.
170 */
171YAHOO.widget.Logger.enableBrowserConsole = function() {
172    this._browserConsoleEnabled = true;
173    YAHOO.log("Logger output to the function console.log() has been enabled.");
174};
175
176/***************************************************************************
177 * Private methods
178 ***************************************************************************/
179/**
180 * Creates a new category of log messages and fires categoryCreateEvent.
181 *
182 * @param {string} category Category name
183 * @private
184 */
185YAHOO.widget.Logger._createNewCategory = function(category) {
186    this.categories.push(category);
187    this.categoryCreateEvent.fire(category);
188};
189
190/**
191 * Checks to see if a category has already been created.
192 *
193 * @param {string} category Category name
194 * @return {boolean} Returns true if category is unknown, else returns false
195 * @private
196 */
197YAHOO.widget.Logger._isNewCategory = function(category) {
198    for(var i=0; i < this.categories.length; i++) {
199        if(category == this.categories[i]) {
200            return false;
201        }
202    }
203    return true;
204};
205
206/**
207 * Creates a new source of log messages and fires sourceCreateEvent.
208 *
209 * @param {string} source Source name
210 * @private
211 */
212YAHOO.widget.Logger._createNewSource = function(source) {
213    this.sources.push(source);
214    this.sourceCreateEvent.fire(source);
215};
216
217/**
218 * Checks to see if a source has already been created.
219 *
220 * @param {string} source Source name
221 * @return {boolean} Returns true if source is unknown, else returns false
222 * @private
223 */
224YAHOO.widget.Logger._isNewSource = function(source) {
225    if(source) {
226        for(var i=0; i < this.sources.length; i++) {
227            if(source == this.sources[i]) {
228                return false;
229            }
230        }
231        return true;
232    }
233};
234
235/**
236 * Outputs a log message to global console.log() function.
237 *
238 * @param {object} entry Log entry object
239 * @private
240 */
241YAHOO.widget.Logger._printToBrowserConsole = function(entry) {
242    if(window.console && console.log) {
243        var category = entry.category;
244        var label = entry.category.substring(0,4).toUpperCase();
245
246        var time = entry.time;
247        if (time.toLocaleTimeString) {
248            var localTime  = time.toLocaleTimeString();
249        }
250        else {
251            localTime = time.toString();
252        }
253
254        var msecs = time.getTime();
255        var elapsedTime = (YAHOO.widget.Logger._lastTime) ?
256            (msecs - YAHOO.widget.Logger._lastTime) : 0;
257        YAHOO.widget.Logger._lastTime = msecs;
258
259        var output =
260            localTime + " (" +
261            elapsedTime + "ms): " +
262            entry.source + ": " +
263            entry.msg;
264
265        console.log(output);
266    }
267};
268
269/***************************************************************************
270 * Private event handlers
271 ***************************************************************************/
272/**
273 * Handles logging of messages due to window error events.
274 *
275 * @param {string} msg The error message
276 * @param {string} url URL of the error
277 * @param {string} line Line number of the error
278 * @private
279 */
280YAHOO.widget.Logger._onWindowError = function(msg,url,line) {
281    // Logger is not in scope of this event handler
282    try {
283        YAHOO.widget.Logger.log(msg+' ('+url+', line '+line+')', "window");
284        if(YAHOO.widget.Logger._origOnWindowError) {
285            YAHOO.widget.Logger._origOnWindowError();
286        }
287    }
288    catch(e) {
289        return false;
290    }
291};
292
293/**
294 * Handle native JavaScript errors
295 */
296//NB: Not all browsers support the window.onerror event
297if(window.onerror) {
298    // Save any previously defined handler to call
299    YAHOO.widget.Logger._origOnWindowError = window.onerror;
300}
301window.onerror = YAHOO.widget.Logger._onWindowError;
302
303/**
304 * First log
305 */
306YAHOO.widget.Logger.log("Logger initialized");
307
308/****************************************************************************/
309/****************************************************************************/
310/****************************************************************************/
311/**
312 * Class providing ability to log messages through YAHOO.widget.Logger from a
313 * named source.
314 *
315 * @constructor
316 * @param {string} sSource Source of LogWriter instance
317 */
318YAHOO.widget.LogWriter = function(sSource) {
319    if(!sSource) {
320        YAHOO.log("Could not instantiate LogWriter due to invalid source.", "error", "LogWriter");
321        return;
322    }
323    this._source = sSource;
324 };
325
326/***************************************************************************
327 * Public methods
328 ***************************************************************************/
329 /**
330 * Public accessor to the unique name of the LogWriter instance.
331 *
332 * @return {string} Unique name of the LogWriter instance
333 */
334YAHOO.widget.LogWriter.prototype.toString = function() {
335    return "LogWriter " + this._sSource;
336};
337
338/**
339 * Logs a message attached to the source of the LogWriter.
340 *
341 * @param {string} sMsg The log message
342 * @param {string} sCategory Category name
343 */
344YAHOO.widget.LogWriter.prototype.log = function(sMsg, sCategory) {
345    YAHOO.widget.Logger.log(sMsg, sCategory, this._source);
346};
347
348/**
349 * Public accessor to get the source name.
350 *
351 * @return {string} The LogWriter source
352 */
353YAHOO.widget.LogWriter.prototype.getSource = function() {
354    return this._sSource;
355};
356
357/**
358 * Public accessor to set the source name.
359 *
360 * @param {string} sSource Source of LogWriter instance
361 */
362YAHOO.widget.LogWriter.prototype.setSource = function(sSource) {
363    if(!sSource) {
364        YAHOO.log("Could not set source due to invalid source.", "error", this.toString());
365        return;
366    }
367    else {
368        this._sSource = sSource;
369    }
370};
371/***************************************************************************
372 * Private members
373 ***************************************************************************/
374/**
375 * Source of the log writer instance.
376 *
377 * @type string
378 * @private
379 */
380YAHOO.widget.LogWriter.prototype._source = null;
381
382
383
384/****************************************************************************/
385/****************************************************************************/
386/****************************************************************************/
387
388/**
389 * Class providing UI to read messages logged to YAHOO.widget.Logger.
390 *
391 * requires YAHOO.util.Dom DOM utility
392 * requires YAHOO.util.Event Event utility
393 * optional YAHOO.util.DragDrop Drag and drop utility
394 *
395 * @constructor
396 * @param {el or ID} containerEl DOM element object or ID of container to wrap reader UI
397 * @param {object} oConfig Optional object literal of configuration params
398 */
399YAHOO.widget.LogReader = function(containerEl, oConfig) {
400    var oSelf = this;
401    this._sName = YAHOO.widget.LogReader._index;
402    YAHOO.widget.LogReader._index++;
403
404    // Parse config vars here
405    if (typeof oConfig == "object") {
406        for(var param in oConfig) {
407            this[param] = oConfig[param];
408        }
409    }
410
411    // Attach container...
412    if(containerEl) {
413        if(typeof containerEl == "string") {
414            this._containerEl = document.getElementById(containerEl);
415        }
416        else if(containerEl.tagName) {
417            this._containerEl = containerEl;
418        }
419        this._containerEl.className = "yui-log";
420    }
421    // ...or create container from scratch
422    if(!this._containerEl) {
423        if(YAHOO.widget.LogReader._defaultContainerEl) {
424            this._containerEl =  YAHOO.widget.LogReader._defaultContainerEl;
425        }
426        else {
427            this._containerEl = document.body.appendChild(document.createElement("div"));
428            this._containerEl.id = "yui-log";
429            this._containerEl.className = "yui-log";
430
431            YAHOO.widget.LogReader._defaultContainerEl = this._containerEl;
432        }
433
434        // If implementer has provided container values, trust and set those
435        var containerStyle = this._containerEl.style;
436        if(this.width) {
437            containerStyle.width = this.width;
438        }
439        if(this.left) {
440            containerStyle.left = this.left;
441        }
442        if(this.right) {
443            containerStyle.right = this.right;
444        }
445        if(this.bottom) {
446            containerStyle.bottom = this.bottom;
447        }
448        if(this.top) {
449            containerStyle.top = this.top;
450        }
451        if(this.fontSize) {
452            containerStyle.fontSize = this.fontSize;
453        }
454    }
455
456    if(this._containerEl) {
457        // Create header
458        if(!this._hdEl) {
459            this._hdEl = this._containerEl.appendChild(document.createElement("div"));
460            this._hdEl.id = "yui-log-hd" + this._sName;
461            this._hdEl.className = "yui-log-hd";
462
463            this._collapseEl = this._hdEl.appendChild(document.createElement("div"));
464            this._collapseEl.className = "yui-log-btns";
465
466            this._collapseBtn = document.createElement("input");
467            this._collapseBtn.type = "button";
468            this._collapseBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");
469            this._collapseBtn.className = "yui-log-button";
470            this._collapseBtn.value = "Collapse";
471            this._collapseBtn = this._collapseEl.appendChild(this._collapseBtn);
472            YAHOO.util.Event.addListener(oSelf._collapseBtn,'click',oSelf._onClickCollapseBtn,oSelf);
473
474            this._title = this._hdEl.appendChild(document.createElement("h4"));
475            this._title.innerHTML = "Logger Console";
476
477            // If Drag and Drop utility is available...
478            // ...and this container was created from scratch...
479            // ...then make the header draggable
480            if(YAHOO.util.DD &&
481            (YAHOO.widget.LogReader._defaultContainerEl == this._containerEl)) {
482                var ylog_dd = new YAHOO.util.DD(this._containerEl.id);
483                ylog_dd.setHandleElId(this._hdEl.id);
484                this._hdEl.style.cursor = "move";
485            }
486        }
487        // Ceate console
488        if(!this._consoleEl) {
489            this._consoleEl = this._containerEl.appendChild(document.createElement("div"));
490            this._consoleEl.className = "yui-log-bd";
491
492            // If implementer has provided console, trust and set those
493            if(this.height) {
494                this._consoleEl.style.height = this.height;
495            }
496        }
497        // Don't create footer if disabled
498        if(!this._ftEl && this.footerEnabled) {
499            this._ftEl = this._containerEl.appendChild(document.createElement("div"));
500            this._ftEl.className = "yui-log-ft";
501
502            this._btnsEl = this._ftEl.appendChild(document.createElement("div"));
503            this._btnsEl.className = "yui-log-btns";
504
505            this._pauseBtn = document.createElement("input");
506            this._pauseBtn.type = "button";
507            this._pauseBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");
508            this._pauseBtn.className = "yui-log-button";
509            this._pauseBtn.value = "Pause";
510            this._pauseBtn = this._btnsEl.appendChild(this._pauseBtn);
511            YAHOO.util.Event.addListener(oSelf._pauseBtn,'click',oSelf._onClickPauseBtn,oSelf);
512
513            this._clearBtn = document.createElement("input");
514            this._clearBtn.type = "button";
515            this._clearBtn.style.fontSize = YAHOO.util.Dom.getStyle(this._containerEl,"fontSize");
516            this._clearBtn.className = "yui-log-button";
517            this._clearBtn.value = "Clear";
518            this._clearBtn = this._btnsEl.appendChild(this._clearBtn);
519            YAHOO.util.Event.addListener(oSelf._clearBtn,'click',oSelf._onClickClearBtn,oSelf);
520
521            this._categoryFiltersEl = this._ftEl.appendChild(document.createElement("div"));
522            this._categoryFiltersEl.className = "yui-log-categoryfilters";
523            this._sourceFiltersEl = this._ftEl.appendChild(document.createElement("div"));
524            this._sourceFiltersEl.className = "yui-log-sourcefilters";
525        }
526    }
527
528    // Initialize internal vars
529    if(!this._buffer) {
530        this._buffer = []; // output buffer
531    }
532    this._lastTime = YAHOO.widget.Logger.getStartTime(); // timestamp of last log message to console
533   
534    // Subscribe to Logger custom events
535    YAHOO.widget.Logger.newLogEvent.subscribe(this._onNewLog, this);
536    YAHOO.widget.Logger.logResetEvent.subscribe(this._onReset, this);
537
538    // Initialize category filters
539    this._categoryFilters = [];
540    var catsLen = YAHOO.widget.Logger.categories.length;
541    if(this._categoryFiltersEl) {
542        for(var i=0; i < catsLen; i++) {
543            this._createCategoryCheckbox(YAHOO.widget.Logger.categories[i]);
544        }
545    }
546    // Initialize source filters
547    this._sourceFilters = [];
548    var sourcesLen = YAHOO.widget.Logger.sources.length;
549    if(this._sourceFiltersEl) {
550        for(var j=0; j < sourcesLen; j++) {
551            this._createSourceCheckbox(YAHOO.widget.Logger.sources[j]);
552        }
553    }
554    YAHOO.widget.Logger.categoryCreateEvent.subscribe(this._onCategoryCreate, this);
555    YAHOO.widget.Logger.sourceCreateEvent.subscribe(this._onSourceCreate, this);
556
557    this._filterLogs();
558    YAHOO.log("LogReader initialized", null, this.toString());
559};
560
561/***************************************************************************
562 * Public members
563 ***************************************************************************/
564/**
565 * Whether or not the log reader is enabled to output log messages. Default:
566 * true.
567 *
568 * @type boolean
569 */
570YAHOO.widget.LogReader.prototype.logReaderEnabled = true;
571
572/**
573 * Public member to access CSS width of the log reader container.
574 *
575 * @type string
576 */
577YAHOO.widget.LogReader.prototype.width = null;
578
579/**
580 * Public member to access CSS height of the log reader container.
581 *
582 * @type string
583 */
584YAHOO.widget.LogReader.prototype.height = null;
585
586/**
587 * Public member to access CSS top position of the log reader container.
588 *
589 * @type string
590 */
591YAHOO.widget.LogReader.prototype.top = null;
592
593/**
594 * Public member to access CSS left position of the log reader container.
595 *
596 * @type string
597 */
598YAHOO.widget.LogReader.prototype.left = null;
599
600/**
601 * Public member to access CSS right position of the log reader container.
602 *
603 * @type string
604 */
605YAHOO.widget.LogReader.prototype.right = null;
606
607/**
608 * Public member to access CSS bottom position of the log reader container.
609 *
610 * @type string
611 */
612YAHOO.widget.LogReader.prototype.bottom = null;
613
614/**
615 * Public member to access CSS font size of the log reader container.
616 *
617 * @type string
618 */
619YAHOO.widget.LogReader.prototype.fontSize = null;
620
621/**
622 * Whether or not the footer UI is enabled for the log reader. Default: true.
623 *
624 * @type boolean
625 */
626YAHOO.widget.LogReader.prototype.footerEnabled = true;
627
628/**
629 * Whether or not output is verbose (more readable). Setting to true will make
630 * output more compact (less readable). Default: true.
631 *
632 * @type boolean
633 */
634YAHOO.widget.LogReader.prototype.verboseOutput = true;
635
636/**
637 * Whether or not newest message is printed on top. Default: true.
638 *
639 * @type boolean
640 */
641YAHOO.widget.LogReader.prototype.newestOnTop = true;
642
643/**
644 * Maximum number of messages a LogReader console will display. Default: 500;
645 *
646 * @type number
647 */
648YAHOO.widget.LogReader.prototype.thresholdMax = 500;
649
650/**
651 * When a LogReader console reaches its thresholdMax, it will clear out messages
652 * and print out the latest thresholdMin number of messages. Default: 100;
653 *
654 * @type number
655 */
656YAHOO.widget.LogReader.prototype.thresholdMin = 100;
657
658/***************************************************************************
659 * Public methods
660 ***************************************************************************/
661 /**
662 * Public accessor to the unique name of the LogReader instance.
663 *
664 * @return {string} Unique name of the LogReader instance
665 */
666YAHOO.widget.LogReader.prototype.toString = function() {
667    return "LogReader instance" + this._sName;
668};
669/**
670 * Pauses output of log messages. While paused, log messages are not lost, but
671 * get saved to a buffer and then output upon resume of log reader.
672 */
673YAHOO.widget.LogReader.prototype.pause = function() {
674    this._timeout = null;
675    this.logReaderEnabled = false;
676};
677
678/**
679 * Resumes output of log messages, including outputting any log messages that
680 * have been saved to buffer while paused.
681 */
682YAHOO.widget.LogReader.prototype.resume = function() {
683    this.logReaderEnabled = true;
684    this._printBuffer();
685};
686
687/**
688 * Hides UI of log reader. Logging functionality is not disrupted.
689 */
690YAHOO.widget.LogReader.prototype.hide = function() {
691    this._containerEl.style.display = "none";
692};
693
694/**
695 * Shows UI of log reader. Logging functionality is not disrupted.
696 */
697YAHOO.widget.LogReader.prototype.show = function() {
698    this._containerEl.style.display = "block";
699};
700
701/**
702 * Updates title to given string.
703 *
704 * @param {string} sTitle String to display in log reader's title bar.
705 */
706YAHOO.widget.LogReader.prototype.setTitle = function(sTitle) {
707    this._title.innerHTML = this._HTML2Text(sTitle);
708};
709 /***************************************************************************
710 * Private members
711 ***************************************************************************/
712/**
713 * Internal class member to index multiple log reader instances.
714 *
715 * @type number
716 * @private
717 */
718YAHOO.widget.LogReader._index = 0;
719
720/**
721 * Name of LogReader instance.
722 *
723 * @type string
724 * @private
725 */
726YAHOO.widget.LogReader.prototype._sName = null;
727
728/**
729 * A class member shared by all log readers if a container needs to be
730 * created during instantiation. Will be null if a container element never needs to
731 * be created on the fly, such as when the implementer passes in their own element.
732 *
733 * @type HTMLElement
734 * @private
735 */
736YAHOO.widget.LogReader._defaultContainerEl = null;
737
738/**
739 * Buffer of log messages for batch output.
740 *
741 * @type array
742 * @private
743 */
744YAHOO.widget.LogReader.prototype._buffer = null;
745
746/**
747 * Number of log messages output to console.
748 *
749 * @type number
750 * @private
751 */
752YAHOO.widget.LogReader.prototype._consoleMsgCount = 0;
753
754/**
755 * Date of last output log message.
756 *
757 * @type date
758 * @private
759 */
760YAHOO.widget.LogReader.prototype._lastTime = null;
761
762/**
763 * Batched output timeout ID.
764 *
765 * @type number
766 * @private
767 */
768YAHOO.widget.LogReader.prototype._timeout = null;
769
770/**
771 * Array of filters for log message categories.
772 *
773 * @type array
774 * @private
775 */
776YAHOO.widget.LogReader.prototype._categoryFilters = null;
777
778/**
779 * Array of filters for log message sources.
780 *
781 * @type array
782 * @private
783 */
784YAHOO.widget.LogReader.prototype._sourceFilters = null;
785
786/**
787 * Log reader container element.
788 *
789 * @type HTMLElement
790 * @private
791 */
792YAHOO.widget.LogReader.prototype._containerEl = null;
793
794/**
795 * Log reader header element.
796 *
797 * @type HTMLElement
798 * @private
799 */
800YAHOO.widget.LogReader.prototype._hdEl = null;
801
802/**
803 * Log reader collapse element.
804 *
805 * @type HTMLElement
806 * @private
807 */
808YAHOO.widget.LogReader.prototype._collapseEl = null;
809
810/**
811 * Log reader collapse button element.
812 *
813 * @type HTMLElement
814 * @private
815 */
816YAHOO.widget.LogReader.prototype._collapseBtn = null;
817
818/**
819 * Log reader title header element.
820 *
821 * @type HTMLElement
822 * @private
823 */
824YAHOO.widget.LogReader.prototype._title = null;
825
826/**
827 * Log reader console element.
828 *
829 * @type HTMLElement
830 * @private
831 */
832YAHOO.widget.LogReader.prototype._consoleEl = null;
833
834/**
835 * Log reader footer element.
836 *
837 * @type HTMLElement
838 * @private
839 */
840YAHOO.widget.LogReader.prototype._ftEl = null;
841
842/**
843 * Log reader buttons container element.
844 *
845 * @type HTMLElement
846 * @private
847 */
848YAHOO.widget.LogReader.prototype._btnsEl = null;
849
850/**
851 * Container element for log reader category filter checkboxes.
852 *
853 * @type HTMLElement
854 * @private
855 */
856YAHOO.widget.LogReader.prototype._categoryFiltersEl = null;
857
858/**
859 * Container element for log reader source filter checkboxes.
860 *
861 * @type HTMLElement
862 * @private
863 */
864YAHOO.widget.LogReader.prototype._sourceFiltersEl = null;
865
866/**
867 * Log reader pause button element.
868 *
869 * @type HTMLElement
870 * @private
871 */
872YAHOO.widget.LogReader.prototype._pauseBtn = null;
873
874/**
875 * Clear button element.
876 *
877 * @type HTMLElement
878 * @private
879 */
880YAHOO.widget.LogReader.prototype._clearBtn = null;
881/***************************************************************************
882 * Private methods
883 ***************************************************************************/
884/**
885 * Creates the UI for a category filter in the log reader footer element.
886 *
887 * @param {string} category Category name
888 * @private
889 */
890YAHOO.widget.LogReader.prototype._createCategoryCheckbox = function(category) {
891    var oSelf = this;
892
893    if(this._ftEl) {
894        var parentEl = this._categoryFiltersEl;
895        var filters = this._categoryFilters;
896
897        var filterEl = parentEl.appendChild(document.createElement("span"));
898        filterEl.className = "yui-log-filtergrp";
899            // Append el at the end so IE 5.5 can set "type" attribute
900            // and THEN set checked property
901            var categoryChk = document.createElement("input");
902            categoryChk.id = "yui-log-filter-" + category + this._sName;
903            categoryChk.className = "yui-log-filter-" + category;
904            categoryChk.type = "checkbox";
905            categoryChk.category = category;
906            categoryChk = filterEl.appendChild(categoryChk);
907            categoryChk.checked = true;
908
909            // Add this checked filter to the internal array of filters
910            filters.push(category);
911            // Subscribe to the click event
912            YAHOO.util.Event.addListener(categoryChk,'click',oSelf._onCheckCategory,oSelf);
913
914            // Create and class the text label
915            var categoryChkLbl = filterEl.appendChild(document.createElement("label"));
916            categoryChkLbl.htmlFor = categoryChk.id;
917            categoryChkLbl.className = category;
918            categoryChkLbl.innerHTML = category;
919    }
920};
921
922YAHOO.widget.LogReader.prototype._createSourceCheckbox = function(source) {
923    var oSelf = this;
924
925    if(this._ftEl) {
926        var parentEl = this._sourceFiltersEl;
927        var filters = this._sourceFilters;
928
929        var filterEl = parentEl.appendChild(document.createElement("span"));
930        filterEl.className = "yui-log-filtergrp";
931
932        // Append el at the end so IE 5.5 can set "type" attribute
933        // and THEN set checked property
934        var sourceChk = document.createElement("input");
935        sourceChk.id = "yui-log-filter" + source + this._sName;
936        sourceChk.className = "yui-log-filter" + source;
937        sourceChk.type = "checkbox";
938        sourceChk.source = source;
939        sourceChk = filterEl.appendChild(sourceChk);
940        sourceChk.checked = true;
941
942        // Add this checked filter to the internal array of filters
943        filters.push(source);
944        // Subscribe to the click event
945        YAHOO.util.Event.addListener(sourceChk,'click',oSelf._onCheckSource,oSelf);
946
947        // Create and class the text label
948        var sourceChkLbl = filterEl.appendChild(document.createElement("label"));
949        sourceChkLbl.htmlFor = sourceChk.id;
950        sourceChkLbl.className = source;
951        sourceChkLbl.innerHTML = source;
952    }
953};
954
955/**
956 * Reprints all log messages in the stack through filters.
957 *
958 * @private
959 */
960YAHOO.widget.LogReader.prototype._filterLogs = function() {
961    // Reprint stack with new filters
962    if (this._consoleEl !== null) {
963        this._clearConsole();
964        this._printToConsole(YAHOO.widget.Logger.getStack());
965    }
966};
967
968/**
969 * Clears all outputted log messages from the console and resets the time of the
970 * last output log message.
971 *
972 * @private
973 */
974YAHOO.widget.LogReader.prototype._clearConsole = function() {
975    // Clear the buffer of any pending messages
976    this._timeout = null;
977    this._buffer = [];
978    this._consoleMsgCount = 0;
979
980    // Reset the rolling timer
981    this._lastTime = YAHOO.widget.Logger.getStartTime();
982
983    var consoleEl = this._consoleEl;
984    while(consoleEl.hasChildNodes()) {
985        consoleEl.removeChild(consoleEl.firstChild);
986    }
987};
988
989/**
990 * Sends buffer of log messages to output and clears buffer.
991 *
992 * @private
993 */
994YAHOO.widget.LogReader.prototype._printBuffer = function() {
995    this._timeout = null;
996
997    if(this._consoleEl !== null) {
998        var thresholdMax = this.thresholdMax;
999        thresholdMax = (thresholdMax && !isNaN(thresholdMax)) ? thresholdMax : 500;
1000        if(this._consoleMsgCount < thresholdMax) {
1001            var entries = [];
1002            for (var i=0; i<this._buffer.length; i++) {
1003                entries[i] = this._buffer[i];
1004            }
1005            this._buffer = [];
1006            this._printToConsole(entries);
1007        }
1008        else {
1009            this._filterLogs();
1010        }
1011       
1012        if(!this.newestOnTop) {
1013            this._consoleEl.scrollTop = this._consoleEl.scrollHeight;
1014        }
1015    }
1016};
1017
1018/**
1019 * Cycles through an array of log messages, and outputs each one to the console
1020 * if its category has not been filtered out.
1021 *
1022 * @param {array} aEntries
1023 * @private
1024 */
1025YAHOO.widget.LogReader.prototype._printToConsole = function(aEntries) {
1026    // Manage the number of messages displayed in the console
1027    var entriesLen = aEntries.length;
1028    var thresholdMin = this.thresholdMin;
1029    if(isNaN(thresholdMin) || (thresholdMin > this.thresholdMax)) {
1030        thresholdMin = 0;
1031    }
1032    var entriesStartIndex = (entriesLen > thresholdMin) ? (entriesLen - thresholdMin) : 0;
1033   
1034    // Iterate through all log entries to print the ones that filter through
1035    var sourceFiltersLen = this._sourceFilters.length;
1036    var categoryFiltersLen = this._categoryFilters.length;
1037    for(var i=entriesStartIndex; i<entriesLen; i++) {
1038        var entry = aEntries[i];
1039        var category = entry.category;
1040        var source = entry.source;
1041        var sourceDetail = entry.sourceDetail;
1042        var okToPrint = false;
1043        var okToFilterCats = false;
1044
1045        for(var j=0; j<sourceFiltersLen; j++) {
1046            if(source == this._sourceFilters[j]) {
1047                okToFilterCats = true;
1048                break;
1049            }
1050        }
1051        if(okToFilterCats) {
1052            for(var k=0; k<categoryFiltersLen; k++) {
1053                if(category == this._categoryFilters[k]) {
1054                    okToPrint = true;
1055                    break;
1056                }
1057            }
1058        }
1059        if(okToPrint) {
1060            // To format for console, calculate the elapsed time
1061            // to be from the last item that passed through the filter,
1062            // not the absolute previous item in the stack
1063            var label = entry.category.substring(0,4).toUpperCase();
1064
1065            var time = entry.time;
1066            if (time.toLocaleTimeString) {
1067                var localTime  = time.toLocaleTimeString();
1068            }
1069            else {
1070                localTime = time.toString();
1071            }
1072
1073            var msecs = time.getTime();
1074            var startTime = YAHOO.widget.Logger.getStartTime();
1075            var totalTime = msecs - startTime;
1076            var elapsedTime = msecs - this._lastTime;
1077            this._lastTime = msecs;
1078
1079            var verboseOutput = (this.verboseOutput);
1080            var container = (verboseOutput) ? "CODE" : "PRE";
1081            var sourceAndDetail = (sourceDetail) ?
1082                source + " " + sourceDetail : source;
1083
1084            // Verbose uses code tag instead of pre tag (for wrapping)
1085            // and includes extra line breaks
1086            var output =  (verboseOutput) ?
1087                ["<p><span class='", category, "'>", label, "</span> ",
1088                totalTime, "ms (+", elapsedTime, ") ",
1089                localTime, ": ",
1090                "</p><p>",
1091                sourceAndDetail,
1092                ": </p><p>",
1093                this._HTML2Text(entry.msg),
1094                "</p>"] :
1095               
1096                ["<p><span class='", category, "'>", label, "</span> ",
1097                totalTime, "ms (+", elapsedTime, ") ",
1098                localTime, ": ",
1099                sourceAndDetail, ": ",
1100                this._HTML2Text(entry.msg),"</p>"];
1101
1102            var oNewElement = (this.newestOnTop) ?
1103                this._consoleEl.insertBefore(document.createElement(container),this._consoleEl.firstChild):
1104                this._consoleEl.appendChild(document.createElement(container));
1105
1106            oNewElement.innerHTML = output.join("");
1107            this._consoleMsgCount++;
1108        }
1109    }
1110};
1111
1112/**
1113 * Converts input chars "<", ">", and "&" to HTML entities.
1114 *
1115 * @private
1116 */
1117YAHOO.widget.LogReader.prototype._HTML2Text = function(html) {
1118    if(html) {
1119        return html.replace(/&/g, "&#38;").replace(/</g, "&#60;").replace(/>/g, "&#62;");
1120    }
1121    else return "";
1122};
1123
1124/***************************************************************************
1125 * Private event handlers
1126 ***************************************************************************/
1127/**
1128 * Handles Logger's categoryCreateEvent.
1129 *
1130 * @param {string} type The event
1131 * @param {array} args Data passed from event firer
1132 * @param {object} oSelf The log reader instance
1133 * @private
1134 */
1135YAHOO.widget.LogReader.prototype._onCategoryCreate = function(type, args, oSelf) {
1136    var category = args[0];
1137    if(oSelf._ftEl) {
1138        oSelf._createCategoryCheckbox(category);
1139    }
1140};
1141
1142/**
1143 * Handles Logger's sourceCreateEvent.
1144 *
1145 * @param {string} type The event
1146 * @param {array} args Data passed from event firer
1147 * @param {object} oSelf The log reader instance
1148 * @private
1149 */
1150YAHOO.widget.LogReader.prototype._onSourceCreate = function(type, args, oSelf) {
1151    var source = args[0];
1152    if(oSelf._ftEl) {
1153        oSelf._createSourceCheckbox(source);
1154    }
1155};
1156
1157/**
1158 * Handles check events on the category filter checkboxes.
1159 *
1160 * @param {event} v The click event
1161 * @param {object} oSelf The log reader instance
1162 * @private
1163 */
1164YAHOO.widget.LogReader.prototype._onCheckCategory = function(v, oSelf) {
1165    var newFilter = this.category;
1166    var filtersArray = oSelf._categoryFilters;
1167
1168    if(!this.checked) { // Remove category from filters
1169        for(var i=0; i<filtersArray.length; i++) {
1170            if(newFilter == filtersArray[i]) {
1171                filtersArray.splice(i, 1);
1172                break;
1173            }
1174        }
1175    }
1176    else { // Add category to filters
1177        filtersArray.push(newFilter);
1178    }
1179    oSelf._filterLogs();
1180};
1181
1182/**
1183 * Handles check events on the category filter checkboxes.
1184 *
1185 * @param {event} v The click event
1186 * @param {object} oSelf The log reader instance
1187 * @private
1188 */
1189YAHOO.widget.LogReader.prototype._onCheckSource = function(v, oSelf) {
1190    var newFilter = this.source;
1191    var filtersArray = oSelf._sourceFilters;
1192
1193    if(!this.checked) { // Remove category from filters
1194        for(var i=0; i<filtersArray.length; i++) {
1195            if(newFilter == filtersArray[i]) {
1196                filtersArray.splice(i, 1);
1197                break;
1198            }
1199        }
1200    }
1201    else { // Add category to filters
1202        filtersArray.push(newFilter);
1203    }
1204    oSelf._filterLogs();
1205};
1206
1207/**
1208 * Handles click events on the collapse button.
1209 *
1210 * @param {event} v The click event
1211 * @param {object} oSelf The log reader instance
1212 * @private
1213 */
1214YAHOO.widget.LogReader.prototype._onClickCollapseBtn = function(v, oSelf) {
1215    var btn = oSelf._collapseBtn;
1216    if(btn.value == "Expand") {
1217        oSelf._consoleEl.style.display = "block";
1218        if(oSelf._ftEl) {
1219            oSelf._ftEl.style.display = "block";
1220        }
1221        btn.value = "Collapse";
1222    }
1223    else {
1224        oSelf._consoleEl.style.display = "none";
1225        if(oSelf._ftEl) {
1226            oSelf._ftEl.style.display = "none";
1227        }
1228        btn.value = "Expand";
1229    }
1230};
1231
1232/**
1233 * Handles click events on the pause button.
1234 *
1235 * @param {event} v The click event
1236 * @param {object} oSelf The log reader instance
1237 * @private
1238 */
1239YAHOO.widget.LogReader.prototype._onClickPauseBtn = function(v, oSelf) {
1240    var btn = oSelf._pauseBtn;
1241    if(btn.value == "Resume") {
1242        oSelf.resume();
1243        btn.value = "Pause";
1244    }
1245    else {
1246        oSelf.pause();
1247        btn.value = "Resume";
1248    }
1249};
1250
1251/**
1252 * Handles click events on the clear button.
1253 *
1254 * @param {event} v The click event
1255 * @param {object} oSelf The log reader instance
1256 * @private
1257 */
1258YAHOO.widget.LogReader.prototype._onClickClearBtn = function(v, oSelf) {
1259    oSelf._clearConsole();
1260};
1261
1262/**
1263 * Handles Logger's newLogEvent.
1264 *
1265 * @param {string} type The newLog event
1266 * @param {array} args Data passed from event firer
1267 * @param {object} oSelf The log reader instance
1268 * @private
1269 */
1270YAHOO.widget.LogReader.prototype._onNewLog = function(type, args, oSelf) {
1271    var logEntry = args[0];
1272    oSelf._buffer.push(logEntry);
1273
1274    if (oSelf.logReaderEnabled === true && oSelf._timeout === null) {
1275        oSelf._timeout = setTimeout(function(){oSelf._printBuffer();}, 100);
1276    }
1277};
1278
1279/**
1280 * Handles Logger's resetEvent.
1281 *
1282 * @param {string} type The click event
1283 * @param {array} args Data passed from event firer
1284 * @param {object} oSelf The log reader instance
1285 * @private
1286 */
1287YAHOO.widget.LogReader.prototype._onReset = function(type, args, oSelf) {
1288    oSelf._filterLogs();
1289};
1290
Note: See TracBrowser for help on using the repository browser.